Completed
Push — master ( f6dfaa...d4ac13 )
by Ben
03:58
created

UrlParser::assertUrlExists()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.0625

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 0
dl 0
loc 6
ccs 3
cts 4
cp 0.75
crap 2.0625
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace Thinktomorrow\Locale\Services;
4
5
use Thinktomorrow\Locale\Locale;
6
7
class UrlParser
8
{
9
    /**
10
     * @var Locale
11
     */
12
    private $locale;
13
14
    /**
15
     * @var array
16
     */
17
    private $parsed;
18
19
    private $schemeless = false;
20
21 60
    public function __construct(Locale $locale)
22
    {
23 60
        $this->locale = $locale;
24 60
    }
25
26 60
    public function set($url)
27
    {
28 60
        $this->parsed = parse_url($url);
0 ignored issues
show
Documentation Bug introduced by
It seems like parse_url($url) can also be of type false. However, the property $parsed is declared as type array. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
29
30 60
        if(false === $this->parsed)
31 37
        {
32 3
            throw new \InvalidArgumentException('Failed to parse url. Invalid url ['.$url.'] passed as parameter.');
33
        }
34
35
        // If a schemeless url is passed, parse_url will ignore this and strip the first tags
36 57
        $this->schemeless = (0 === strpos($url,'//') && isset($this->parsed['host']));
37
38 57
        return $this;
39
    }
40
41 57
    public function get()
42
    {
43 57
        $this->assertUrlExists();
44
45 57
        return $this->reassemble($this->parsed);
46
    }
47
48
    /**
49
     * Place locale segment in front of url path
50
     * e.g. /foo/bar is transformed into /en/foo/bar
51
     *
52
     * @param null $locale
53
     * @return string
54
     */
55 54
    public function localize($locale = null)
56
    {
57 54
        $this->localizePath($locale);
58
59 54
        return $this;
60
    }
61
62 54
    private function localizePath($locale = null)
63
    {
64 54
        $this->assertUrlExists();
65
66 54
        $this->parsed['path'] = str_replace('//','/',
67 54
            '/'.$this->locale->getSlug($locale).$this->delocalizePath()
68 33
        );
69 54
    }
70
71
    /**
72
     * @return array
73
     */
74 54
    private function delocalizePath()
75
    {
76 54
        $this->assertUrlExists();
77
78 54
        if (!isset($this->parsed['path'])) return null;
79
80 54
        $path_segments = explode('/', trim($this->parsed['path'], '/'));
81
82 54
        if (count($path_segments) < 1) return null;
83
84 54
        if ($path_segments[0] == $this->locale->getSlug($path_segments[0]) || $this->locale->isHidden($path_segments[0])) {
85 21
            unset($path_segments[0]);
86 13
        }
87
88 54
        return '/' . implode('/', $path_segments);
89
    }
90
91
    /**
92
     * Construct a full url with the parsed url elements
93
     * resulted from a parse_url() function call
94
     *
95
     * @param array $parsed
96
     * @return string
97
     */
98 57
    private function reassemble(array $parsed)
99
    {
100
        return
101 57
            ((isset($parsed['scheme'])) ? $parsed['scheme'] . '://' : ($this->schemeless ? '//' : ''))
102 57
            .((isset($parsed['user'])) ? $parsed['user'] . ((isset($parsed['pass'])) ? ':' . $parsed['pass'] : '') .'@' : '')
103 57
            .((isset($parsed['host'])) ? $parsed['host'] : '')
104 57
            .((isset($parsed['port'])) ? ':' . $parsed['port'] : '')
105 57
            .((isset($parsed['path'])) ? $parsed['path'] : '')
106 57
            .((isset($parsed['query'])) ? '?' . $parsed['query'] : '')
107 57
            .((isset($parsed['fragment'])) ? '#' . $parsed['fragment'] : '');
108
    }
109
110 57
    private function assertUrlExists()
111
    {
112 57
        if (!$this->parsed) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->parsed of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
113
            throw new \LogicException('Url is required. Please run UrlParser::set($url) first.');
114
        }
115
    }
116
}