Passed
Pull Request — 1.x (#1)
by Kevin
01:50
created

Url   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 25
dl 0
loc 55
rs 10
c 1
b 0
f 0
wmc 8

5 Methods

Rating   Name   Duplication   Size   Complexity  
A matches() 0 9 1
A notMatches() 0 9 1
A __construct() 0 4 1
A parseUrl() 0 15 4
A jsonEncode() 0 3 1
1
<?php
2
3
namespace Zenstruck\Browser\Assert\Assertion;
4
5
/**
6
 * @author Kevin Bond <[email protected]>
7
 */
8
final class Url
9
{
10
    private array $current;
11
    private array $partsToMatch;
12
13
    public function __construct(string $current, array $partsToMatch = [])
14
    {
15
        $this->partsToMatch = $partsToMatch;
16
        $this->current = $this->parseUrl($current);
17
    }
18
19
    public function matches(string $expected): IsTrue
20
    {
21
        $expected = $this->parseUrl($expected);
22
23
        return new IsTrue(
24
            $expected === $this->current,
25
            'The current url: %s does not match expected: %s.',
26
            self::jsonEncode($this->current),
27
            self::jsonEncode($expected)
28
        );
29
    }
30
31
    public function notMatches(string $expected): IsTrue
32
    {
33
        $expected = $this->parseUrl($expected);
34
35
        return new IsTrue(
36
            $expected !== $this->current,
37
            'The current url: %s matches expected: %s but it should not.',
38
            self::jsonEncode($this->current),
39
            self::jsonEncode($expected)
40
        );
41
    }
42
43
    private static function jsonEncode(array $parts): string
44
    {
45
        return \json_encode($parts, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
46
    }
47
48
    private function parseUrl(string $url): array
49
    {
50
        $parts = \parse_url(\urldecode($url));
51
52
        if (empty($this->partsToMatch)) {
53
            return $parts;
54
        }
55
56
        foreach (\array_keys($parts) as $part) {
57
            if (!\in_array($part, $this->partsToMatch, true)) {
58
                unset($parts[$part]);
59
            }
60
        }
61
62
        return $parts;
63
    }
64
}
65