Completed
Pull Request — master (#12)
by Sergey
02:44
created

EndpointsContainer::__construct()   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
3
namespace seregazhuk\HeadHunterApi\EndPoints;
4
5
use ReflectionClass;
6
use seregazhuk\HeadHunterApi\Contracts\RequestInterface;
7
use seregazhuk\HeadHunterApi\Exceptions\WrongEndPointException;
8
9
class EndpointsContainer
10
{
11
    /**
12
     * @var RequestInterface
13
     */
14
    protected $request;
15
16
    /**
17
     * Array with the cached endpoints
18
     * @var Endpoint[]
19
     */
20
    protected $endpoints = [];
21
22
    public function __construct(RequestInterface $request)
23
    {
24
        $this->request = $request;
25
    }
26
27
    /**
28
     * @param string $endpoint
29
     * @return Endpoint
30
     * @throws WrongEndPointException
31
     */
32
    public function getEndpoint($endpoint)
33
    {
34
        if (!isset($this->endpoints[$endpoint])) {
35
            $this->addEndpoint($endpoint);
36
        }
37
38
        return $this->endpoints[$endpoint];
39
    }
40
41
    /**
42
     * @param string $endpoint
43
     * @throws WrongEndPointException
44
     */
45
    protected function addEndpoint($endpoint)
46
    {
47
        $class = __NAMESPACE__ . '\\' . ucfirst($endpoint);
48
        if (!class_exists($class)) {
49
            throw new WrongEndPointException;
50
        }
51
52
        $this->endpoints[$endpoint] = $this->createEndpoint($class);
53
    }
54
55
    /**
56
     * @param string $class
57
     * @return Endpoint|object
58
     * @throws WrongEndPointException
59
     */
60
    protected function createEndpoint($class)
61
    {
62
        $reflector = new ReflectionClass($class);
63
        if(!$reflector->isInstantiable()) {
64
            throw new WrongEndPointException("Endpoint $class is not instantiable.");
65
        }
66
67
        return $reflector->newInstanceArgs([$this]);
68
    }
69
70
    /**
71
     * @return RequestInterface
72
     */
73
    public function getRequest()
74
    {
75
        return $this->request;
76
    }
77
}