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:
| 1 | <?php |
||
| 20 | trait GeneratorProxyTrait |
||
| 21 | { |
||
| 22 | /** |
||
| 23 | * Overload this for correct type hint on object type. |
||
| 24 | * |
||
| 25 | * @var object|null |
||
| 26 | */ |
||
| 27 | protected $object; |
||
| 28 | |||
| 29 | /** |
||
| 30 | * Needs to be protected as value objects often define this as well. |
||
| 31 | * |
||
| 32 | * @var mixed |
||
| 33 | */ |
||
| 34 | protected $id; |
||
| 35 | |||
| 36 | /** |
||
| 37 | * @var Generator|null |
||
| 38 | */ |
||
| 39 | private $generator; |
||
| 40 | |||
| 41 | /** |
||
| 42 | * GeneratorProxyTrait constructor. |
||
| 43 | * |
||
| 44 | * @param Generator $generator |
||
| 45 | * @param mixed $id Object id to use for loading the object on demand. |
||
| 46 | */ |
||
| 47 | public function __construct(Generator $generator, $id) |
||
| 52 | |||
| 53 | public function __call($name, $arguments) |
||
| 61 | |||
| 62 | public function __invoke(...$args) |
||
| 70 | |||
| 71 | View Code Duplication | public function __get($name) |
|
| 83 | |||
| 84 | View Code Duplication | public function __isset($name) |
|
| 96 | |||
| 97 | public function __unset($name) |
||
| 105 | |||
| 106 | public function __set($name, $value) |
||
| 114 | |||
| 115 | public function __toString() |
||
| 123 | |||
| 124 | public function __sleep() |
||
| 132 | |||
| 133 | public function __debugInfo() |
||
| 144 | |||
| 145 | /** |
||
| 146 | * Loads the generator to object value and unset's generator. |
||
| 147 | * |
||
| 148 | * Can only be called once, so check presence of $this->object before using it. |
||
| 149 | * |
||
| 150 | * This assumes generator is made to support bulk loading of several objects, and thus takes object id as input |
||
| 151 | * in order to return right object at a time, and thus performs two yields per item. |
||
| 152 | * -> See PR that came with this trait for example generators. |
||
| 153 | */ |
||
| 154 | protected function loadObject() |
||
| 160 | } |
||
| 161 |