1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Bright Nucleus Invoker Component. |
4
|
|
|
* |
5
|
|
|
* @package BrightNucleus\Invoker |
6
|
|
|
* @author Alain Schlesser <[email protected]> |
7
|
|
|
* @license MIT |
8
|
|
|
* @link http://www.brightnucleus.com/ |
9
|
|
|
* @copyright 2015-2016 Alain Schlesser, Bright Nucleus |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace BrightNucleus\Invoker; |
13
|
|
|
|
14
|
|
|
use BrightNucleus\Exception\InvalidArgumentException; |
15
|
|
|
use Exception; |
16
|
|
|
use ReflectionMethod; |
17
|
|
|
use ReflectionClass; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* Trait to make the instantiate() method easily accessible inside classes. |
21
|
|
|
* |
22
|
|
|
* @since 0.2.0 |
23
|
|
|
* |
24
|
|
|
* @package BrightNucleus\Invoker |
25
|
|
|
* @author Alain Schlesser <[email protected]> |
26
|
|
|
*/ |
27
|
|
|
trait InstantiatorTrait |
28
|
|
|
{ |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* Check the accepted arguments for a given class constructor and pass |
32
|
|
|
* associative array values in the right order. |
33
|
|
|
* |
34
|
|
|
* @since 0.2.0 |
35
|
|
|
* |
36
|
|
|
* @param string $class The class that needs to be instantiated. |
37
|
|
|
* @param array $args Associative array that contains the arguments. |
38
|
|
|
* |
39
|
|
|
* @return object Instantiated object. |
40
|
|
|
* @throws InvalidArgumentException If a valid method is missing. |
41
|
|
|
*/ |
42
|
9 |
|
protected function instantiateClass($class, array $args) |
43
|
|
|
{ |
44
|
|
|
try { |
45
|
9 |
|
$reflectionMethod = new ReflectionMethod($class, '__construct'); |
46
|
|
|
|
47
|
9 |
|
$ordered_arguments = Helper::parseParams( |
48
|
9 |
|
$reflectionMethod->getParameters(), |
49
|
|
|
$args |
50
|
|
|
); |
51
|
|
|
|
52
|
8 |
|
$reflectionClass = new ReflectionClass($class); |
53
|
|
|
|
54
|
8 |
|
return $reflectionClass->newInstanceArgs( |
55
|
8 |
|
(array)$ordered_arguments |
56
|
|
|
); |
57
|
1 |
|
} catch (Exception $exception) { |
58
|
1 |
|
throw new InvalidArgumentException( |
59
|
|
|
sprintf( |
60
|
1 |
|
_('Failed to instantiate class "%1$s". Reason: %2$s'), |
61
|
|
|
$class, |
62
|
1 |
|
$exception->getMessage() |
63
|
|
|
) |
64
|
|
|
); |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|