Completed
Push — master ( 0eceaa...aee3a6 )
by Ben
15:21 queued 05:47
created

src/Thinktomorrow/Locale/Parsers/UrlParser.php (2 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
namespace Thinktomorrow\Locale\Parsers;
4
5
use Illuminate\Routing\UrlGenerator;
6
use Thinktomorrow\Locale\Locale;
7
8
class UrlParser implements Parser
9
{
10
    /**
11
     * @var Locale
12
     */
13
    private $locale;
14
15
    /**
16
     * If locale is explicitly passed, we will set it
17
     * If null is passed it means the default locale must be used.
18
     *
19
     * @var string
20
     */
21
    private $localeslug = false;
22
23
    /**
24
     * @var array
25
     */
26
    private $parsed;
27
28
    /**
29
     * @var bool
30
     */
31
    private $secure = false;
32
33
    /**
34
     * @var array
35
     */
36
    private $parameters = [];
37
38
    /**
39
     * Internal flag to keep track of schemeless url.
40
     *
41
     * @var bool
42
     */
43
    private $schemeless = false;
44
45
    /**
46
     * @var UrlGenerator
47
     */
48
    private $generator;
49
50 50
    public function __construct(Locale $locale, UrlGenerator $generator)
51
    {
52 50
        $this->locale = $locale;
53 50
        $this->generator = $generator;
54 50
    }
55
56
    /**
57
     * Set the original url/uri.
58
     *
59
     * @param $url
60
     *
61
     * @throws \InvalidArgumentException
62
     *
63
     * @return $this
64
     */
65 47
    public function set($url)
66
    {
67 47
        $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...
68
69 47
        if (false === $this->parsed) {
70 1
            throw new \InvalidArgumentException('Failed to parse url. Invalid url ['.$url.'] passed as parameter.');
71
        }
72
73
        // If a schemeless url is passed, parse_url will ignore this and strip the first tags
74
        // so we keep a reminder to explicitly reassemble the 'anonymous scheme' manually
75 46
        $this->schemeless = (0 === strpos($url, '//') && isset($this->parsed['host']));
76
77 46
        return $this;
78
    }
79
80
    /**
81
     * Get the localized url.
82
     *
83
     * @return string
84
     */
85 47
    public function get()
86
    {
87 47
        $this->assertUrlExists();
88
89
        // Only localize the url if a locale is passed.
90 46
        if (false !== $this->localeslug) {
91 43
            $this->localizePath($this->localeslug);
92
        }
93
94 46
        $url = $this->generator->to($this->reassemble($this->parsed), $this->parameters, $this->secure);
95
96
        // Secure url is not enforced by the urlgenerator when a valid url is passed
97
        // So we enforce it after url generation
98 46
        if ($this->secure && 0 === strpos($url, 'http://')) {
99 2
            $url = str_replace('http://', 'https://', $url);
100
        }
101
102 46
        return $url;
103
    }
104
105
    /**
106
     * Resolve the route via the Illuminate UrlGenerator.
107
     *
108
     * @param $routekey
109
     * @param array $parameters
110
     *
111
     * @return string
112
     */
113 27
    public function resolveRoute($routekey, $parameters = [])
114
    {
115 27
        return $this->generator->route($routekey, $parameters, true);
116
    }
117
118
    /**
119
     * Place locale segment in front of url path
120
     * e.g. /foo/bar is transformed into /en/foo/bar.
121
     *
122
     * @param null $localeslug
123
     *
124
     * @return string
125
     */
126 45
    public function localize($localeslug = null)
127
    {
128 45
        $this->localeslug = $localeslug;
129
130 45
        return $this;
131
    }
132
133
    /**
134
     * @param array $parameters
135
     *
136
     * @return $this
137
     */
138 11
    public function parameters(array $parameters = [])
139
    {
140 11
        $this->parameters = $parameters;
141
142 11
        return $this;
143
    }
144
145
    /**
146
     * @param bool $secure
147
     *
148
     * @return $this
149
     */
150 13
    public function secure($secure = true)
151
    {
152 13
        $this->secure = (bool) $secure;
153
154 13
        return $this;
155
    }
156
157
    /**
158
     * Inject the locale slug in the uri.
159
     *
160
     * @param null $locale
161
     */
162 43
    private function localizePath($locale = null)
163
    {
164 43
        $this->parsed['path'] = str_replace('//', '/',
165 43
            '/'.$this->locale->getSlug($locale).$this->delocalizePath()
166
        );
167 43
    }
168
169
    /**
170
     * @return array
171
     */
172 43
    private function delocalizePath()
173
    {
174 43
        if (!isset($this->parsed['path'])) {
175 7
            return;
176
        }
177
178 43
        $path_segments = explode('/', trim($this->parsed['path'], '/'));
179
180 43
        if (count($path_segments) < 1) {
181
            return;
182
        }
183
184 43
        if ($this->locale->isHidden($path_segments[0]) || $path_segments[0] === $this->locale->getSlug($path_segments[0])) {
185 12
            unset($path_segments[0]);
186
        }
187
188 43
        return '/'.implode('/', $path_segments);
189
    }
190
191
    /**
192
     * Construct a full url with the parsed url elements
193
     * resulted from a parse_url() function call.
194
     *
195
     * @param array $parsed
196
     *
197
     * @return string
198
     */
199 46
    private function reassemble(array $parsed)
200
    {
201 46
        $scheme = (isset($parsed['scheme'])) ? $parsed['scheme'].'://' : ($this->schemeless ? '//' : '');
202
203
        return
204
            $scheme
205 46
            .((isset($parsed['user'])) ? $parsed['user'].((isset($parsed['pass'])) ? ':'.$parsed['pass'] : '').'@' : '')
206 46
            .((isset($parsed['host'])) ? $parsed['host'] : '')
207 46
            .((isset($parsed['port'])) ? ':'.$parsed['port'] : '')
208 46
            .((isset($parsed['path'])) ? $parsed['path'] : '')
209 46
            .((isset($parsed['query'])) ? '?'.$parsed['query'] : '')
210 46
            .((isset($parsed['fragment'])) ? '#'.$parsed['fragment'] : '');
211
    }
212
213 47
    private function assertUrlExists()
214
    {
215 47
        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...
216 1
            throw new \LogicException('Url is required. Please run UrlParser::set($url) first.');
217
        }
218 46
    }
219
}
220