Passed
Push — master ( 103cdb...e9fd84 )
by Mikael
02:04
created

Url::setDefaultsFromConfiguration()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

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