Bin will be removed on June 1, 2014 in favor of http://gist.github.com. Please save all your pastes before then. So long, and thanks for all the fish!×
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
<?php
App::uses('CakeRoute', 'Routing/Route');
class SubdomainRoute extends CakeRoute {
 
/**
 * @var CakeRequest
 */
    private $Request;
 
/**
 * Length of domain's TLD
 *
 * @var int
 */
    public static $_tldLength = 1;
 
/**
 * Constructor for a Route
 *
 * @param string $template Template string with parameter placeholders
 * @param array $defaults Array of defaults for the route.
 * @param array $options Array of additional options for the Route
 */
    public function __construct($template, $defaults = array(), $options = array()) {
        parent::__construct($template, $defaults, $options);
 
        $this->Request = new CakeRequest();
        $this->options = array_merge(array('protocol' => 'http', 'subdomain' => 'www'), $options);
    }
 
/**
 * Sets tld length
 *
 * @param $length
 * @return mixed void|int
 */
    public static function tldLength($length = null) {
        if (is_null($length)) {
            return self::$_tldLength;
        }
 
        self::$_tldLength = $length;
    }
 
/**
 * Parses the current url and only returns route if the current subdomain is the one specified
 *
 * @param $url
 * @return bool|mixed
 */
    public function parse($url) {
        $route = parent::parse($url);
 
        if ($route) {
            $subdomains = $this->_getSubdomains();
            $subdomain = $this->options['subdomain'];
 
            if (
                (empty($subdomains) && $subdomain == 'www') ||
                (in_array($this->options['subdomain'], $subdomains))
            ) {
                return $route;
            }
        }
 
        return false;
    }
 
/**
 * Writes out full url with protocol and subdomain
 *
 * @param $params
 * @return string
 */
    protected function _writeUrl($params) {
        $protocol = $this->options['protocol'];
        $subdomain = $this->options['subdomain'];
        $domain = $this->_getDomain();
        $url = parent::_writeUrl($params);
 
        return "{$protocol}://{$subdomain}.{$domain}{$url}";
    }
 
/**
 * Gets list of subdomains from current URL
 *
 * @return array Of subdomains
 */
    protected function _getSubdomains() {
        return $this->Request->subdomains(self::$_tldLength);
    }
 
/**
 * Get domain name
 *
 * @return string
 */
    protected function _getDomain() {
        return $this->Request->domain(self::$_tldLength);
    }
}