Last active
August 14, 2016 14:43
-
-
Save mylk/9a6fe3eaacb605b31aaa7808ac6e6dab to your computer and use it in GitHub Desktop.
A converter of URL to URL with "campaign" query parameters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* PHPUnit test suite available at: | |
* https://gist.github.com/mylk/33e3d0e49152cf6b74362dc8a09b9d39 | |
*/ | |
/* | |
* Installation (Symfony): | |
* ======================= | |
* # services.yml | |
* services: | |
* # ... | |
* acme.url_campaign_builder: | |
* class: Acme\AcmeBundle\Service\UrlCampaignBuilderService | |
* | |
* Usage (Symfony): | |
* ================ | |
* $campaignParameters = array( | |
* "source" => "newsletter", | |
* "medium" => "email", | |
* "campaign" => "august" | |
* ); | |
* | |
* $urlCampaignBuilder = $this->get("acme.url_campaign_builder"); | |
* $urlCampaigned = $urlCampaignBuilder->build("http://www.google.com", $campaignParameters); | |
*/ | |
namespace Acme\AcmeBundle\Service; | |
class UrlCampaignBuilderService | |
{ | |
/** | |
* Builds a campaign URL and addresses some cases. | |
* | |
* @param string $url | |
* @param array $parameters Usually one of "source", "medium", "campaign" but can be anything | |
* | |
* @return string|null | |
*/ | |
public function build($url, $parameters) | |
{ | |
if (!$url) { | |
return null; | |
} | |
$urlParsed = \parse_url($url); | |
// if no scheme exists (http) the "host" by default is placed in "path" | |
if (!isset($urlParsed["host"])) { | |
$urlParsed["host"] = $urlParsed["path"]; | |
$urlParsed["path"] = "/"; | |
} | |
if (!isset($urlParsed["scheme"])) { | |
$urlParsed["scheme"] = "http"; | |
} | |
if (!isset($urlParsed["path"])) { | |
$urlParsed["path"] = "/"; | |
} | |
if (!isset($urlParsed["query"])) { | |
$urlParsed["query"] = ""; | |
} else { | |
$urlParsed["query"] .= "&"; | |
} | |
$campaignParameters = ""; | |
foreach ($parameters as $parameterKey => $parameterValue) { | |
$campaignParameters .= \sprintf("&utm_%s=%s", $parameterKey, $parameterValue); | |
} | |
// remove the first "&" character | |
$campaignParameters = \substr($campaignParameters, 1, \strlen($campaignParameters) - 1); | |
// append to the original query | |
$urlParsed["query"] .= $campaignParameters; | |
$urlWithCampaign = \sprintf("%s://%s%s?%s", $urlParsed["scheme"], $urlParsed["host"], $urlParsed["path"], $urlParsed["query"]); | |
return $urlWithCampaign; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment