Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
Complex classes like Builder often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use Builder, and based on these observations, apply Extract Interface, too.
| 1 | <?php declare(strict_types = 1); |
||
| 22 | class Builder implements ContainerBuilderInterface |
||
| 23 | { |
||
| 24 | /** Controller classes scope name */ |
||
| 25 | const SCOPE_CONTROLLER = 'controllers'; |
||
| 26 | |||
| 27 | /** Service classes scope name */ |
||
| 28 | const SCOPE_SERVICES = 'service'; |
||
| 29 | |||
| 30 | /** Generated resolving function name prefix */ |
||
| 31 | const DI_FUNCTION_PREFIX = 'container'; |
||
| 32 | |||
| 33 | /** Generated resolving function service static collection name */ |
||
| 34 | const DI_FUNCTION_SERVICES = self::SCOPE_SERVICES . 'Instances'; |
||
| 35 | |||
| 36 | /** @var string[] Collection of available container scopes */ |
||
| 37 | protected $scopes = [ |
||
| 38 | self::SCOPE_CONTROLLER => [], |
||
| 39 | self::SCOPE_SERVICES => [] |
||
| 40 | ]; |
||
| 41 | |||
| 42 | /** @var ClassMetadata[] Collection of classes metadata */ |
||
| 43 | protected $classesMetadata = []; |
||
| 44 | |||
| 45 | /** @var array Collection of dependencies aliases */ |
||
| 46 | protected $classAliases = []; |
||
| 47 | |||
| 48 | /** @var ContainerInterface */ |
||
| 49 | protected $parentContainer; |
||
| 50 | |||
| 51 | /** |
||
| 52 | * @var Generator |
||
| 53 | * @Injectable |
||
| 54 | */ |
||
| 55 | protected $generator; |
||
| 56 | |||
| 57 | /** @var string Resolver function name */ |
||
| 58 | protected $resolverFunction; |
||
| 59 | |||
| 60 | /** |
||
| 61 | * Container builder constructor. |
||
| 62 | * |
||
| 63 | * @param Generator $generator PHP code generator |
||
| 64 | * @param ClassMetadata[] $classMetadata Collection of classes metadata for container |
||
|
|
|||
| 65 | */ |
||
| 66 | 2 | public function __construct(Generator $generator) |
|
| 67 | { |
||
| 68 | 2 | $this->generator = $generator; |
|
| 69 | 2 | } |
|
| 70 | |||
| 71 | /** |
||
| 72 | * {@inheritdoc} |
||
| 73 | */ |
||
| 74 | 2 | public function build(array $classesMetadata, $containerClass = 'Container', $namespace = '', ContainerInterface $parentContainer = null) |
|
| 75 | { |
||
| 76 | 2 | $this->classesMetadata = $this->processClassMetadata($classesMetadata); |
|
| 77 | 2 | $this->parentContainer = $parentContainer; |
|
| 78 | |||
| 79 | // Build dependency injection container function name |
||
| 80 | 2 | $this->resolverFunction = uniqid(self::DI_FUNCTION_PREFIX); |
|
| 81 | |||
| 82 | 2 | $containerDependencies = []; |
|
| 83 | 2 | foreach ($classesMetadata as $classMetadata) { |
|
| 84 | 2 | $className = $classMetadata->className; |
|
| 85 | // Store inner dependencies |
||
| 86 | 2 | if (array_key_exists('__construct', $classMetadata->methodsMetadata)) { |
|
| 87 | 2 | $containerDependencies[$className] = array_values($classMetadata->methodsMetadata['__construct']->dependencies ?? []); |
|
| 88 | } |
||
| 89 | } |
||
| 90 | |||
| 91 | 2 | $this->generator |
|
| 92 | 2 | ->text('<?php declare(strict_types = 1);') |
|
| 93 | 2 | ->newLine() |
|
| 94 | 2 | ->defNamespace($namespace) |
|
| 95 | 2 | ->multiComment(['Application container']) |
|
| 96 | 2 | ->defClass($containerClass, '\\' . Container::class) |
|
| 97 | 2 | ->multiComment(['@var array Collection of service instances']) |
|
| 98 | 2 | ->defClassFunction('__construct', 'public', [], ['Container constructor']) |
|
| 99 | 2 | ->newLine('$this->dependencies = ')->arrayValue($containerDependencies)->text(';') |
|
| 100 | 2 | ->newLine('$this->aliases = ')->arrayValue($this->classAliases)->text(';') |
|
| 101 | 2 | ->newLine('$this->scopes = ')->arrayValue($this->scopes)->text(';') |
|
| 102 | 2 | ->newLine('$this->services = ')->arrayValue($this->scopes[self::SCOPE_SERVICES])->text(';') |
|
| 103 | 2 | ->endClassFunction() |
|
| 104 | 2 | ->defClassFunction('logic', 'protected', ['$dependency'], ['{@inheritdoc}']) |
|
| 105 | 2 | ->newLine('return $this->' . $this->resolverFunction . '($dependency);') |
|
| 106 | 2 | ->endClassFunction(); |
|
| 107 | |||
| 108 | 2 | foreach ($classesMetadata as $classMetadata) { |
|
| 109 | 2 | $className = $classMetadata->className; |
|
| 110 | 2 | $dependencyName = $classMetadata->name ?? $className; |
|
| 111 | |||
| 112 | // Generate camel case getter method |
||
| 113 | 2 | $camelMethodName = 'get' . str_replace(' ', '', ucwords(ucfirst(str_replace(['\\', '_'], ' ', $dependencyName)))); |
|
| 114 | |||
| 115 | 2 | $this->generator |
|
| 116 | 2 | ->defClassFunction($camelMethodName, 'public', [], ['@return ' . '\\'.ltrim($className, '\\') . ' Get ' . $dependencyName . ' instance']) |
|
| 117 | 2 | ->newLine('return $this->' . $this->resolverFunction . '(\'' . $dependencyName . '\');') |
|
| 118 | 2 | ->endClassFunction(); |
|
| 119 | } |
||
| 120 | |||
| 121 | // Build di container function and add to container class and return class code |
||
| 122 | 2 | $this->buildDependencyResolver($this->resolverFunction); |
|
| 123 | |||
| 124 | 2 | return $this->generator |
|
| 125 | 2 | ->endClass() |
|
| 126 | 2 | ->flush(); |
|
| 127 | } |
||
| 128 | |||
| 129 | /** |
||
| 130 | * Read class metadata and fill internal collections. |
||
| 131 | * |
||
| 132 | * @param ClassMetadata[] $classesMetadata |
||
| 133 | * @return ClassMetadata[] Processed class metadata |
||
| 134 | */ |
||
| 135 | 2 | public function processClassMetadata(array $classesMetadata) : array |
|
| 136 | { |
||
| 137 | 2 | $processedClassesMetadata = []; |
|
| 138 | |||
| 139 | // Read all classes in given file |
||
| 140 | 2 | foreach ($classesMetadata as $classMetadata) { |
|
| 141 | // Store by metadata name as alias |
||
| 142 | 2 | $this->classAliases[$classMetadata->className] = $classMetadata->name; |
|
| 143 | |||
| 144 | // Store class in defined scopes |
||
| 145 | 2 | foreach ($classMetadata->scopes as $scope) { |
|
| 146 | 2 | $this->scopes[$scope][$classMetadata->name] = $classMetadata->className; |
|
| 147 | } |
||
| 148 | 2 | $processedClassesMetadata[$classMetadata->name] = $classMetadata; |
|
| 149 | } |
||
| 150 | |||
| 151 | 2 | return $processedClassesMetadata; |
|
| 152 | } |
||
| 153 | |||
| 154 | /** |
||
| 155 | * Build dependency resolving function. |
||
| 156 | * |
||
| 157 | * @param string $functionName Function name |
||
| 158 | * |
||
| 159 | * @throws \InvalidArgumentException |
||
| 160 | */ |
||
| 161 | 2 | protected function buildDependencyResolver($functionName) |
|
| 175 | |||
| 176 | /** |
||
| 177 | * Generate logic conditions and their implementation for container and its delegates. |
||
| 178 | * |
||
| 179 | * @param string $inputVariable Input condition parameter variable name |
||
| 180 | * @param bool|false $started Flag if condition branching has been started |
||
| 181 | */ |
||
| 182 | 2 | public function generateConditions($inputVariable = '$alias', $started = false) |
|
| 183 | { |
||
| 184 | // Iterate all container dependencies |
||
| 185 | 2 | foreach ($this->classesMetadata as $classMetadata) { |
|
| 186 | 2 | $className = $classMetadata->className; |
|
| 187 | // Generate condition statement to define if this class is needed |
||
| 188 | 2 | $conditionFunc = !$started ? 'defIfCondition' : 'defElseIfCondition'; |
|
| 189 | |||
| 190 | // Output condition branch |
||
| 191 | 2 | $this->generator->$conditionFunc( |
|
| 192 | 2 | $this->buildResolverCondition($inputVariable, $className, $classMetadata->name) |
|
| 193 | ); |
||
| 194 | |||
| 195 | // Define if this class has service scope |
||
| 196 | 2 | $isService = in_array($className, $this->scopes[self::SCOPE_SERVICES], true); |
|
| 197 | |||
| 198 | /** @var MethodMetadata[] Gather only valid method for container */ |
||
| 199 | 2 | $classValidMethods = $this->getValidClassMethodsMetadata($classMetadata->methodsMetadata); |
|
| 200 | |||
| 201 | /** @var PropertyMetadata[] Gather only valid property for container */ |
||
| 202 | 2 | $classValidProperties = $this->getValidClassPropertiesMetadata($classMetadata->propertiesMetadata); |
|
| 203 | |||
| 204 | // Define class or service variable |
||
| 205 | 2 | $staticContainerName = $isService |
|
| 206 | 2 | ? '$this->' . self::DI_FUNCTION_SERVICES . '[\'' . $classMetadata->name . '\']' |
|
| 207 | 2 | : '$temp'; |
|
| 208 | |||
| 209 | 2 | if ($isService) { |
|
| 210 | // Check if dependency was instantiated |
||
| 211 | 2 | $this->generator->defIfCondition('!array_key_exists(\'' . $classMetadata->name . '\', $this->' . self::DI_FUNCTION_SERVICES . ')'); |
|
| 212 | } |
||
| 213 | |||
| 214 | 2 | if (count($classValidMethods) || count($classValidProperties)) { |
|
| 215 | 2 | $this->generator->newLine($staticContainerName . ' = '); |
|
| 216 | 2 | $this->buildResolvingClassDeclaration($className); |
|
| 217 | 2 | $this->buildConstructorDependencies($classMetadata->methodsMetadata); |
|
| 218 | |||
| 219 | // Internal scope reflection variable |
||
| 220 | 2 | $reflectionVariable = '$reflectionClass'; |
|
| 221 | |||
| 222 | 2 | $this->buildReflectionClass($className, $classValidProperties, $classValidMethods, $reflectionVariable); |
|
| 223 | |||
| 224 | // Process class properties |
||
| 225 | 2 | foreach ($classValidProperties as $property) { |
|
| 226 | // If such property has the dependency |
||
| 227 | 2 | if ($property->dependency) { |
|
| 228 | // Set value via refection |
||
| 229 | 2 | $this->buildResolverPropertyDeclaration( |
|
| 230 | 2 | $property->name, |
|
| 231 | 2 | $property->dependency, |
|
| 232 | $staticContainerName, |
||
| 233 | $reflectionVariable, |
||
| 234 | 2 | $property->isPublic |
|
| 235 | ); |
||
| 236 | } |
||
| 237 | } |
||
| 238 | |||
| 239 | /** @var MethodMetadata $methodMetadata */ |
||
| 240 | 2 | foreach ($classValidMethods as $methodName => $methodMetadata) { |
|
| 241 | 2 | $this->buildResolverMethodDeclaration( |
|
| 242 | 2 | $methodMetadata->dependencies, |
|
| 243 | $methodName, |
||
| 244 | $staticContainerName, |
||
| 245 | $reflectionVariable, |
||
| 246 | 2 | $methodMetadata->isPublic |
|
| 247 | ); |
||
| 248 | } |
||
| 249 | |||
| 250 | 2 | if ($isService) { |
|
| 251 | 2 | $this->generator->endIfCondition(); |
|
| 252 | } |
||
| 253 | |||
| 254 | 2 | $this->generator->newLine()->newLine('return ' . $staticContainerName . ';'); |
|
| 255 | } else { |
||
| 256 | 2 | if ($isService) { |
|
| 257 | $this->generator->newLine($staticContainerName.' = '); |
||
| 258 | $this->buildResolvingClassDeclaration($className); |
||
| 259 | $this->buildConstructorDependencies($classMetadata->methodsMetadata); |
||
| 260 | $this->generator->endIfCondition()->newLine('return ' . $staticContainerName . ';'); |
||
| 261 | } else { |
||
| 262 | 2 | $this->generator->newLine('return '); |
|
| 263 | 2 | $this->buildResolvingClassDeclaration($className); |
|
| 264 | 2 | $this->buildConstructorDependencies($classMetadata->methodsMetadata); |
|
| 265 | } |
||
| 266 | |||
| 267 | } |
||
| 268 | |||
| 269 | // Set flag that condition is started |
||
| 270 | 2 | $started = true; |
|
| 271 | } |
||
| 272 | 2 | } |
|
| 273 | |||
| 274 | /** |
||
| 275 | * Build resolving function condition. |
||
| 276 | * |
||
| 277 | * @param string $inputVariable Condition variable |
||
| 278 | * @param string $className |
||
| 279 | * @param string|null $alias |
||
| 280 | * |
||
| 281 | * @return string Condition code |
||
| 282 | */ |
||
| 283 | 2 | protected function buildResolverCondition(string $inputVariable, string $className, string $alias = null) : string |
|
| 294 | |||
| 295 | /** |
||
| 296 | * Get valid class methods metadata. |
||
| 297 | * |
||
| 298 | * @param MethodMetadata[] $classMethodsMetadata All class methods metadata |
||
| 299 | * |
||
| 300 | * @return array Valid class methods metadata |
||
| 301 | */ |
||
| 302 | 2 | protected function getValidClassMethodsMetadata(array $classMethodsMetadata) |
|
| 315 | |||
| 316 | /** |
||
| 317 | * Get valid class properties metadata. |
||
| 318 | * |
||
| 319 | * @param PropertyMetadata[] $classPropertiesMetadata All class properties metadata |
||
| 320 | * |
||
| 321 | * @return array Valid class properties metadata |
||
| 322 | */ |
||
| 323 | 2 | protected function getValidClassPropertiesMetadata(array $classPropertiesMetadata) |
|
| 336 | |||
| 337 | /** |
||
| 338 | * Build resolving function class block. |
||
| 339 | * |
||
| 340 | * @param string $className Class name for new instance creation |
||
| 341 | */ |
||
| 342 | 2 | protected function buildResolvingClassDeclaration(string $className) |
|
| 346 | |||
| 347 | /** |
||
| 348 | * Build constructor arguments injection. |
||
| 349 | * |
||
| 350 | * @param MethodMetadata[] $methodsMetaData |
||
| 351 | */ |
||
| 352 | 2 | protected function buildConstructorDependencies(array $methodsMetaData) |
|
| 381 | |||
| 382 | /** |
||
| 383 | * Build resolving function dependency argument. |
||
| 384 | * |
||
| 385 | * @param mixed $argument Dependency argument |
||
| 386 | * |
||
| 387 | * @throws \InvalidArgumentException On invalid argument type |
||
| 388 | */ |
||
| 389 | 2 | protected function buildResolverArgument($argument, $textFunction = 'newLine') |
|
| 413 | |||
| 414 | /** |
||
| 415 | * Generate reflection class for private/protected methods or properties |
||
| 416 | * in current scope. |
||
| 417 | * |
||
| 418 | * @param string $className Reflection class source class name |
||
| 419 | * @param PropertyMetadata[] $propertiesMetadata Properties metadata |
||
| 420 | * @param MethodMetadata[] $methodsMetadata Methods metadata |
||
| 421 | * @param string $reflectionVariable Reflection class variable name |
||
| 422 | */ |
||
| 423 | 2 | protected function buildReflectionClass(string $className, array $propertiesMetadata, array $methodsMetadata, string $reflectionVariable) |
|
| 457 | |||
| 458 | /** |
||
| 459 | * Build resolving property injection declaration. |
||
| 460 | * |
||
| 461 | * @param string $propertyName Target property name |
||
| 462 | * @param string $dependency Dependency class name |
||
| 463 | * @param string $containerVariable Container declaration variable name |
||
| 464 | * @param string $reflectionVariable Reflection class variable name |
||
| 465 | * @param bool $isPublic Flag if property is public |
||
| 466 | */ |
||
| 467 | 2 | protected function buildResolverPropertyDeclaration( |
|
| 499 | |||
| 500 | /** |
||
| 501 | * Build resolving method injection declaration. |
||
| 502 | * |
||
| 503 | * @param array $dependencies Collection of method dependencies |
||
| 504 | * @param string $methodName Method name |
||
| 505 | * @param string $containerVariable Container declaration variable name |
||
| 506 | * @param string $reflectionVariable Reflection class variable name |
||
| 507 | * @param bool $isPublic Flag if method is public |
||
| 508 | */ |
||
| 509 | 2 | protected function buildResolverMethodDeclaration( |
|
| 547 | } |
||
| 548 |
This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.
Consider the following example. The parameter
$italyis not defined by the methodfinale(...).The most likely cause is that the parameter was removed, but the annotation was not.