-
-
Notifications
You must be signed in to change notification settings - Fork 99
/
Copy pathExactUrlChecker.php
48 lines (36 loc) · 1.44 KB
/
ExactUrlChecker.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<?php
namespace Spatie\Menu;
use Spatie\Menu\Helpers\Str;
use Spatie\Url\Url;
class ExactUrlChecker
{
public static function check(string $url, string $requestUrl, string $rootUrl = '/'): bool
{
$url = Url::fromString($url);
$requestUrl = Url::fromString($requestUrl);
// If the hosts don't match, this url isn't active.
if ($url->getHost() !== $requestUrl->getHost()) {
return false;
}
$rootUrl = Str::ensureLeft('/', $rootUrl);
// All paths used in this method should be terminated by a /
// otherwise startsWith at the end will be too greedy and
// also matches items which are on the same level
$rootUrl = Str::ensureRight('/', $rootUrl);
$itemPath = Str::ensureRight('/', $url->getPath());
// If this url doesn't start with the rootUrl, it's inactive.
if (! Str::startsWith($itemPath, $rootUrl)) {
return false;
}
$matchPath = Str::ensureRight('/', $requestUrl->getPath());
// For the next comparisons we just need the paths, and we'll remove
// the rootUrl first.
$itemPath = Str::removeFromStart($rootUrl, $itemPath);
$matchPath = Str::removeFromStart($rootUrl, $matchPath);
// If this url is an exact match for the url we're matching with, it's exact-active.
if ($matchPath === $itemPath) {
return true;
}
return false;
}
}