Total Lines | 62 |
Code Lines | 17 |
Lines | 0 |
Ratio | 0 % |
Changes | 1 | ||
Bugs | 0 | Features | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
1 | <?php |
||
180 | protected function closureToListener(Closure $closure): ListenerInterface |
||
181 | { |
||
182 | $listener = new class ($closure) extends ListenerAbstract implements ListenerInterface |
||
183 | { |
||
184 | const ERR_CLOSURE_ARG_MISSING = 'Listener closure required at least one Event argument'; |
||
185 | const ERR_CLOSURE_ARG_INVALID ='Listener closure arg type should comply EventInterface'; |
||
186 | |||
187 | /** |
||
188 | * listener as closure |
||
189 | * |
||
190 | * @var Closure |
||
191 | */ |
||
192 | protected $closure; |
||
193 | |||
194 | /** |
||
195 | * instanciate |
||
196 | * |
||
197 | * @param Closure $closure |
||
198 | */ |
||
199 | public function __construct(Closure $closure) |
||
200 | { |
||
201 | $params = $this->getClosureParameters($closure); |
||
202 | if (count($params) === 0) { |
||
203 | throw new Exception( |
||
204 | self::ERR_CLOSURE_ARG_MISSING |
||
205 | ); |
||
206 | } |
||
207 | $argTypeName = $params[0]->getType()->getName(); |
||
208 | if ($argTypeName !== EventInterface::class) { |
||
209 | throw new Exception( |
||
210 | self::ERR_CLOSURE_ARG_INVALID |
||
211 | ); |
||
212 | } |
||
213 | $this->closure = $closure; |
||
214 | } |
||
215 | |||
216 | /** |
||
217 | * publish |
||
218 | * |
||
219 | * @param EventInterface $event |
||
220 | * @return void |
||
221 | */ |
||
222 | public function publish(EventInterface $event) |
||
223 | { |
||
224 | call_user_func($this->closure, $event); |
||
225 | } |
||
226 | |||
227 | /** |
||
228 | * return an array of reflexion parameter |
||
229 | * |
||
230 | * @see https://www.php.net/manual/fr/class.reflectionparameter.php |
||
231 | * |
||
232 | * @param Closure $closure |
||
233 | * @return ReflectionParameter[] |
||
234 | */ |
||
235 | protected function getClosureParameters(Closure $closure): array |
||
236 | { |
||
237 | $reflection = new ReflectionFunction($closure); |
||
238 | return $reflection->getParameters(); |
||
239 | } |
||
240 | }; |
||
241 | return $listener; |
||
242 | } |
||
244 |