vendor/symfony/var-exporter/LazyGhostTrait.php line 38

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