| Total Complexity | 79 |
| Total Lines | 385 |
| Duplicated Lines | 0 % |
| Changes | 0 | ||
Complex classes like Dice 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.
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 Dice, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 16 | class Dice |
||
| 17 | { |
||
| 18 | const CONSTANT = 'Dice::CONSTANT'; |
||
| 19 | const INSTANCE = 'Dice::INSTANCE'; |
||
| 20 | |||
| 21 | /** |
||
| 22 | * @var array $rules Rules which have been set using addRule() |
||
| 23 | */ |
||
| 24 | private $rules = []; |
||
| 25 | |||
| 26 | /** |
||
| 27 | * @var array $cache A cache of closures based on class name so each class is only reflected once |
||
| 28 | */ |
||
| 29 | private $cache = []; |
||
| 30 | |||
| 31 | /** |
||
| 32 | * @var array $instances Stores any instances marked as 'shared' so create() can return the same instance |
||
| 33 | */ |
||
| 34 | private $instances = []; |
||
| 35 | |||
| 36 | /** |
||
| 37 | * Constructor which allows setting a default ruleset to apply to all objects. |
||
| 38 | */ |
||
| 39 | public function __construct($defaultRule = []) |
||
| 40 | { |
||
| 41 | if (!empty($defaultRule)) { |
||
| 42 | $this->rules['*'] = $defaultRule; |
||
| 43 | } |
||
| 44 | } |
||
| 45 | |||
| 46 | /** |
||
| 47 | * Adds a rule $rule to the class $classname. |
||
| 48 | * |
||
| 49 | * The container can be fully configured using rules provided by associative arrays. |
||
| 50 | * See {@link https://r.je/dice.html#example3} for a description of the rules. |
||
| 51 | * |
||
| 52 | * @param string $classname The name of the class to add the rule for |
||
| 53 | * @param array $rule The rule to add to it |
||
| 54 | */ |
||
| 55 | public function addRule($classname, $rule) |
||
| 71 | } |
||
| 72 | |||
| 73 | /** |
||
| 74 | * Add rules as array. Useful for JSON loading |
||
| 75 | * $dice->addRules(json_decode(file_get_contents('foo.json')); |
||
| 76 | * |
||
| 77 | * @param array $rules Rules in a single array [name => $rule] format |
||
| 78 | */ |
||
| 79 | public function addRules(array $rules) |
||
| 80 | { |
||
| 81 | foreach ($rules as $name => $rule) { |
||
| 82 | $this->addRule($name, $rule); |
||
| 83 | } |
||
| 84 | } |
||
| 85 | |||
| 86 | /** |
||
| 87 | * Returns the rule that will be applied to the class $matching during create(). |
||
| 88 | * |
||
| 89 | * @param string $name The name of the ruleset to get - can be a class or not |
||
| 90 | * @return array Ruleset that applies when instantiating the given name |
||
| 91 | */ |
||
| 92 | public function getRule($name) |
||
| 93 | { |
||
| 94 | // first, check for exact match |
||
| 95 | $normalname = self::normalizeName($name); |
||
| 96 | |||
| 97 | if (isset($this->rules[$normalname])) { |
||
| 98 | return $this->rules[$normalname]; |
||
| 99 | } |
||
| 100 | |||
| 101 | // next, look for a rule where: |
||
| 102 | foreach ($this->rules as $key => $rule) { |
||
| 103 | if ($key !== '*' // it's not the default rule, |
||
| 104 | && \is_subclass_of($name, $key) // its name is a parent class of what we're looking for, |
||
| 105 | && empty($rule['instanceOf']) // it's not a named instance, |
||
| 106 | && (!array_key_exists('inherit', $rule) || $rule['inherit'] === true) // and it applies to subclasses |
||
| 107 | ) { |
||
| 108 | return $rule; |
||
| 109 | } |
||
| 110 | } |
||
| 111 | |||
| 112 | // if we get here, return the default rule if it's set |
||
| 113 | return (isset($this->rules['*'])) ? $this->rules['*'] : []; |
||
| 114 | } |
||
| 115 | |||
| 116 | /** |
||
| 117 | * Returns a fully constructed object based on $classname using $args and $share as constructor arguments |
||
| 118 | * |
||
| 119 | * @param string $classname The name of the class to instantiate |
||
| 120 | * @param array $args An array with any additional arguments to be passed into the constructor |
||
| 121 | * @param array $share Whether the same class instance should be passed around each time |
||
| 122 | * @return object A fully constructed object based on the specified input arguments |
||
| 123 | */ |
||
| 124 | public function create($classname, array $args = [], array $share = []) |
||
| 125 | { |
||
| 126 | if (!empty($this->instances[$classname])) { |
||
| 127 | // we've already created a shared instance so return it to save the closure call. |
||
| 128 | return $this->instances[$classname]; |
||
| 129 | } |
||
| 130 | |||
| 131 | // so now, we either need a new instance or just don't have one stored |
||
| 132 | // but if we have the closure stored that creates it, call that |
||
| 133 | if (!empty($this->cache[$classname])) { |
||
| 134 | return $this->cache[$classname]($args, $share); |
||
| 135 | } |
||
| 136 | |||
| 137 | $rule = $this->getRule($classname); |
||
| 138 | // Reflect the class for inspection, this should only ever be done once per class and then be cached |
||
| 139 | $class = new \ReflectionClass(isset($rule['instanceOf']) ? $rule['instanceOf'] : $classname); |
||
| 140 | $constructor = $class->getConstructor(); |
||
| 141 | // Create parameter-generating closure in order to cache reflection on the parameters. |
||
| 142 | // This way $reflectmethod->getParameters() only ever gets called once. |
||
| 143 | $params = (isset($constructor)) ? $this->getParams($constructor, $rule) : null; |
||
| 144 | |||
| 145 | $closure = $this->getClosure($class, $params); |
||
| 146 | |||
| 147 | // Get a closure based on the type of object being created: shared, normal, or constructorless |
||
| 148 | if (isset($rule['shared']) && $rule['shared'] === true) { |
||
| 149 | $closure = function(array $args, array $share) use ($classname, $class, $constructor, $params, $closure) { |
||
| 150 | if ($class->isInternal() === true) { |
||
| 151 | $this->instances[$classname] = $closure($args, $share); |
||
| 152 | } else if (isset($constructor)) { |
||
| 153 | try { |
||
| 154 | // Shared instance: create without calling constructor (and write to \$classname and $classname, see issue #68) |
||
| 155 | $this->instances[$classname] = $class->newInstanceWithoutConstructor(); |
||
| 156 | // Now call constructor after constructing all dependencies. Avoids problems with cyclic references (issue #7) |
||
| 157 | $constructor->invokeArgs($this->instances[$classname], $params($args, $share)); |
||
| 158 | } catch (\ReflectionException $e) { |
||
| 159 | $this->instances[$classname] = $class->newInstanceArgs($params($args, $share)); |
||
| 160 | } |
||
| 161 | } else { |
||
| 162 | $this->instances[$classname] = $class->newInstanceWithoutConstructor(); |
||
| 163 | } |
||
| 164 | |||
| 165 | $this->instances[self::normalizeNamespace($classname)] = $this->instances[$classname]; |
||
| 166 | |||
| 167 | return $this->instances[$classname]; |
||
| 168 | }; |
||
| 169 | } |
||
| 170 | |||
| 171 | //If there are shared instances, create them and merge them with shared instances higher up the object graph |
||
| 172 | if (isset($rule['shareInstances'])) { |
||
| 173 | $closure = function(array $args, array $share) use ($closure, $rule) { |
||
| 174 | foreach ($rule['shareInstances'] as $instance) { |
||
| 175 | $share[] = $this->create($instance, [], $share); |
||
| 176 | } |
||
| 177 | return $closure($args, $share); |
||
| 178 | }; |
||
| 179 | } |
||
| 180 | |||
| 181 | // When $rule['call'] is set, wrap the closure in another closure which calls the required methods after constructing the object. |
||
| 182 | // By putting this in a closure, the loop is never executed unless call is actually set. |
||
| 183 | if (isset($rule['call'])) { |
||
| 184 | $closure = function(array $args, array $share) use ($closure, $class, $rule) { |
||
| 185 | // Construct the object using the original closure |
||
| 186 | $object = $closure($args, $share); |
||
| 187 | |||
| 188 | foreach ($rule['call'] as $call) { |
||
| 189 | // Generate the method arguments using getParams() and call the returned closure |
||
| 190 | // (in php7 it will be ()() rather than __invoke) |
||
| 191 | $shareRule = ['shareInstances' => isset($rule['shareInstances']) ? $rule['shareInstances'] : []]; |
||
| 192 | $callMeMaybe = isset($call[1]) ? $call[1] : []; |
||
| 193 | $return = call_user_func_array( |
||
| 194 | [$object, $call[0]], |
||
| 195 | $this->getParams($class->getMethod($call[0]), $shareRule) |
||
| 196 | ->__invoke($this->expand($callMeMaybe)) |
||
| 197 | ); |
||
| 198 | |||
| 199 | if (isset($call[2]) && is_callable($call[2])) { |
||
| 200 | call_user_func($call[2], $return); |
||
| 201 | } |
||
| 202 | } |
||
| 203 | |||
| 204 | return $object; |
||
| 205 | }; |
||
| 206 | } |
||
| 207 | |||
| 208 | $this->cache[$classname] = $closure; |
||
| 209 | |||
| 210 | return $this->cache[$classname]($args, $share); |
||
| 211 | } |
||
| 212 | |||
| 213 | /** |
||
| 214 | * Returns a closure for creating object, caching the reflection object for later use. |
||
| 215 | * |
||
| 216 | * The container can be fully configured using rules provided by associative arrays. |
||
| 217 | * See {@link https://r.je/dice.html#example3} for a description of the rules. |
||
| 218 | * |
||
| 219 | * @param \ReflectionClass $class The reflection object used to inspect the class |
||
| 220 | * @param \Closure|null $params The output of getParams() |
||
| 221 | * @return \Closure A closure that will create the appropriate object when called |
||
| 222 | */ |
||
| 223 | private function getClosure(\ReflectionClass $class, $params) |
||
| 224 | { |
||
| 225 | // PHP throws a fatal error rather than an exception when trying to |
||
| 226 | // instantiate an interface - detect it and throw an exception instead |
||
| 227 | if ($class->isInterface()) { |
||
| 228 | return function() { |
||
| 229 | throw new \InvalidArgumentException('Cannot instantiate interface'); |
||
| 230 | }; |
||
| 231 | } |
||
| 232 | |||
| 233 | if ($params) { |
||
| 234 | // This class has dependencies, call the $params closure to generate them based on $args and $share |
||
| 235 | return function(array $args, array $share) use ($class, $params) { |
||
| 236 | return $class->newInstanceArgs($params($args, $share)); |
||
| 237 | }; |
||
| 238 | } |
||
| 239 | |||
| 240 | return function() use ($class) { |
||
| 241 | // No constructor arguments, just instantiate the class |
||
| 242 | return new $class->name(); |
||
| 243 | }; |
||
| 244 | } |
||
| 245 | |||
| 246 | /** |
||
| 247 | * Returns a closure that generates arguments for $method based on $rule and any $args passed into the closure |
||
| 248 | * |
||
| 249 | * @param \ReflectionMethod $method A reflection of the method to inspect |
||
| 250 | * @param array $rule The ruleset to use in interpreting what the params should be |
||
| 251 | * @return \Closure A closure that uses the cached information to generate the method's arguments |
||
| 252 | */ |
||
| 253 | private function getParams(\ReflectionMethod $method, array $rule) |
||
| 330 | }; |
||
| 331 | } |
||
| 332 | |||
| 333 | /** |
||
| 334 | * Looks for Dice::INSTANCE or Dice::CONSTANT array keys in $param, and when found, returns an object based on the value. |
||
| 335 | * See {@link https:// r.je/dice.html#example3-1} |
||
| 336 | * |
||
| 337 | * @param string|array $param |
||
| 338 | * @param array $share Array of instances from 'shareInstances', required for calls to `create` |
||
| 339 | * @param bool $createFromString |
||
| 340 | * @return mixed |
||
| 341 | */ |
||
| 342 | private function expand($param, array $share = [], $createFromString = false) |
||
| 343 | { |
||
| 344 | if (!\is_array($param)) { |
||
| 345 | // doesn't need any processing |
||
| 346 | return (is_string($param) && $createFromString) ? $this->create($param) : $param; |
||
| 347 | } |
||
| 348 | |||
| 349 | if (isset($param[self::CONSTANT])) { |
||
| 350 | return constant($param[self::CONSTANT]); |
||
| 351 | } |
||
| 352 | |||
| 353 | if (!isset($param[self::INSTANCE])) { |
||
| 354 | // not a lazy instance, so recursively search for any self::INSTANCE keys on deeper levels |
||
| 355 | foreach ($param as $name => $value) { |
||
| 356 | $param[$name] = $this->expand($value, $share); |
||
| 357 | } |
||
| 358 | |||
| 359 | return $param; |
||
| 360 | } |
||
| 361 | |||
| 362 | // Check for 'params' which allows parameters to be sent to the instance when it's created |
||
| 363 | // Either as a callback method or to the constructor of the instance |
||
| 364 | $args = isset($param['params']) ? $this->expand($param['params']) : []; |
||
| 365 | |||
| 366 | // for [self::INSTANCE => ['className', 'methodName'] construct the instance before calling it |
||
| 367 | if (\is_array($param[self::INSTANCE])) { |
||
| 368 | $param[self::INSTANCE][0] = $this->expand($param[self::INSTANCE][0], $share, true); |
||
| 369 | } |
||
| 370 | |||
| 371 | if (\is_callable($param[self::INSTANCE])) { |
||
| 372 | // it's a lazy instance formed by a function. Call or return the value stored under the key self::INSTANCE |
||
| 373 | if (isset($param['params']) && is_array($args)) { |
||
| 374 | return \call_user_func_array($param[self::INSTANCE], $args); |
||
| 375 | } |
||
| 376 | |||
| 377 | return \call_user_func($param[self::INSTANCE]); |
||
| 378 | } |
||
| 379 | |||
| 380 | if (\is_string($param[self::INSTANCE])) { |
||
| 381 | // it's a lazy instance's class name string |
||
| 382 | return $this->create($param[self::INSTANCE], (is_array($args)) ? \array_merge($args, $share) : $share); |
||
| 383 | } |
||
| 384 | // if it's not a string, it's malformed. *shrug* |
||
| 385 | } |
||
| 386 | |||
| 387 | /** |
||
| 388 | * @param string $name |
||
| 389 | */ |
||
| 390 | private static function normalizeName($name) |
||
| 393 | } |
||
| 394 | |||
| 395 | /** |
||
| 396 | * @param string $name |
||
| 397 | */ |
||
| 398 | private static function normalizeNamespace($name) |
||
| 401 | } |
||
| 402 | } |
||
| 403 |