Total Complexity | 81 |
Total Lines | 347 |
Duplicated Lines | 0 % |
Changes | 0 |
Complex classes like LazyGhostTrait 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 LazyGhostTrait, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
20 | trait LazyGhostTrait |
||
21 | { |
||
22 | use LazyObjectTrait; |
||
23 | |||
24 | /** |
||
25 | * Creates a lazy-loading ghost instance. |
||
26 | * |
||
27 | * Skipped properties should be indexed by their array-cast identifier, see |
||
28 | * https://php.net/manual/language.types.array#language.types.array.casting |
||
29 | * |
||
30 | * @param \Closure(static):void $initializer The closure should initialize the object it receives as argument |
||
31 | * @param array<string, true>|null $skippedProperties An array indexed by the properties to skip, a.k.a. the ones |
||
32 | * that the initializer doesn't initialize, if any |
||
33 | * @param static|null $instance |
||
34 | */ |
||
35 | public static function createLazyGhost(\Closure $initializer, ?array $skippedProperties = null, ?object $instance = null): static |
||
36 | { |
||
37 | if (self::class !== $class = $instance ? $instance::class : static::class) { |
||
38 | $skippedProperties["\0".self::class."\0lazyObjectState"] = true; |
||
39 | } |
||
40 | |||
41 | if (!isset(Registry::$defaultProperties[$class])) { |
||
42 | Registry::$classReflectors[$class] ??= new \ReflectionClass($class); |
||
43 | $instance ??= Registry::$classReflectors[$class]->newInstanceWithoutConstructor(); |
||
44 | Registry::$defaultProperties[$class] ??= (array) $instance; |
||
45 | Registry::$classResetters[$class] ??= Registry::getClassResetters($class); |
||
46 | |||
47 | if (self::class === $class && \defined($class.'::LAZY_OBJECT_PROPERTY_SCOPES')) { |
||
48 | Hydrator::$propertyScopes[$class] ??= $class::LAZY_OBJECT_PROPERTY_SCOPES; |
||
49 | } |
||
50 | } else { |
||
51 | $instance ??= Registry::$classReflectors[$class]->newInstanceWithoutConstructor(); |
||
52 | } |
||
53 | |||
54 | if (isset($instance->lazyObjectState)) { |
||
55 | $instance->lazyObjectState->initializer = $initializer; |
||
56 | $instance->lazyObjectState->skippedProperties = $skippedProperties ??= []; |
||
57 | |||
58 | if (LazyObjectState::STATUS_UNINITIALIZED_FULL !== $instance->lazyObjectState->status) { |
||
59 | $instance->lazyObjectState->reset($instance); |
||
60 | } |
||
61 | |||
62 | return $instance; |
||
63 | } |
||
64 | |||
65 | $instance->lazyObjectState = new LazyObjectState($initializer, $skippedProperties ??= []); |
||
66 | |||
67 | foreach (Registry::$classResetters[$class] as $reset) { |
||
68 | $reset($instance, $skippedProperties); |
||
69 | } |
||
70 | |||
71 | return $instance; |
||
72 | } |
||
73 | |||
74 | /** |
||
75 | * Returns whether the object is initialized. |
||
76 | * |
||
77 | * @param bool $partial Whether partially initialized objects should be considered as initialized |
||
78 | */ |
||
79 | #[Ignore] |
||
80 | public function isLazyObjectInitialized(bool $partial = false): bool |
||
81 | { |
||
82 | if (!$state = $this->lazyObjectState ?? null) { |
||
83 | return true; |
||
84 | } |
||
85 | |||
86 | return LazyObjectState::STATUS_INITIALIZED_FULL === $state->status; |
||
87 | } |
||
88 | |||
89 | /** |
||
90 | * Forces initialization of a lazy object and returns it. |
||
91 | */ |
||
92 | public function initializeLazyObject(): static |
||
93 | { |
||
94 | if (!$state = $this->lazyObjectState ?? null) { |
||
95 | return $this; |
||
96 | } |
||
97 | |||
98 | if (LazyObjectState::STATUS_UNINITIALIZED_FULL === $state->status) { |
||
99 | $state->initialize($this, '', null); |
||
100 | } |
||
101 | |||
102 | return $this; |
||
103 | } |
||
104 | |||
105 | /** |
||
106 | * @return bool Returns false when the object cannot be reset, ie when it's not a lazy object |
||
107 | */ |
||
108 | public function resetLazyObject(): bool |
||
109 | { |
||
110 | if (!$state = $this->lazyObjectState ?? null) { |
||
111 | return false; |
||
112 | } |
||
113 | |||
114 | if (LazyObjectState::STATUS_UNINITIALIZED_FULL !== $state->status) { |
||
115 | $state->reset($this); |
||
116 | } |
||
117 | |||
118 | return true; |
||
119 | } |
||
120 | |||
121 | public function &__get($name): mixed |
||
122 | { |
||
123 | $propertyScopes = Hydrator::$propertyScopes[$this::class] ??= Hydrator::getPropertyScopes($this::class); |
||
124 | $scope = null; |
||
125 | $notByRef = 0; |
||
126 | |||
127 | if ([$class, , $writeScope, $access] = $propertyScopes[$name] ?? null) { |
||
128 | $scope = Registry::getScopeForRead($propertyScopes, $class, $name); |
||
129 | $state = $this->lazyObjectState ?? null; |
||
130 | |||
131 | if ($state && (null === $scope || isset($propertyScopes["\0$scope\0$name"]))) { |
||
132 | $notByRef = $access & Hydrator::PROPERTY_NOT_BY_REF; |
||
133 | |||
134 | if (LazyObjectState::STATUS_INITIALIZED_FULL === $state->status) { |
||
135 | // Work around php/php-src#12695 |
||
136 | $property = null === $scope ? $name : "\0$scope\0$name"; |
||
137 | $property = $propertyScopes[$property][4] |
||
138 | ?? Hydrator::$propertyScopes[$this::class][$property][4] = new \ReflectionProperty($scope ?? $class, $name); |
||
139 | } else { |
||
140 | $property = null; |
||
141 | } |
||
142 | if (\PHP_VERSION_ID >= 80400 && !$notByRef && ($access >> 2) & \ReflectionProperty::IS_PRIVATE_SET) { |
||
143 | $scope ??= $writeScope; |
||
144 | } |
||
145 | |||
146 | if ($property?->isInitialized($this) ?? LazyObjectState::STATUS_UNINITIALIZED_PARTIAL !== $state->initialize($this, $name, $writeScope ?? $scope)) { |
||
147 | goto get_in_scope; |
||
148 | } |
||
149 | } |
||
150 | } |
||
151 | |||
152 | if ($parent = (Registry::$parentMethods[self::class] ??= Registry::getParentMethods(self::class))['get']) { |
||
153 | if (2 === $parent) { |
||
154 | return parent::__get($name); |
||
155 | } |
||
156 | $value = parent::__get($name); |
||
157 | |||
158 | return $value; |
||
159 | } |
||
160 | |||
161 | if (null === $class) { |
||
162 | $frame = debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 1)[0]; |
||
163 | trigger_error(\sprintf('Undefined property: %s::$%s in %s on line %s', $this::class, $name, $frame['file'], $frame['line']), \E_USER_NOTICE); |
||
164 | } |
||
165 | |||
166 | get_in_scope: |
||
167 | |||
168 | try { |
||
169 | if (null === $scope) { |
||
170 | if (!$notByRef) { |
||
171 | return $this->$name; |
||
172 | } |
||
173 | $value = $this->$name; |
||
174 | |||
175 | return $value; |
||
176 | } |
||
177 | $accessor = Registry::$classAccessors[$scope] ??= Registry::getClassAccessors($scope); |
||
178 | |||
179 | return $accessor['get']($this, $name, $notByRef); |
||
180 | } catch (\Error $e) { |
||
181 | if (\Error::class !== $e::class || !str_starts_with($e->getMessage(), 'Cannot access uninitialized non-nullable property')) { |
||
182 | throw $e; |
||
183 | } |
||
184 | |||
185 | try { |
||
186 | if (null === $scope) { |
||
187 | $this->$name = []; |
||
188 | |||
189 | return $this->$name; |
||
190 | } |
||
191 | |||
192 | $accessor['set']($this, $name, []); |
||
193 | |||
194 | return $accessor['get']($this, $name, $notByRef); |
||
195 | } catch (\Error) { |
||
196 | if (preg_match('/^Cannot access uninitialized non-nullable property ([^ ]++) by reference$/', $e->getMessage(), $matches)) { |
||
197 | throw new \Error('Typed property '.$matches[1].' must not be accessed before initialization', $e->getCode(), $e->getPrevious()); |
||
198 | } |
||
199 | |||
200 | throw $e; |
||
201 | } |
||
202 | } |
||
203 | } |
||
204 | |||
205 | public function __set($name, $value): void |
||
237 | } |
||
238 | } |
||
239 | |||
240 | public function __isset($name): bool |
||
269 | } |
||
270 | |||
271 | public function __unset($name): void |
||
272 | { |
||
273 | $propertyScopes = Hydrator::$propertyScopes[$this::class] ??= Hydrator::getPropertyScopes($this::class); |
||
274 | $scope = null; |
||
275 | |||
276 | if ([$class, , $writeScope, $access] = $propertyScopes[$name] ?? null) { |
||
277 | $scope = Registry::getScopeForWrite($propertyScopes, $class, $name, $access >> 2); |
||
278 | $state = $this->lazyObjectState ?? null; |
||
279 | |||
280 | if ($state && ($writeScope === $scope || isset($propertyScopes["\0$scope\0$name"])) |
||
281 | && LazyObjectState::STATUS_INITIALIZED_FULL !== $state->status |
||
282 | ) { |
||
283 | if (LazyObjectState::STATUS_UNINITIALIZED_FULL === $state->status) { |
||
284 | $state->initialize($this, $name, $writeScope ?? $scope); |
||
285 | } |
||
286 | goto unset_in_scope; |
||
287 | } |
||
288 | } |
||
289 | |||
290 | if ((Registry::$parentMethods[self::class] ??= Registry::getParentMethods(self::class))['unset']) { |
||
291 | parent::__unset($name); |
||
292 | |||
293 | return; |
||
294 | } |
||
295 | |||
296 | unset_in_scope: |
||
297 | |||
298 | if (null === $scope) { |
||
299 | unset($this->$name); |
||
300 | } else { |
||
301 | $accessor = Registry::$classAccessors[$scope] ??= Registry::getClassAccessors($scope); |
||
302 | $accessor['unset']($this, $name); |
||
303 | } |
||
304 | } |
||
305 | |||
306 | public function __clone(): void |
||
307 | { |
||
308 | if ($state = $this->lazyObjectState ?? null) { |
||
309 | $this->lazyObjectState = clone $state; |
||
310 | } |
||
311 | |||
312 | if ((Registry::$parentMethods[self::class] ??= Registry::getParentMethods(self::class))['clone']) { |
||
313 | parent::__clone(); |
||
314 | } |
||
315 | } |
||
316 | |||
317 | public function __serialize(): array |
||
347 | } |
||
348 | |||
349 | public function __destruct() |
||
350 | { |
||
351 | $state = $this->lazyObjectState ?? null; |
||
352 | |||
353 | if (LazyObjectState::STATUS_UNINITIALIZED_FULL === $state?->status) { |
||
354 | return; |
||
355 | } |
||
356 | |||
357 | if ((Registry::$parentMethods[self::class] ??= Registry::getParentMethods(self::class))['destruct']) { |
||
358 | parent::__destruct(); |
||
359 | } |
||
360 | } |
||
361 | |||
362 | #[Ignore] |
||
367 | } |
||
368 | } |
||
369 | } |
||
370 |
Let?s assume that you have a directory layout like this:
and let?s assume the following content of
Bar.php
:If both files
OtherDir/Foo.php
andSomeDir/Foo.php
are loaded in the same runtime, you will see a PHP error such as the following:PHP Fatal error: Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php
However, as
OtherDir/Foo.php
does not necessarily have to be loaded and the error is only triggered if it is loaded beforeOtherDir/Bar.php
, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias: