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
|
|
|
} |