1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Ciromattia\Teamwork; |
4
|
|
|
|
5
|
|
|
use Ciromattia\Teamwork\Contracts\RequestableInterface; |
6
|
|
|
use Ciromattia\Teamwork\Exceptions\ClassNotCreatedException; |
7
|
|
|
|
8
|
|
|
class Factory |
9
|
|
|
{ |
10
|
|
|
protected $client; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* @param RequestableInterface $client |
14
|
|
|
*/ |
15
|
|
|
public function __construct(RequestableInterface $client) |
16
|
|
|
{ |
17
|
|
|
$this->client = $client; |
18
|
|
|
} |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @param $method |
22
|
|
|
* @param $parameters |
23
|
|
|
* @return mixed |
24
|
|
|
* @throws ClassNotCreatedException |
25
|
|
|
* @throws \ReflectionException |
26
|
|
|
*/ |
27
|
|
|
public function __call($method, $parameters) |
28
|
|
|
{ |
29
|
|
|
$class = $this->getQualifiedName($method); |
30
|
|
|
if (!class_exists($class)) { |
31
|
|
|
throw new ClassNotCreatedException("Class $class could not be created."); |
32
|
|
|
} |
33
|
|
|
if ($this->paramIsId($parameters) == true) { |
34
|
|
|
return new $class($this->client, $parameters[0]); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
return new $class($this->client); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* Get namespace |
42
|
|
|
* |
43
|
|
|
* @return string |
44
|
|
|
* @throws \ReflectionException |
45
|
|
|
*/ |
46
|
|
|
private function getNamespace() |
47
|
|
|
{ |
48
|
|
|
$reflection = new \ReflectionClass($this); |
49
|
|
|
|
50
|
|
|
return $reflection->getNamespaceName(); |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* Get Fully Qualified Name |
55
|
|
|
* |
56
|
|
|
* build and return fully qualified name |
57
|
|
|
* for class to instantiate |
58
|
|
|
* |
59
|
|
|
* @param $method |
60
|
|
|
* @return string |
61
|
|
|
* @throws \ReflectionException |
62
|
|
|
*/ |
63
|
|
|
protected function getQualifiedName($method) |
64
|
|
|
{ |
65
|
|
|
return $this->getNamespace() . '\\' . ucfirst($method); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
/** |
69
|
|
|
* Parameter Has ID |
70
|
|
|
* |
71
|
|
|
* is there a parameter being passed in, and is it |
72
|
|
|
* an integer? |
73
|
|
|
* |
74
|
|
|
* @param $parameters |
75
|
|
|
* @return bool |
76
|
|
|
* @throws \InvalidArgumentException |
77
|
|
|
*/ |
78
|
|
|
protected function paramIsId($parameters) |
79
|
|
|
{ |
80
|
|
|
if ($parameters == null) return null; |
81
|
|
|
|
82
|
|
|
if (!is_int($parameters[0])) { |
83
|
|
|
throw new \InvalidArgumentException("This is not a valid ID"); |
84
|
|
|
} |
85
|
|
|
return true; |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
|