Passed
Push — master ( 9aeb56...0cd590 )
by Mikael
34s
created

Url::createRelative()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 19
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 19
ccs 7
cts 7
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 7
nc 3
nop 1
crap 3
1
<?php
2
3
namespace Anax\Url;
4
5
use Anax\Uri\Uri;
6
7
/**
8
 * A helper to create urls.
9
 *
10
 */
11
class Url implements \Anax\Configure\ConfigureInterface
12
{
13
    use \Anax\Configure\ConfigureTrait;
14
15
16
17
    /**
18
     * @const URL_CLEAN  controller/action/param1/param2
19
     * @const URL_APPEND index.php/controller/action/param1/param2
20
     * @var   $urlType   What type of urls to generate, select from
21
     *                   URL_CLEAN or URL_APPEND.
22
     */
23
    const URL_CLEAN  = 'clean';
24
    const URL_APPEND = 'append';
25
    private $urlType = self::URL_APPEND;
26
27
28
29
    /**
30
     * @var $siteUrl    Siteurl to prepend to all absolute urls created.
31
     * @var $baseUrl    Baseurl to prepend to all relative urls created.
32
     * @var $scriptName Name of the frontcontroller script.
33
     */
34
    private $siteUrl;
35
    private $baseUrl;
36
    private $scriptName;
37
38
39
40
    /**
41
     * @var $staticSiteUrl    Siteurl to prepend to all absolute urls for
42
     *                        assets.
43
     * @var $staticBaseUrl    Baseurl to prepend to all relative urls for
44
     *                        assets.
45
     */
46
    private $staticSiteUrl;
47
    private $staticBaseUrl;
48
49
50
    /**
51
     * Constructor
52
     */
53 49
    public function __construct()
54
    {
55 49
        $this->siteUrl = new Uri("");
56 49
        $this->baseUrl = new Uri("");
57 49
        $this->scriptName = new Uri("");
58 49
        $this->staticSiteUrl = new Uri("");
59 49
        $this->staticBaseUrl = new Uri("");
60 49
    }
61
62
63
64
    /**
65
     * Set default values from configuration.
66
     *
67
     * @param mixed $configSource optional config source.
68
     *
69
     * @return self
70
     */
71 1
    public function setDefaultsFromConfiguration($configSource = null)
72
    {
73 1
        $config = is_null($configSource)
74 1
            ? $this->config
75 1
            : $this->configure($configSource)->config;
76
77 1
        foreach ($config as $key => $value) {
78
            switch ($key) {
79 1
                case "urlType":
80 1
                    $this->setUrlType($value);
81 1
                    break;
82 1
                case "siteUrl":
83 1
                case "baseUrl":
84 1
                case "staticSiteUrl":
85 1
                case "staticBaseUrl":
86 1
                case "scriptName":
87 1
                    $this->$key = new Uri($value);
88 1
                    break;
89
            }
90 1
        }
91
92 1
        return $this;
93
    }
94
95
96
97
    /**
98
     * Create an url and prepending the baseUrl.
99
     *
100
     * @param string $uri     part of uri to use when creating an url.
101
     *                        empty means baseurl to current
102
     *                        frontcontroller.
103
     * @param string $baseuri optional base to prepend uri.
104
     *
105
     * @return string as resulting url.
106
     */
107 30
    public function create($uri = "", $baseuri = "")
108
    {
109 30
        $uri = new Uri($uri);
110 30
        $baseuri = new Uri($baseuri);
111
112
        /**
113
         * Cases with quick return
114
         */
115 30
        if ($uri->startsWith("http://", "https://", "//")) {
116
            /** Fully qualified, just leave as is. */
117 1
            return $uri->uri();
118
        }
119
120 29
        if ($uri->startsWith("#", "?")) {
121
            /** Hashtag url to local page, or query part, leave as is. */
122 6
            return $uri->uri();
123
        }
124
125 23
        if ($uri->startsWith("mailto:") || substr(html_entity_decode($uri->uri()), 0, 7) == "mailto:") {
126
            /**
127
             * Leave mailto links as is
128
             *
129
             * The odd fix is for markdown converting mailto: to UTF-8
130
             * Might be a better way to solve this...
131
             */
132 1
            return $uri->uri();
133
        }
134
135 22
        if ($uri->startsWith("/")) {
136
            /** Absolute url, prepend with siteUrl. */
137 7
            return $uri->prepend($this->siteUrl)->uri();
138
        }
139
140
        /**
141
         * Other cases
142
         */
143
144
        /** Remove the trailing 'index' part of the url. */
145 16
        $uri->removeBasename("index");
146
147 16
        if ($this->urlType != self::URL_CLEAN) {
148 6
            $uri->prepend($this->scriptName);
149 6
        }
150
151
        return $uri
152 16
            ->prepend($baseuri)
153 16
            ->prepend($this->baseUrl)
154 16
            ->uri();
155
    }
156
157
158
159
    /**
160
     * Create an url and prepend the baseUrl to the directory of
161
     * the frontcontroller.
162
     *
163
     * @param string $uri part of uri to use when creating an url.
164
     *                    empty means baseurl to directory of
165
     *                    the current frontcontroller.
166
     *
167
     * @return string as resulting url.
168
     */
169 6
    public function createRelative($uri = "")
170
    {
171 6
        $uri = new Uri($uri);
172
173
        /**
174
         * Catch early returns
175
         */
176 6
        if ($uri->startsWith("http://", "https://", "//")) {
177
            /** Fully qualified, return as is */
178 4
            return $uri->uri();
179
        }
180
181 2
        if ($uri->startsWith("/")) {
182
            /** Absolute url, prepend with siteUrl */
183 1
            return $uri->prepend($this->siteUrl)->uri();
184
        }
185
186 1
        return $uri->prepend($this->baseUrl)->uri();
187
    }
188
189
190
191
    /**
192
     * Create an url for a static asset.
193
     *
194
     * @param string $uri part of uri to use when creating an url.
195
     *
196
     * @return string as resulting url.
197
     */
198 15
    public function asset($uri = "")
199
    {
200 15
        $uri = new Uri($uri);
201
202
        /**
203
         * Catch early returns
204
         */
205 15
        if ($uri->startsWith("http://", "https://", "//")) {
206
            /** Fully qualified, return as is */
207 8
            return $uri->uri();
208
        }
209
210 7
        if ($uri->startsWith("/")) {
211
            /** Absolute url, prepend with staticSiteUrl */
212 4
            return $uri->prepend($this->staticSiteUrl)->uri();
213
        }
214
215 4
        $baseUrl = $this->staticBaseUrl->isEmpty()
216 4
            ? $this->baseUrl
217 4
            : $this->staticBaseUrl;
218
219 4
        return $uri->prepend($baseUrl)->uri();
220
    }
221
222
223
224
    /**
225
     * Set the siteUrl to prepend all absolute urls created.
226
     *
227
     * @param string $url part of url to use when creating an url.
228
     *
229
     * @return self
230
     */
231 35
    public function setSiteUrl($url)
232
    {
233 35
        $this->siteUrl = new Uri($url);
234 35
        return $this;
235
    }
236
237
238
239
    /**
240
     * Set the baseUrl to prepend all relative urls created.
241
     *
242
     * @param string $url part of url to use when creating an url.
243
     *
244
     * @return self
245
     */
246 39
    public function setBaseUrl($url)
247
    {
248 39
        $this->baseUrl = new Uri($url);
249 39
        return $this;
250
    }
251
252
253
254
    /**
255
     * Set the siteUrl to prepend absolute urls for assets.
256
     *
257
     * @param string $url part of url to use when creating an url.
258
     *
259
     * @return self
260
     */
261 10
    public function setStaticSiteUrl($url)
262
    {
263 10
        $this->staticSiteUrl = new Uri($url);
264 10
        return $this;
265
    }
266
267
268
269
    /**
270
     * Set the baseUrl to prepend relative urls for assets.
271
     *
272
     * @param string $url part of url to use when creating an url.
273
     *
274
     * @return self
275
     */
276 10
    public function setStaticBaseUrl($url)
277
    {
278 10
        $this->staticBaseUrl = new Uri($url);
279 10
        return $this;
280
    }
281
282
283
284
    /**
285
     * Set the scriptname to use when creating URL_APPEND urls.
286
     *
287
     * @param string $name as the scriptname, for example index.php.
288
     *
289
     * @return self
290
     */
291 11
    public function setScriptName($name)
292
    {
293 11
        $this->scriptName = new Uri($name);
294 11
        return $this;
295
    }
296
297
298
299
    /**
300
     * Set the type of urls to be generated, URL_CLEAN, URL_APPEND.
301
     *
302
     * @param string $type what type of urls to create.
303
     *
304
     * @return self
305
     *
306
     * @throws Exception
307
     */
308 31
    public function setUrlType($type)
309
    {
310 31
        if (!in_array($type, [self::URL_APPEND, self::URL_CLEAN])) {
311 1
            throw new Exception("Unsupported Url type.");
312
        }
313
314 30
        $this->urlType = $type;
315 30
        return $this;
316
    }
317
318
319
320
    /**
321
     * Create a slug of a string, to be used as url.
322
     *
323
     * @param string $str the string to format as slug.
324
     *
325
     * @return string the formatted slug.
326
     */
327 4
    public function slugify($str)
328
    {
329 4
        $str = mb_strtolower(trim($str));
330 4
        $str = str_replace(array('å','ä','ö'), array('a','a','o'), $str);
331 4
        $str = preg_replace('/[^a-z0-9-]/', '-', $str);
332 4
        $str = trim(preg_replace('/-+/', '-', $str), '-');
333 4
        return $str;
334
    }
335
}
336