LazyGhostTrait.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\VarExporter;
  11. use Symfony\Component\Serializer\Attribute\Ignore;
  12. use Symfony\Component\VarExporter\Internal\Hydrator;
  13. use Symfony\Component\VarExporter\Internal\LazyObjectRegistry as Registry;
  14. use Symfony\Component\VarExporter\Internal\LazyObjectState;
  15. use Symfony\Component\VarExporter\Internal\LazyObjectTrait;
  16. if (\PHP_VERSION_ID >= 80400) {
  17. trigger_deprecation('symfony/var-exporter', '7.3', 'The "%s" trait is deprecated, use native lazy objects instead.', LazyGhostTrait::class);
  18. }
  19. /**
  20. * @deprecated since Symfony 7.3, use native lazy objects instead
  21. */
  22. trait LazyGhostTrait
  23. {
  24. use LazyObjectTrait;
  25. /**
  26. * Creates a lazy-loading ghost instance.
  27. *
  28. * Skipped properties should be indexed by their array-cast identifier, see
  29. * https://php.net/manual/language.types.array#language.types.array.casting
  30. *
  31. * @param \Closure(static):void $initializer The closure should initialize the object it receives as argument
  32. * @param array<string, true>|null $skippedProperties An array indexed by the properties to skip, a.k.a. the ones
  33. * that the initializer doesn't initialize, if any
  34. * @param static|null $instance
  35. */
  36. public static function createLazyGhost(\Closure $initializer, ?array $skippedProperties = null, ?object $instance = null): static
  37. {
  38. if (self::class !== $class = $instance ? $instance::class : static::class) {
  39. $skippedProperties["\0".self::class."\0lazyObjectState"] = true;
  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. if (self::class === $class && \defined($class.'::LAZY_OBJECT_PROPERTY_SCOPES')) {
  47. Hydrator::$propertyScopes[$class] ??= $class::LAZY_OBJECT_PROPERTY_SCOPES;
  48. }
  49. } else {
  50. $instance ??= Registry::$classReflectors[$class]->newInstanceWithoutConstructor();
  51. }
  52. if (isset($instance->lazyObjectState)) {
  53. $instance->lazyObjectState->initializer = $initializer;
  54. $instance->lazyObjectState->skippedProperties = $skippedProperties ??= [];
  55. if (LazyObjectState::STATUS_UNINITIALIZED_FULL !== $instance->lazyObjectState->status) {
  56. $instance->lazyObjectState->reset($instance);
  57. }
  58. return $instance;
  59. }
  60. $instance->lazyObjectState = new LazyObjectState($initializer, $skippedProperties ??= []);
  61. foreach (Registry::$classResetters[$class] as $reset) {
  62. $reset($instance, $skippedProperties);
  63. }
  64. return $instance;
  65. }
  66. /**
  67. * Returns whether the object is initialized.
  68. *
  69. * @param bool $partial Whether partially initialized objects should be considered as initialized
  70. */
  71. #[Ignore]
  72. public function isLazyObjectInitialized(bool $partial = false): bool
  73. {
  74. if (!$state = $this->lazyObjectState ?? null) {
  75. return true;
  76. }
  77. return LazyObjectState::STATUS_INITIALIZED_FULL === $state->status;
  78. }
  79. /**
  80. * Forces initialization of a lazy object and returns it.
  81. */
  82. public function initializeLazyObject(): static
  83. {
  84. if (!$state = $this->lazyObjectState ?? null) {
  85. return $this;
  86. }
  87. if (LazyObjectState::STATUS_UNINITIALIZED_FULL === $state->status) {
  88. $state->initialize($this, '', null);
  89. }
  90. return $this;
  91. }
  92. /**
  93. * @return bool Returns false when the object cannot be reset, ie when it's not a lazy object
  94. */
  95. public function resetLazyObject(): bool
  96. {
  97. if (!$state = $this->lazyObjectState ?? null) {
  98. return false;
  99. }
  100. if (LazyObjectState::STATUS_UNINITIALIZED_FULL !== $state->status) {
  101. $state->reset($this);
  102. }
  103. return true;
  104. }
  105. public function &__get($name): mixed
  106. {
  107. $propertyScopes = Hydrator::$propertyScopes[$this::class] ??= Hydrator::getPropertyScopes($this::class);
  108. $scope = null;
  109. $notByRef = 0;
  110. if ([$class, , $writeScope, $access] = $propertyScopes[$name] ?? null) {
  111. $scope = Registry::getScopeForRead($propertyScopes, $class, $name);
  112. $state = $this->lazyObjectState ?? null;
  113. if ($state && (null === $scope || isset($propertyScopes["\0$scope\0$name"]))) {
  114. $notByRef = $access & Hydrator::PROPERTY_NOT_BY_REF;
  115. if (LazyObjectState::STATUS_INITIALIZED_FULL === $state->status) {
  116. // Work around php/php-src#12695
  117. $property = null === $scope ? $name : "\0$scope\0$name";
  118. $property = $propertyScopes[$property][4]
  119. ?? Hydrator::$propertyScopes[$this::class][$property][4] = new \ReflectionProperty($scope ?? $class, $name);
  120. } else {
  121. $property = null;
  122. }
  123. if (\PHP_VERSION_ID >= 80400 && !$notByRef && ($access >> 2) & \ReflectionProperty::IS_PRIVATE_SET) {
  124. $scope ??= $writeScope;
  125. }
  126. if ($property?->isInitialized($this) ?? LazyObjectState::STATUS_UNINITIALIZED_PARTIAL !== $state->initialize($this, $name, $writeScope ?? $scope)) {
  127. goto get_in_scope;
  128. }
  129. }
  130. }
  131. if ($parent = (Registry::$parentMethods[self::class] ??= Registry::getParentMethods(self::class))['get']) {
  132. if (2 === $parent) {
  133. return parent::__get($name);
  134. }
  135. $value = parent::__get($name);
  136. return $value;
  137. }
  138. if (null === $class) {
  139. $frame = debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 1)[0];
  140. trigger_error(\sprintf('Undefined property: %s::$%s in %s on line %s', $this::class, $name, $frame['file'], $frame['line']), \E_USER_NOTICE);
  141. }
  142. get_in_scope:
  143. try {
  144. if (null === $scope) {
  145. if (!$notByRef) {
  146. return $this->$name;
  147. }
  148. $value = $this->$name;
  149. return $value;
  150. }
  151. $accessor = Registry::$classAccessors[$scope] ??= Registry::getClassAccessors($scope);
  152. return $accessor['get']($this, $name, $notByRef);
  153. } catch (\Error $e) {
  154. if (\Error::class !== $e::class || !str_starts_with($e->getMessage(), 'Cannot access uninitialized non-nullable property')) {
  155. throw $e;
  156. }
  157. try {
  158. if (null === $scope) {
  159. $this->$name = [];
  160. return $this->$name;
  161. }
  162. $accessor['set']($this, $name, []);
  163. return $accessor['get']($this, $name, $notByRef);
  164. } catch (\Error) {
  165. if (preg_match('/^Cannot access uninitialized non-nullable property ([^ ]++) by reference$/', $e->getMessage(), $matches)) {
  166. throw new \Error('Typed property '.$matches[1].' must not be accessed before initialization', $e->getCode(), $e->getPrevious());
  167. }
  168. throw $e;
  169. }
  170. }
  171. }
  172. public function __set($name, $value): void
  173. {
  174. $propertyScopes = Hydrator::$propertyScopes[$this::class] ??= Hydrator::getPropertyScopes($this::class);
  175. $scope = null;
  176. if ([$class, , $writeScope, $access] = $propertyScopes[$name] ?? null) {
  177. $scope = Registry::getScopeForWrite($propertyScopes, $class, $name, $access >> 2);
  178. $state = $this->lazyObjectState ?? null;
  179. if ($state && ($writeScope === $scope || isset($propertyScopes["\0$scope\0$name"]))
  180. && LazyObjectState::STATUS_INITIALIZED_FULL !== $state->status
  181. ) {
  182. if (LazyObjectState::STATUS_UNINITIALIZED_FULL === $state->status) {
  183. $state->initialize($this, $name, $writeScope ?? $scope);
  184. }
  185. goto set_in_scope;
  186. }
  187. }
  188. if ((Registry::$parentMethods[self::class] ??= Registry::getParentMethods(self::class))['set']) {
  189. parent::__set($name, $value);
  190. return;
  191. }
  192. set_in_scope:
  193. if (null === $scope) {
  194. $this->$name = $value;
  195. } else {
  196. $accessor = Registry::$classAccessors[$scope] ??= Registry::getClassAccessors($scope);
  197. $accessor['set']($this, $name, $value);
  198. }
  199. }
  200. public function __isset($name): bool
  201. {
  202. $propertyScopes = Hydrator::$propertyScopes[$this::class] ??= Hydrator::getPropertyScopes($this::class);
  203. $scope = null;
  204. if ([$class, , $writeScope] = $propertyScopes[$name] ?? null) {
  205. $scope = Registry::getScopeForRead($propertyScopes, $class, $name);
  206. $state = $this->lazyObjectState ?? null;
  207. if ($state && (null === $scope || isset($propertyScopes["\0$scope\0$name"]))
  208. && LazyObjectState::STATUS_INITIALIZED_FULL !== $state->status
  209. && LazyObjectState::STATUS_UNINITIALIZED_PARTIAL !== $state->initialize($this, $name, $writeScope ?? $scope)
  210. ) {
  211. goto isset_in_scope;
  212. }
  213. }
  214. if ((Registry::$parentMethods[self::class] ??= Registry::getParentMethods(self::class))['isset']) {
  215. return parent::__isset($name);
  216. }
  217. isset_in_scope:
  218. if (null === $scope) {
  219. return isset($this->$name);
  220. }
  221. $accessor = Registry::$classAccessors[$scope] ??= Registry::getClassAccessors($scope);
  222. return $accessor['isset']($this, $name);
  223. }
  224. public function __unset($name): void
  225. {
  226. $propertyScopes = Hydrator::$propertyScopes[$this::class] ??= Hydrator::getPropertyScopes($this::class);
  227. $scope = null;
  228. if ([$class, , $writeScope, $access] = $propertyScopes[$name] ?? null) {
  229. $scope = Registry::getScopeForWrite($propertyScopes, $class, $name, $access >> 2);
  230. $state = $this->lazyObjectState ?? null;
  231. if ($state && ($writeScope === $scope || isset($propertyScopes["\0$scope\0$name"]))
  232. && LazyObjectState::STATUS_INITIALIZED_FULL !== $state->status
  233. ) {
  234. if (LazyObjectState::STATUS_UNINITIALIZED_FULL === $state->status) {
  235. $state->initialize($this, $name, $writeScope ?? $scope);
  236. }
  237. goto unset_in_scope;
  238. }
  239. }
  240. if ((Registry::$parentMethods[self::class] ??= Registry::getParentMethods(self::class))['unset']) {
  241. parent::__unset($name);
  242. return;
  243. }
  244. unset_in_scope:
  245. if (null === $scope) {
  246. unset($this->$name);
  247. } else {
  248. $accessor = Registry::$classAccessors[$scope] ??= Registry::getClassAccessors($scope);
  249. $accessor['unset']($this, $name);
  250. }
  251. }
  252. public function __clone(): void
  253. {
  254. if ($state = $this->lazyObjectState ?? null) {
  255. $this->lazyObjectState = clone $state;
  256. }
  257. if ((Registry::$parentMethods[self::class] ??= Registry::getParentMethods(self::class))['clone']) {
  258. parent::__clone();
  259. }
  260. }
  261. public function __serialize(): array
  262. {
  263. $class = self::class;
  264. if ((Registry::$parentMethods[$class] ??= Registry::getParentMethods($class))['serialize']) {
  265. $properties = parent::__serialize();
  266. } else {
  267. $this->initializeLazyObject();
  268. $properties = (array) $this;
  269. }
  270. unset($properties["\0$class\0lazyObjectState"]);
  271. if (Registry::$parentMethods[$class]['serialize'] || !Registry::$parentMethods[$class]['sleep']) {
  272. return $properties;
  273. }
  274. $scope = get_parent_class($class);
  275. $data = [];
  276. foreach (parent::__sleep() as $name) {
  277. $value = $properties[$k = $name] ?? $properties[$k = "\0*\0$name"] ?? $properties[$k = "\0$class\0$name"] ?? $properties[$k = "\0$scope\0$name"] ?? $k = null;
  278. if (null === $k) {
  279. trigger_error(\sprintf('serialize(): "%s" returned as member variable from __sleep() but does not exist', $name), \E_USER_NOTICE);
  280. } else {
  281. $data[$k] = $value;
  282. }
  283. }
  284. return $data;
  285. }
  286. public function __destruct()
  287. {
  288. $state = $this->lazyObjectState ?? null;
  289. if (LazyObjectState::STATUS_UNINITIALIZED_FULL === $state?->status) {
  290. return;
  291. }
  292. if ((Registry::$parentMethods[self::class] ??= Registry::getParentMethods(self::class))['destruct']) {
  293. parent::__destruct();
  294. }
  295. }
  296. #[Ignore]
  297. private function setLazyObjectAsInitialized(bool $initialized): void
  298. {
  299. if ($state = $this->lazyObjectState ?? null) {
  300. $state->status = $initialized ? LazyObjectState::STATUS_INITIALIZED_FULL : LazyObjectState::STATUS_UNINITIALIZED_FULL;
  301. }
  302. }
  303. }