Completed
Pull Request — master (#14)
by Sergey
02:31
created

EndpointsContainer::addEndpoint()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.6666
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 1
1
<?php
2
3
namespace seregazhuk\HeadHunterApi\EndPoints;
4
5
use ReflectionClass;
6
use seregazhuk\HeadHunterApi\Request;
7
use seregazhuk\HeadHunterApi\Exceptions\WrongEndPointException;
8
9
/**
10
 * Class EndpointsContainer
11
 * @package seregazhuk\HeadHunterApi\EndPoints
12
 *
13
 * @property Vacancies $vacancies
14
 * @property Employers $employers
15
 * @property Regions $regions
16
 * @property Specializations $specializations
17
 * @property Industries $industries
18
 * @property Me $me
19
 * @property Resumes $resumes
20
 * @property Artifacts $artifacts
21
 * @property Negotiations $negotiations
22
 * @property SavedSearches $savedSearches
23
 * @property Comments $comments
24
 * @property Manager $manager
25
 */
26
class EndpointsContainer
27
{
28
    /**
29
     * @var Request
30
     */
31
    protected $request;
32
33
    /**
34
     * Array with the cached endpoints
35
     * @var Endpoint[]
36
     */
37
    protected $endpoints = [];
38
39
    public function __construct(Request $request)
40
    {
41
        $this->request = $request;
42
    }
43
44
    /**
45
     * @param string $endpoint
46
     * @return Endpoint
47
     */
48
    public function __get($endpoint)
49
    {
50
        return $this->getEndpoint($endpoint);
51
    }
52
53
    /**
54
     * @param string $endpoint
55
     * @return Endpoint
56
     * @throws WrongEndPointException
57
     */
58
    public function getEndpoint($endpoint)
59
    {
60
        if (!isset($this->endpoints[$endpoint])) {
61
            $this->addEndpoint($endpoint);
62
        }
63
64
        return $this->endpoints[$endpoint];
65
    }
66
67
    /**
68
     * @param string $endpoint
69
     * @throws WrongEndPointException
70
     */
71
    protected function addEndpoint($endpoint)
72
    {
73
        $class = __NAMESPACE__ . '\\' . ucfirst($endpoint);
74
        if (!class_exists($class)) {
75
            throw new WrongEndPointException;
76
        }
77
78
        $this->endpoints[$endpoint] = $this->createEndpoint($class);
79
    }
80
81
    /**
82
     * @param string $class
83
     * @return Endpoint|object
84
     * @throws WrongEndPointException
85
     */
86
    protected function createEndpoint($class)
87
    {
88
        $reflector = new ReflectionClass($class);
89
        if(!$reflector->isInstantiable()) {
90
            throw new WrongEndPointException("Endpoint $class is not instantiable.");
91
        }
92
93
        return $reflector->newInstanceArgs([$this]);
94
    }
95
96
    /**
97
     * @return Request
98
     */
99
    public function getRequest()
100
    {
101
        return $this->request;
102
    }
103
}