Completed
Push — master ( 0cd590...7bcb43 )
by Mikael
02:33
created

Url::createRelative()   B

Complexity

Conditions 6
Paths 4

Size

Total Lines 19
Code Lines 11

Duplication

Lines 13
Ratio 68.42 %

Code Coverage

Tests 7
CRAP Score 8.6047

Importance

Changes 0
Metric Value
dl 13
loc 19
ccs 7
cts 12
cp 0.5833
rs 8.8571
c 0
b 0
f 0
cc 6
eloc 11
nc 4
nop 1
crap 8.6047
1
<?php
2
3
namespace Anax\Url;
4
5
/**
6
 * A helper to create urls.
7
 *
8
 */
9
class Url implements \Anax\Common\ConfigureInterface
10
{
11
    use \Anax\Common\ConfigureTrait;
12
13
14
15
    /**
16
     * @const URL_CLEAN  controller/action/param1/param2
17
     * @const URL_APPEND index.php/controller/action/param1/param2
18
     * @var   $urlType   What type of urls to generate, select from
19
     *                   URL_CLEAN or URL_APPEND.
20
     */
21
    const URL_CLEAN  = 'clean';
22
    const URL_APPEND = 'append';
23
    private $urlType = self::URL_APPEND;
24
25
26
27
    /**
28
     * @var $siteUrl    Siteurl to prepend to all absolute urls created.
29
     * @var $baseUrl    Baseurl to prepend to all relative urls created.
30
     * @var $scriptName Name of the frontcontroller script.
31
     */
32
    private $siteUrl = null;
33
    private $baseUrl = null;
34
    private $scriptName = null;
35
36
37
38
    /**
39
     * @var $staticSiteUrl    Siteurl to prepend to all absolute urls for
40
     *                        assets.
41
     * @var $staticBaseUrl    Baseurl to prepend to all relative urls for
42
     *                        assets.
43
     */
44
    private $staticSiteUrl = null;
45
    private $staticBaseUrl = null;
46
47
48
49
    /**
50
     * Set default values from configuration.
51
     *
52
     * @return this.
0 ignored issues
show
Documentation introduced by
The doc-type this. could not be parsed: Unknown type name "this." at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
53
     */
54
    public function setDefaultsFromConfiguration()
55
    {
56
        $set = [
57
            "urlType",
58
            "siteUrl",
59
            "baseUrl",
60
            "staticSiteUrl",
61
            "staticBaseUrl",
62
            "scriptName",
63
        ];
64
        
65
        foreach ($set as $item) {
66
            if (!isset($this->config[$item])) {
67
                continue;
68
            }
69
            
70
            $this->$item = $this->config[$item];
71
        }
72
73
        return $this;
74
    }
75
76
77
78
    /**
79
     * Create an url and prepending the baseUrl.
80
     *
81
     * @param string $uri     part of uri to use when creating an url.
82
     *                        "" or null means baseurl to current
83
     *                        frontcontroller.
84
     * @param string $baseuri optional base to prepend uri.
85
     *
86
     * @return string as resulting url.
87
     */
88 27
    public function create($uri = null, $baseuri = null)
89
    {
90 27
        if (empty($uri) && empty($baseuri)) {
91
            // Empty uri means baseurl
92 2
            return $this->baseUrl
93 2
                . (($this->urlType == self::URL_APPEND)
94 2
                    ? "/$this->scriptName"
95 2
                    : null);
96 25
        } elseif (empty($uri)) {
97
            // Empty uri means baseurl with appended $baseuri
98
            ;
99 25
        } elseif (substr($uri, 0, 7) == "http://"
100 24
            || substr($uri, 0, 8) == "https://"
101 24
            || substr($uri, 0, 2) == "//"
102 24
        ) {
103
            // Fully qualified, just leave as is.
104
            return rtrim($uri, "/");
105 24
        } elseif ($uri[0] == "/") {
106
            // Absolute url, prepend with siteUrl
107 6
            return rtrim($this->siteUrl . rtrim($uri, '/'), '/');
108 18
        } elseif ($uri[0] == "#"
109 18
            || $uri[0] == "?"
110 18
        ) {
111
            // Hashtag url to local page, or query part, leave as is.
112 6
            return $uri;
113 12
        } elseif (substr($uri, 0, 7) == "mailto:"
114 12
            || substr(html_entity_decode($uri), 0, 7) == "mailto:") {
115
            // Leave mailto links as is
116
            // The odd fix is for markdown converting mailto: to UTF-8
117
            // Might be a better way to solve this...
118
            return $uri;
119
        }
120
121
        // Prepend uri with baseuri
122 13
        $uri = rtrim($uri, "/");
123 13
        if (!empty($baseuri)) {
124 5
            $uri = rtrim($baseuri, "/") . "/$uri";
125 5
        }
126
127
        // Remove the trailing index part of the url
128 13
        if (basename($uri) == "index") {
129
            $uri = dirname($uri);
130
        }
131
132 13
        if ($this->urlType == self::URL_CLEAN) {
133 9
            return rtrim($this->baseUrl . "/" . $uri, "/");
134
        } else {
135 4
            return rtrim($this->baseUrl . "/" . $this->scriptName . "/" . $uri, "/");
136
        }
137
    }
138
139
140
141
    /**
142
     * Create an url and prepend the baseUrl to the directory of
143
     * the frontcontroller.
144
     *
145
     * @param string $uri part of uri to use when creating an url.
146
     *                    "" or null means baseurl to directory of
147
     *                    the current frontcontroller.
148
     *
149
     * @return string as resulting url.
150
     */
151 4
    public function createRelative($uri = null)
152
    {
153 4 View Code Duplication
        if (empty($uri)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
154
            // Empty uri means baseurl
155
            return $this->baseUrl;
156 4
        } elseif (substr($uri, 0, 7) == "http://"
157 4
            || substr($uri, 0, 8) == "https://"
158 2
            || substr($uri, 0, 2) == "//"
159 4
        ) {
160
            // Fully qualified, just leave as is.
161 4
            return rtrim($uri, '/');
162
        } elseif ($uri[0] == '/') {
163
            // Absolute url, prepend with siteUrl
164
            return rtrim($this->siteUrl . rtrim($uri, '/'), '/');
165
        }
166
167
        $uri = rtrim($uri, '/');
168
        return $this->baseUrl . '/' . $uri;
169
    }
170
171
172
173
    /**
174
     * Create an url for a static asset.
175
     *
176
     * @param string $uri part of uri to use when creating an url.
177
     *
178
     * @return string as resulting url.
179
     */
180 12
    public function asset($uri = null)
181
    {
182 12 View Code Duplication
        if (empty($uri)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
183
            // Allow empty
184 12
        } elseif (substr($uri, 0, 7) == "http://"
185 12
            || substr($uri, 0, 8) == "https://"
186 8
            || substr($uri, 0, 2) == "//"
187 12
        ) {
188
            // Fully qualified, just leave as is.
189 8
            return rtrim($uri, '/');
190 4
        } elseif ($uri[0] == '/') {
191
            // Absolute url, prepend with staticSiteUrl
192 2
            return rtrim($this->staticSiteUrl . rtrim($uri, '/'), '/');
193
        }
194
195 2
        $baseUrl = isset($this->staticBaseUrl)
196 2
            ? $this->staticBaseUrl
197 2
            : $this->baseUrl;
198
199 2
        return empty($uri)
200 2
            ? $baseUrl
201 2
            : $baseUrl . '/' . $uri;
202
    }
203
204
205
206
    /**
207
     * Set the siteUrl to prepend all absolute urls created.
208
     *
209
     * @param string $url part of url to use when creating an url.
210
     *
211
     * @return self
212
     */
213 31
    public function setSiteUrl($url)
214
    {
215 31
        $this->siteUrl = rtrim($url, '/');
216 31
        return $this;
217
    }
218
219
220
221
    /**
222
     * Set the baseUrl to prepend all relative urls created.
223
     *
224
     * @param string $url part of url to use when creating an url.
225
     *
226
     * @return self
227
     */
228 35
    public function setBaseUrl($url)
229
    {
230 35
        $this->baseUrl = rtrim($url, '/');
231 35
        return $this;
232
    }
233
234
235
236
    /**
237
     * Set the siteUrl to prepend absolute urls for assets.
238
     *
239
     * @param string $url part of url to use when creating an url.
240
     *
241
     * @return self
242
     */
243 8
    public function setStaticSiteUrl($url)
244
    {
245 8
        $this->staticSiteUrl = rtrim($url, '/');
246 8
        return $this;
247
    }
248
249
250
251
    /**
252
     * Set the baseUrl to prepend relative urls for assets.
253
     *
254
     * @param string $url part of url to use when creating an url.
255
     *
256
     * @return self
257
     */
258 8
    public function setStaticBaseUrl($url)
259
    {
260 8
        $this->staticBaseUrl = rtrim($url, '/');
261 8
        return $this;
262
    }
263
264
265
266
    /**
267
     * Set the scriptname to use when creating URL_APPEND urls.
268
     *
269
     * @param string $name as the scriptname, for example index.php.
270
     *
271
     * @return self
272
     */
273 9
    public function setScriptName($name)
274
    {
275 9
        $this->scriptName = $name;
276 9
        return $this;
277
    }
278
279
280
281
    /**
282
     * Set the type of urls to be generated, URL_CLEAN, URL_APPEND.
283
     *
284
     * @param string $type what type of urls to create.
285
     *
286
     * @return self
287
     *
288
     * @throws Anax\Url\Exception
289
     */
290 28
    public function setUrlType($type)
291
    {
292 28
        if (!in_array($type, [self::URL_APPEND, self::URL_CLEAN])) {
293 1
            throw new Exception("Unsupported Url type.");
294
        }
295
296 27
        $this->urlType = $type;
297 27
        return $this;
298
    }
299
300
301
302
    /**
303
     * Create a slug of a string, to be used as url.
304
     *
305
     * @param string $str the string to format as slug.
306
     *
307
     * @return str the formatted slug.
308
     */
309
    public function slugify($str)
310
    {
311
        $str = mb_strtolower(trim($str));
312
        $str = str_replace(array('å','ä','ö'), array('a','a','o'), $str);
313
        $str = preg_replace('/[^a-z0-9-]/', '-', $str);
314
        $str = trim(preg_replace('/-+/', '-', $str), '-');
315
        return $str;
316
    }
317
}
318