| Total Lines | 60 |
| 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 |
||
| 179 | protected function closureToListener(Closure $closure): ListenerInterface |
||
| 180 | { |
||
| 181 | $listener = new class ($closure) extends ListenerAbstract implements ListenerInterface |
||
| 182 | { |
||
| 183 | const ERR_CLOSURE_ARG_MISSING = 'Listener closure required at least one Event argument'; |
||
| 184 | const ERR_CLOSURE_ARG_INVALID = 'Listener closure arg type should comply EventInterface'; |
||
| 185 | |||
| 186 | /** |
||
| 187 | * listener as closure |
||
| 188 | * |
||
| 189 | * @var Closure |
||
| 190 | */ |
||
| 191 | protected $closure; |
||
| 192 | |||
| 193 | /** |
||
| 194 | * instanciate |
||
| 195 | * |
||
| 196 | * @param Closure $closure |
||
| 197 | */ |
||
| 198 | public function __construct(Closure $closure) |
||
| 199 | { |
||
| 200 | $params = $this->getClosureParameters($closure); |
||
| 201 | if (count($params) === 0) { |
||
| 202 | throw new Exception(self::ERR_CLOSURE_ARG_MISSING); |
||
| 203 | } |
||
| 204 | $argTypeName = (version_compare(phpversion(), '7.1', '<')) |
||
| 205 | ? (string) $params[0]->getType() |
||
| 206 | : $params[0]->getType()->getName(); |
||
| 207 | if ($argTypeName !== EventInterface::class) { |
||
| 208 | throw new Exception(self::ERR_CLOSURE_ARG_INVALID); |
||
| 209 | } |
||
| 210 | $this->closure = $closure; |
||
| 211 | } |
||
| 212 | |||
| 213 | /** |
||
| 214 | * publish |
||
| 215 | * |
||
| 216 | * @param EventInterface $event |
||
| 217 | * @return void |
||
| 218 | */ |
||
| 219 | public function publish(EventInterface $event) |
||
| 220 | { |
||
| 221 | call_user_func($this->closure, $event); |
||
| 222 | } |
||
| 223 | |||
| 224 | /** |
||
| 225 | * return an array of reflexion parameter |
||
| 226 | * |
||
| 227 | * @see https://www.php.net/manual/fr/class.reflectionparameter.php |
||
| 228 | * |
||
| 229 | * @param Closure $closure |
||
| 230 | * @return ReflectionParameter[] |
||
| 231 | */ |
||
| 232 | protected function getClosureParameters(Closure $closure): array |
||
| 233 | { |
||
| 234 | $reflection = new ReflectionFunction($closure); |
||
| 235 | return $reflection->getParameters(); |
||
| 236 | } |
||
| 237 | }; |
||
| 238 | return $listener; |
||
| 239 | } |
||
| 241 |