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

EndpointsContainer   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 69
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
dl 0
loc 69
c 0
b 0
f 0
wmc 8
lcom 1
cbo 1
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getEndpoint() 0 8 2
A addEndpoint() 0 9 2
A createEndpoint() 0 9 2
A getRequest() 0 4 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
}