Passed
Push — master ( c54cf2...993f75 )
by Tom
01:10 queued 10s
created

Route::getMethod()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
4
namespace TomHart\Restful\Routing;
5
6
use TomHart\Restful\Exceptions\UndefinedIndexException;
7
8
final class Route
9
{
10
11
    /**
12
     * @var string
13
     */
14
    private $method;
15
16
    /**
17
     * @var string[]
18
     */
19
    private $hrefs = [];
20
21
    /**
22
     * Route constructor.
23
     * @param string $method
24
     * @param string[] $hrefs
25
     */
26
    public function __construct(string $method, array $hrefs)
27
    {
28
        $this->method = $method;
29
        $this->hrefs = $hrefs;
30
    }
31
32
33
    /**
34
     * Build an instance from an array.
35
     * @param mixed[] $arr
36
     * @return static
37
     */
38
    public static function fromArray(array $arr): self
39
    {
40
        return new static($arr['method'], $arr['href']);
41
    }
42
43
    /**
44
     * @param string $url
45
     * @param string $method
46
     * @return static
47
     */
48
    public static function fromUrl(string $url, string $method): self
49
    {
50
        return new static($method, ['absolute' => $url]);
51
    }
52
53
    /**
54
     * @return string
55
     */
56
    public function getMethod()
57
    {
58
        return $this->method;
59
    }
60
61
    /**
62
     * @param string $part
63
     * @param mixed[] $queryString
64
     * @return string[]|string
65
     * @throws UndefinedIndexException
66
     */
67
    public function getHrefs(string $part = null, array $queryString = [])
68
    {
69
        if ($part !== null) {
70
            if (!isset($this->hrefs[$part])) {
71
                throw new UndefinedIndexException("index $part not in hrefs");
72
            }
73
74
            $post = '';
75
            if (!empty($queryString)) {
76
                $post = '?' . http_build_query($queryString);
77
            }
78
79
            return $this->hrefs[$part] . $post;
80
        }
81
        return $this->hrefs;
82
    }
83
}
84