Completed
Pull Request — master (#16)
by Sergii
05:00
created

Url::__construct()   B

Complexity

Conditions 5
Paths 3

Size

Total Lines 14
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
dl 0
loc 14
rs 8.8571
c 1
b 0
f 1
cc 5
eloc 6
nc 3
nop 2
1
<?php
2
/**
3
 * @author Sergii Bondarenko, <[email protected]>
4
 */
5
namespace Drupal\TqExtension\Utils;
6
7
class Url
8
{
9
    /**
10
     * URL to build.
11
     *
12
     * @var string
13
     */
14
    private $url = '';
15
    /**
16
     * URL components.
17
     *
18
     * @var string[]
19
     */
20
    private $components = [];
21
22
    /**
23
     * Url constructor.
24
     *
25
     * @param string $baseUrl
26
     *   Base URL.
27
     * @param string $path
28
     *   Path on a base URL.
29
     */
30
    public function __construct($baseUrl, $path = '')
31
    {
32
        // @todo Check URL validity.
33
        if (empty($baseUrl)) {
34
            throw new \RuntimeException('Set base URL before continue.');
35
        }
36
37
        // Start with base URL when path is empty, or not starts from "//" or "http".
38
        if (empty($path) || strpos($path, '//') !== 0 && strpos($path, 'http') !== 0) {
39
            $path = rtrim($baseUrl, '/') . '/' . trim($path, '/');
40
        }
41
42
        $this->setUrl($path)->scheme()->credentials()->host()->components();
43
    }
44
45
    /**
46
     * @return string
47
     *   Constructed URL.
48
     */
49
    public function __toString()
50
    {
51
        return $this->url;
52
    }
53
54
    /**
55
     * Initialize URL creation.
56
     *
57
     * @param string $url
58
     *
59
     * @return $this
60
     */
61
    private function setUrl($url)
62
    {
63
        $this->url = $url;
64
        $this->components = parse_url(strtolower($this->url));
1 ignored issue
show
Documentation Bug introduced by
It seems like parse_url(strtolower($this->url)) can also be of type false. However, the property $components is declared as type array<integer,string>. 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...
65
66
        if (false === $this->components || !isset($this->components['host'])) {
67
            throw new \InvalidArgumentException(sprintf('%s - incorrect URL.', $this->url));
68
        }
69
70
        return $this;
71
    }
72
73
    /**
74
     * Append HTTP scheme.
75
     *
76
     * @return $this
77
     */
78
    private function scheme()
79
    {
80
        $this->components += [
81
            // When URL starts from "//" the "scheme" key will not exists.
82
            'scheme' => 'http',
83
        ];
84
85
        // Check scheme.
86
        if (!in_array($this->components['scheme'], ['http', 'https'])) {
87
            throw new \InvalidArgumentException(sprintf('%s - invalid scheme.', $this->components['scheme']));
88
        }
89
90
        $this->url = $this->components['scheme'] . '://';
91
92
        return $this;
93
    }
94
95
    /**
96
     * Append authentication credentials.
97
     *
98
     * @return $this
99
     */
100
    private function credentials()
101
    {
102
        if (isset($this->components['user'], $this->components['pass'])) {
103
            // Encode special characters in username and password. Useful
104
            // when some item contain something like "@" symbol.
105
            foreach (['user' => ':', 'pass' => '@'] as $part => $suffix) {
106
                $this->url .= rawurlencode($this->components[$part]) . $suffix;
107
            }
108
        }
109
110
        return $this;
111
    }
112
113
    /**
114
     * Append host.
115
     *
116
     * @return $this
117
     */
118
    private function host()
119
    {
120
        $this->url .= $this->components['host'];
121
122
        return $this;
123
    }
124
125
    /**
126
     * Append additional URL components.
127
     *
128
     * @return $this
129
     */
130
    private function components()
131
    {
132
        foreach (['port' => ':', 'path' => '', 'query' => '?', 'fragment' => '#'] as $part => $prefix) {
133
            if (isset($this->components[$part])) {
134
                $this->url .= $prefix . $this->components[$part];
135
            }
136
        }
137
138
        return $this;
139
    }
140
}
141