1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* Usage: |
5
|
|
|
* $myAnswer = |
6
|
|
|
* CountryPrice_Translation::get_country_url_provider() |
7
|
|
|
* ->doSomething(....); |
8
|
|
|
* |
9
|
|
|
*/ |
10
|
|
|
|
11
|
|
|
class CountryURLProvider extends Object implements CountryURLProviderInterface |
|
|
|
|
12
|
|
|
{ |
13
|
|
|
private static $country_segments = array('nz', 'au', 'gb', 'eu', 'us', 'row'); |
|
|
|
|
14
|
|
|
|
15
|
|
|
public function hasCountrySegment($url = ''){ |
16
|
|
|
$url = $this->getDefaultURL($url); |
17
|
|
|
$parsedUrl = parse_url($url); |
18
|
|
|
$pathSegments = explode("/", $parsedUrl['path']); |
19
|
|
|
$firstSegment = ''; |
20
|
|
|
$countries = Config::inst()->get('CountryURLProvider', 'country_segments'); |
21
|
|
|
foreach ($pathSegments as $position => $segment){ |
22
|
|
|
if($segment){ |
23
|
|
|
$firstSegment = $segment; |
24
|
|
|
break; |
25
|
|
|
} |
26
|
|
|
} |
27
|
|
|
if(in_array($firstSegment, $countries)){ |
|
|
|
|
28
|
|
|
return true; |
29
|
|
|
} |
30
|
|
|
return false; |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
public function replaceCountryCodeInUrl($countryCode, $url = ''){ |
34
|
|
|
$url = $this->getDefaultURL($url); |
35
|
|
|
$parsedUrl = parse_url($url); |
36
|
|
|
$pathParts = explode('/', $parsedUrl['path']); |
37
|
|
|
$countries = Config::inst()->get('CountryURLProvider', 'country_segments'); |
38
|
|
|
foreach($pathParts as $pathPartsKey => $pathPart) { |
39
|
|
|
//check for first match |
40
|
|
|
if(in_array($pathPart, $countries)) { |
41
|
|
|
$pathParts[$pathPartsKey] = strtolower($countryCode); |
42
|
|
|
break; |
43
|
|
|
} |
44
|
|
|
} |
45
|
|
|
$parsedUrl['path'] = implode('/', $pathParts); |
46
|
|
|
$url = $parsedUrl['scheme']. '://'. $parsedUrl['host']. $parsedUrl['path']; |
47
|
|
|
if(isset($parsedUrl['query'])){ |
48
|
|
|
$url = $url . $parsedUrl['query']; |
49
|
|
|
} |
50
|
|
|
return $url; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
public function addCountryCodeToUrl($countryCode, $url = ''){ |
54
|
|
|
$url = $this->getDefaultURL($url); |
55
|
|
|
$parsedUrl = parse_url($url); |
56
|
|
|
$url = $parsedUrl['scheme']. '://'. $parsedUrl['host']. '/'. strtolower($countryCode) . $parsedUrl['path']; |
57
|
|
|
if(isset($parsedUrl['query'])){ |
58
|
|
|
$url = $url . $parsedUrl['query']; |
59
|
|
|
} |
60
|
|
|
return $url; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
private function getDefaultURL($url = '') |
|
|
|
|
64
|
|
|
{ |
65
|
|
|
if($url) { |
66
|
|
|
return Director::absoluteURL($url); |
67
|
|
|
} |
68
|
|
|
return (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
} |
72
|
|
|
|
You can fix this by adding a namespace to your class:
When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.