Completed
Push — master ( 1a5d97...d1cd89 )
by Sergey
03:37
created

EndpointsContainer   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 4
Bugs 1 Features 0
Metric Value
wmc 6
c 4
b 1
f 0
lcom 1
cbo 1
dl 0
loc 62
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A addProvider() 0 10 2
A buildEndpoint() 0 4 1
A resolve() 0 11 2
1
<?php
2
3
namespace seregazhuk\Favro\Api\Endpoints;
4
5
use ReflectionClass;
6
use seregazhuk\Favro\Contracts\HttpInterface;
7
use seregazhuk\Favro\Exceptions\BadEndpointException;
8
9
class EndpointsContainer
10
{
11
    const ENDPOINTS_NAMESPACE = 'seregazhuk\\Favro\\Api\\Endpoints\\';
12
13
    /*
14
    * @var HttpInterface
15
    */
16
    protected $http;
17
18
    /*
19
     * @var array
20
     */
21
    protected $endpoints = [];
22
23
    /**
24
     * @param HttpInterface $http
25
     */
26
    public function __construct(HttpInterface $http)
27
    {
28
        $this->http = $http;
29
    }
30
31
    /**
32
     * @param string $endpoint
33
     * @return Endpoint
34
     */
35
    public function resolve($endpoint)
36
    {
37
        $endpoint = strtolower($endpoint);
38
39
        // Check if an instance has already been initiated
40
        if (!isset($this->endpoints[$endpoint])) {
41
            $this->addProvider($endpoint);
42
        }
43
44
        return $this->endpoints[$endpoint];
45
    }
46
47
    /**
48
     * @param $endpoint
49
     * @throws BadEndpointException
50
     */
51
    protected function addProvider($endpoint)
52
    {
53
        $className = self::ENDPOINTS_NAMESPACE . ucfirst($endpoint);
54
55
        if (!class_exists($className)) {
56
            throw new BadEndpointException("Endpoint $className not found.");
57
        }
58
59
        $this->endpoints[$endpoint] = $this->buildEndpoint($className);
60
    }
61
62
    /**
63
     * @param string $className
64
     * @return Endpoint|object
65
     */
66
    protected function buildEndpoint($className)
67
    {
68
        return (new ReflectionClass($className))->newInstanceArgs([$this->http]);
69
    }
70
}