@@ 68-86 (lines=19) @@ | ||
65 | * @param $methodName |
|
66 | * @return mixed The method's return value |
|
67 | */ |
|
68 | public function injectIntoMethod( $object, $methodName = "injectDependencies" ){ |
|
69 | $ref = new \ReflectionClass($object); |
|
70 | try{ |
|
71 | $refMethod = $ref->getMethod( $methodName ); |
|
72 | }catch( ReflectionException $e ){ |
|
73 | return null; |
|
74 | } |
|
75 | ||
76 | $toInject = []; |
|
77 | foreach ($refMethod->getParameters() as $p) { |
|
78 | $className = $p->getClass()->name; |
|
79 | if( $className === "Pimple\\Container" ){ |
|
80 | $toInject[] = $this->container; |
|
81 | }else{ |
|
82 | $toInject[] = $this->container[ $className ]; |
|
83 | } |
|
84 | } |
|
85 | return $refMethod->invoke( $object, ... $toInject ); |
|
86 | } |
|
87 | ||
88 | /** |
|
89 | * Inject dependencies from, or including, the Pimple container, into a a given class's constructor |
|
@@ 96-118 (lines=23) @@ | ||
93 | * @param array $toInject |
|
94 | * @return bool Whether the method was found |
|
95 | */ |
|
96 | public function injectIntoConstructor( $classToBuildName, array $toInject=[] ){ |
|
97 | $ref = new \ReflectionClass($classToBuildName); |
|
98 | try{ |
|
99 | $constr = $ref->getConstructor(); |
|
100 | }catch( ReflectionException $e ){ |
|
101 | return null; |
|
102 | } |
|
103 | ||
104 | $numToSkip = count($toInject); |
|
105 | foreach ($constr->getParameters() as $p) { |
|
106 | if( $numToSkip > 0 ){ |
|
107 | $numToSkip--; |
|
108 | continue; |
|
109 | } |
|
110 | $classToInjectName = $p->getClass()->name; |
|
111 | if( $classToInjectName === "Pimple\\Container" ){ |
|
112 | $toInject[] = $this->container; |
|
113 | }else{ |
|
114 | $toInject[] = $this->container[ $classToInjectName ]; |
|
115 | } |
|
116 | } |
|
117 | return new $classToBuildName( ... $toInject ); |
|
118 | } |
|
119 | ||
120 | } |
|
121 |