Completed
Pull Request — master (#32)
by Sergey
08:58 queued 05:34
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
    /**
23
     * @var ResponseInterface
24
     */
25
    protected $response;
26
27
    const PROVIDERS_NAMESPACE = "seregazhuk\\PinterestBot\\Api\\Providers\\";
28
29
    /**
30
     * A array containing the cached providers
31
     *
32
     * @var array
33
     */
34
    private $providers = [];
35
36
    public function __construct(RequestInterface $request, ResponseInterface $response)
37
    {
38
        $this->request = $request;
39
        $this->response = $response;
40
    }
41
42
    /**
43
     * @param string $provider
44
     * @return Provider
45
     * @throws WrongProviderException
46
     */
47
    public function getProvider($provider)
48
    {
49
        // Check if an instance has already been initiated
50
        if ( ! isset($this->providers[$provider])) {
51
            $this->addProvider($provider);
52
        }
53
54
        return $this->providers[$provider];
55
    }
56
57
    /**
58
     * @param string $provider
59
     * @throws WrongProviderException
60
     */
61
    private function addProvider($provider)
62
    {
63
        $class = self::PROVIDERS_NAMESPACE.ucfirst($provider);
64
65
        if ( ! class_exists($class)) {
66
            throw new WrongProviderException;
67
        }
68
69
        // Create a reflection of the called class
70
        $ref = new ReflectionClass($class);
71
        $obj = $ref->newInstanceArgs([$this->request, $this->response]);
72
73
        $this->providers[$provider] = $obj;
74
    }
75
76
    /**
77
     * @return RequestInterface
78
     */
79
    public function getRequest()
80
    {
81
        return $this->request;
82
    }
83
84
    /**
85
     * @return ResponseInterface
86
     */
87
    public function getResponse()
88
    {
89
        return $this->response;
90
    }
91
}