Completed
Pull Request — master (#32)
by Sergey
03:28
created

ProvidersContainer::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 5
rs 9.4285
cc 1
eloc 3
nc 1
nop 2
1
<?php
2
3
namespace seregazhuk\PinterestBot\Api;
4
5
use ReflectionClass;
6
use seregazhuk\PinterestBot\Api\Providers\Provider;
7
use seregazhuk\PinterestBot\Contracts\ProvidersContainerInterface;
8
use seregazhuk\PinterestBot\Contracts\RequestInterface;
9
use seregazhuk\PinterestBot\Contracts\ResponseInterface;
10
use seregazhuk\PinterestBot\Exceptions\WrongProviderException;
11
12
class ProvidersContainer implements ProvidersContainerInterface
13
{
14
    /**
15
     * References to the request and response classes that travels
16
     * through the application
17
     *
18
     * @var RequestInterface
19
     */
20
    protected $request;
21
    /**
22
     * @var ResponseInterface
23
     */
24
    protected $response;
25
26
    const PROVIDERS_NAMESPACE = "seregazhuk\\PinterestBot\\Api\\Providers\\";
27
28
    /**
29
     * A array containing the cached providers
30
     *
31
     * @var array
32
     */
33
    private $providers = [];
34
35
    public function __construct(RequestInterface $request, ResponseInterface $response)
36
    {
37
        $this->request = $request;
38
        $this->response = $response;
39
    }
40
41
    /**
42
     * @param string $provider
43
     * @return Provider
44
     * @throws WrongProviderException
45
     */
46
    public function getProvider($provider)
47
    {
48
        $provider = strtolower($provider);
49
50
        // Check if an instance has already been initiated
51
        if ( ! isset($this->providers[$provider])) {
52
            $this->addProvider($provider);
53
        }
54
55
        return $this->providers[$provider];
56
    }
57
58
    /**
59
     * @param string $provider
60
     * @throws WrongProviderException
61
     */
62
    private function addProvider($provider)
63
    {
64
        $class = self::PROVIDERS_NAMESPACE.ucfirst($provider);
65
66
        if ( ! class_exists($class)) {
67
            throw new WrongProviderException;
68
        }
69
70
        // Create a reflection of the called class
71
        $ref = new ReflectionClass($class);
72
        $obj = $ref->newInstanceArgs([$this->request, $this->response]);
73
74
        $this->providers[$provider] = $obj;
75
    }
76
77
    /**
78
     * @return RequestInterface
79
     */
80
    public function getRequest()
81
    {
82
        return $this->request;
83
    }
84
85
    /**
86
     * @return ResponseInterface
87
     */
88
    public function getResponse()
89
    {
90
        return $this->response;
91
    }
92
}