Completed
Push — master ( c5bc9f...e55977 )
by Sebastian
04:11
created

Uri::equals()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
namespace Kartenmacherei\RestFramework\Request;
3
4
use Kartenmacherei\RestFramework\EnsureException;
5
6
class Uri
7
{
8
    private $value = '';
9
10
    /**
11
     * @param string $value
12
     */
13
    public function __construct($value)
14
    {
15
        $this->value = rtrim($value, '/');
16
    }
17
18
    /**
19
     * @return string
20
     */
21
    public function asString(): string
22
    {
23
        return $this->value;
24
    }
25
26
    /**
27
     * @param Uri $uri
28
     * @return bool
29
     */
30
    public function equals(Uri $uri): bool
31
    {
32
        return $this->asString() === $uri->asString();
33
    }
34
35
    /**
36
     * @param Pattern $pattern
37
     * @return bool
38
     */
39
    public function matches(Pattern $pattern): bool
40
    {
41
        return preg_match($pattern->asString(), $this->value) === 1;
42
    }
43
44
    /**
45
     * @param int $index
46
     * @return string
47
     * @throws EnsureException
48
     * @throws UriException
49
     */
50
    public function getPathSegment(int $index): string
51
    {
52
        if ($index < 0) {
53
            throw new EnsureException('Index must not be negative');
54
        }
55
        $path = parse_url($this->value, PHP_URL_PATH);
56
        $parts = explode('/', trim($path, '/'));
57
        if (count($parts) <= $index) {
58
            throw new UriException(sprintf('URI does not have %d segments', $index));
59
        }
60
        return $parts[$index];
61
    }
62
63
}
64