Conditions | 5 |
Paths | 4 |
Total Lines | 38 |
Lines | 38 |
Ratio | 100 % |
Changes | 0 |
1 | <?php |
||
10 | public static function check(string $url, string $requestUrl, string $rootUrl = '/'): bool |
||
11 | { |
||
12 | $url = Url::fromString($url); |
||
13 | $requestUrl = Url::fromString($requestUrl); |
||
14 | |||
15 | // If the hosts don't match, this url isn't active. |
||
16 | if ($url->getHost() !== $requestUrl->getHost()) { |
||
17 | return false; |
||
18 | } |
||
19 | |||
20 | $rootUrl = Str::ensureLeft('/', $rootUrl); |
||
21 | |||
22 | // All paths used in this method should be terminated by a / |
||
23 | // otherwise startsWith at the end will be too greedy and |
||
24 | // also matches items which are on the same level |
||
25 | $rootUrl = Str::ensureRight('/', $rootUrl); |
||
26 | |||
27 | $itemPath = Str::ensureRight('/', $url->getPath()); |
||
28 | |||
29 | // If this url doesn't start with the rootUrl, it's inactive. |
||
30 | if (! Str::startsWith($itemPath, $rootUrl)) { |
||
31 | return false; |
||
32 | } |
||
33 | |||
34 | $matchPath = Str::ensureRight('/', $requestUrl->getPath()); |
||
35 | |||
36 | // For the next comparisons we just need the paths, and we'll remove |
||
37 | // the rootUrl first. |
||
38 | $itemPath = Str::removeFromStart($rootUrl, $itemPath); |
||
39 | $matchPath = Str::removeFromStart($rootUrl, $matchPath); |
||
40 | |||
41 | // If this url starts with the url we're matching with, it's active. |
||
42 | if ($matchPath === $itemPath || Str::startsWith($matchPath, $itemPath)) { |
||
43 | return true; |
||
44 | } |
||
45 | |||
46 | return false; |
||
47 | } |
||
48 | } |
||
49 |
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.