Completed
Push — master ( d4ac13...53915c )
by Ben
04:13
created

UrlParser::reassemble()   C

Complexity

Conditions 10
Paths 512

Size

Total Lines 11
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 10

Importance

Changes 0
Metric Value
cc 10
eloc 9
nc 512
nop 1
dl 0
loc 11
ccs 8
cts 8
cp 1
crap 10
rs 5.7204
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Thinktomorrow\Locale\Parsers;
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 96
    public function __construct(Locale $locale)
22
    {
23 96
        $this->locale = $locale;
24 96
    }
25
26 90
    public function set($url)
27
    {
28 90
        $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 90
        if(false === $this->parsed)
31 57
        {
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
        // so we keep a reminder to explicitly reassemble the 'anonymous scheme' manually
37 87
        $this->schemeless = (0 === strpos($url,'//') && isset($this->parsed['host']));
38
39 87
        return $this;
40
    }
41
42 87
    public function get()
43
    {
44 87
        $this->assertUrlExists();
45
46 87
        return $this->reassemble($this->parsed);
47
    }
48
49
    /**
50
     * Place locale segment in front of url path
51
     * e.g. /foo/bar is transformed into /en/foo/bar
52
     *
53
     * @param null $locale
54
     * @return string
55
     */
56 87
    public function localize($locale = null)
57
    {
58 87
        $this->localizePath($locale);
59
60 84
        return $this;
61
    }
62
63 87
    private function localizePath($locale = null)
64
    {
65 87
        $this->assertUrlExists();
66
67 84
        $this->parsed['path'] = str_replace('//','/',
68 84
            '/'.$this->locale->getSlug($locale).$this->delocalizePath()
69 53
        );
70 84
    }
71
72
    /**
73
     * @return array
74
     */
75 84
    private function delocalizePath()
76
    {
77 84
        $this->assertUrlExists();
78
79 84
        if (!isset($this->parsed['path'])) return null;
80
81 84
        $path_segments = explode('/', trim($this->parsed['path'], '/'));
82
83 84
        if (count($path_segments) < 1) return null;
84
85 84
        if ($path_segments[0] == $this->locale->getSlug($path_segments[0]) || $this->locale->isHidden($path_segments[0])) {
86 30
            unset($path_segments[0]);
87 19
        }
88
89 84
        return '/' . implode('/', $path_segments);
90
    }
91
92
    /**
93
     * Construct a full url with the parsed url elements
94
     * resulted from a parse_url() function call
95
     *
96
     * @param array $parsed
97
     * @return string
98
     */
99 87
    private function reassemble(array $parsed)
100
    {
101
        return
102 87
            ((isset($parsed['scheme'])) ? $parsed['scheme'] . '://' : ($this->schemeless ? '//' : ''))
103 87
            .((isset($parsed['user'])) ? $parsed['user'] . ((isset($parsed['pass'])) ? ':' . $parsed['pass'] : '') .'@' : '')
104 87
            .((isset($parsed['host'])) ? $parsed['host'] : '')
105 87
            .((isset($parsed['port'])) ? ':' . $parsed['port'] : '')
106 87
            .((isset($parsed['path'])) ? $parsed['path'] : '')
107 87
            .((isset($parsed['query'])) ? '?' . $parsed['query'] : '')
108 87
            .((isset($parsed['fragment'])) ? '#' . $parsed['fragment'] : '');
109
    }
110
111 90
    private function assertUrlExists()
112
    {
113 90
        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...
114 3
            throw new \LogicException('Url is required. Please run UrlParser::set($url) first.');
115
        }
116
    }
117
}