LazyProxyTrait.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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\Hydrator as PublicHydrator;
  13. use Symfony\Component\VarExporter\Internal\Hydrator;
  14. use Symfony\Component\VarExporter\Internal\LazyObjectRegistry as Registry;
  15. use Symfony\Component\VarExporter\Internal\LazyObjectState;
  16. use Symfony\Component\VarExporter\Internal\LazyObjectTrait;
  17. trait LazyProxyTrait
  18. {
  19. use LazyObjectTrait;
  20. /**
  21. * Creates a lazy-loading virtual proxy.
  22. *
  23. * @param \Closure():object $initializer Returns the proxied object
  24. * @param static|null $instance
  25. */
  26. public static function createLazyProxy(\Closure $initializer, ?object $instance = null): static
  27. {
  28. if (self::class !== $class = $instance ? $instance::class : static::class) {
  29. $skippedProperties = ["\0".self::class."\0lazyObjectState" => true];
  30. } elseif (\defined($class.'::LAZY_OBJECT_PROPERTY_SCOPES')) {
  31. Hydrator::$propertyScopes[$class] ??= $class::LAZY_OBJECT_PROPERTY_SCOPES;
  32. }
  33. $instance ??= (Registry::$classReflectors[$class] ??= new \ReflectionClass($class))->newInstanceWithoutConstructor();
  34. $instance->lazyObjectState = new LazyObjectState($initializer);
  35. foreach (Registry::$classResetters[$class] ??= Registry::getClassResetters($class) as $reset) {
  36. $reset($instance, $skippedProperties ??= []);
  37. }
  38. return $instance;
  39. }
  40. /**
  41. * Returns whether the object is initialized.
  42. *
  43. * @param $partial Whether partially initialized objects should be considered as initialized
  44. */
  45. #[Ignore]
  46. public function isLazyObjectInitialized(bool $partial = false): bool
  47. {
  48. return !isset($this->lazyObjectState) || isset($this->lazyObjectState->realInstance) || Registry::$noInitializerState === $this->lazyObjectState->initializer;
  49. }
  50. /**
  51. * Forces initialization of a lazy object and returns it.
  52. */
  53. public function initializeLazyObject(): parent
  54. {
  55. if ($state = $this->lazyObjectState ?? null) {
  56. return $state->realInstance ??= ($state->initializer)();
  57. }
  58. return $this;
  59. }
  60. /**
  61. * @return bool Returns false when the object cannot be reset, ie when it's not a lazy object
  62. */
  63. public function resetLazyObject(): bool
  64. {
  65. if (!isset($this->lazyObjectState) || Registry::$noInitializerState === $this->lazyObjectState->initializer) {
  66. return false;
  67. }
  68. unset($this->lazyObjectState->realInstance);
  69. return true;
  70. }
  71. public function &__get($name): mixed
  72. {
  73. $propertyScopes = Hydrator::$propertyScopes[$this::class] ??= Hydrator::getPropertyScopes($this::class);
  74. $scope = null;
  75. $instance = $this;
  76. $notByRef = 0;
  77. if ([$class, , $writeScope, $access] = $propertyScopes[$name] ?? null) {
  78. $notByRef = $access & Hydrator::PROPERTY_NOT_BY_REF;
  79. $scope = Registry::getScopeForRead($propertyScopes, $class, $name);
  80. if (null === $scope || isset($propertyScopes["\0$scope\0$name"])) {
  81. if ($state = $this->lazyObjectState ?? null) {
  82. $instance = $state->realInstance ??= ($state->initializer)();
  83. }
  84. if (\PHP_VERSION_ID >= 80400 && !$notByRef && ($access >> 2) & \ReflectionProperty::IS_PRIVATE_SET) {
  85. $scope ??= $writeScope;
  86. }
  87. $parent = 2;
  88. goto get_in_scope;
  89. }
  90. }
  91. $parent = (Registry::$parentMethods[self::class] ??= Registry::getParentMethods(self::class))['get'];
  92. if ($state = $this->lazyObjectState ?? null) {
  93. $instance = $state->realInstance ??= ($state->initializer)();
  94. } else {
  95. if (2 === $parent) {
  96. return parent::__get($name);
  97. }
  98. $value = parent::__get($name);
  99. return $value;
  100. }
  101. if (!$parent && null === $class && !\array_key_exists($name, (array) $instance)) {
  102. $frame = debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 1)[0];
  103. trigger_error(\sprintf('Undefined property: %s::$%s in %s on line %s', $instance::class, $name, $frame['file'], $frame['line']), \E_USER_NOTICE);
  104. }
  105. get_in_scope:
  106. $notByRef = $notByRef || 1 === $parent;
  107. try {
  108. if (null === $scope) {
  109. if (!$notByRef) {
  110. return $instance->$name;
  111. }
  112. $value = $instance->$name;
  113. return $value;
  114. }
  115. $accessor = Registry::$classAccessors[$scope] ??= Registry::getClassAccessors($scope);
  116. return $accessor['get']($instance, $name, $notByRef);
  117. } catch (\Error $e) {
  118. if (\Error::class !== $e::class || !str_starts_with($e->getMessage(), 'Cannot access uninitialized non-nullable property')) {
  119. throw $e;
  120. }
  121. try {
  122. if (null === $scope) {
  123. $instance->$name = [];
  124. return $instance->$name;
  125. }
  126. $accessor['set']($instance, $name, []);
  127. return $accessor['get']($instance, $name, $notByRef);
  128. } catch (\Error) {
  129. throw $e;
  130. }
  131. }
  132. }
  133. public function __set($name, $value): void
  134. {
  135. $propertyScopes = Hydrator::$propertyScopes[$this::class] ??= Hydrator::getPropertyScopes($this::class);
  136. $scope = null;
  137. $instance = $this;
  138. if ([$class, , $writeScope, $access] = $propertyScopes[$name] ?? null) {
  139. $scope = Registry::getScopeForWrite($propertyScopes, $class, $name, $access >> 2);
  140. if ($writeScope === $scope || isset($propertyScopes["\0$scope\0$name"])) {
  141. if ($state = $this->lazyObjectState ?? null) {
  142. $instance = $state->realInstance ??= ($state->initializer)();
  143. }
  144. goto set_in_scope;
  145. }
  146. }
  147. if ($state = $this->lazyObjectState ?? null) {
  148. $instance = $state->realInstance ??= ($state->initializer)();
  149. } elseif ((Registry::$parentMethods[self::class] ??= Registry::getParentMethods(self::class))['set']) {
  150. parent::__set($name, $value);
  151. return;
  152. }
  153. set_in_scope:
  154. if (null === $scope) {
  155. $instance->$name = $value;
  156. } else {
  157. $accessor = Registry::$classAccessors[$scope] ??= Registry::getClassAccessors($scope);
  158. $accessor['set']($instance, $name, $value);
  159. }
  160. }
  161. public function __isset($name): bool
  162. {
  163. $propertyScopes = Hydrator::$propertyScopes[$this::class] ??= Hydrator::getPropertyScopes($this::class);
  164. $scope = null;
  165. $instance = $this;
  166. if ([$class] = $propertyScopes[$name] ?? null) {
  167. $scope = Registry::getScopeForRead($propertyScopes, $class, $name);
  168. if (null === $scope || isset($propertyScopes["\0$scope\0$name"])) {
  169. if ($state = $this->lazyObjectState ?? null) {
  170. $instance = $state->realInstance ??= ($state->initializer)();
  171. }
  172. goto isset_in_scope;
  173. }
  174. }
  175. if ($state = $this->lazyObjectState ?? null) {
  176. $instance = $state->realInstance ??= ($state->initializer)();
  177. } elseif ((Registry::$parentMethods[self::class] ??= Registry::getParentMethods(self::class))['isset']) {
  178. return parent::__isset($name);
  179. }
  180. isset_in_scope:
  181. if (null === $scope) {
  182. return isset($instance->$name);
  183. }
  184. $accessor = Registry::$classAccessors[$scope] ??= Registry::getClassAccessors($scope);
  185. return $accessor['isset']($instance, $name);
  186. }
  187. public function __unset($name): void
  188. {
  189. $propertyScopes = Hydrator::$propertyScopes[$this::class] ??= Hydrator::getPropertyScopes($this::class);
  190. $scope = null;
  191. $instance = $this;
  192. if ([$class, , $writeScope, $access] = $propertyScopes[$name] ?? null) {
  193. $scope = Registry::getScopeForWrite($propertyScopes, $class, $name, $access >> 2);
  194. if ($writeScope === $scope || isset($propertyScopes["\0$scope\0$name"])) {
  195. if ($state = $this->lazyObjectState ?? null) {
  196. $instance = $state->realInstance ??= ($state->initializer)();
  197. }
  198. goto unset_in_scope;
  199. }
  200. }
  201. if ($state = $this->lazyObjectState ?? null) {
  202. $instance = $state->realInstance ??= ($state->initializer)();
  203. } elseif ((Registry::$parentMethods[self::class] ??= Registry::getParentMethods(self::class))['unset']) {
  204. parent::__unset($name);
  205. return;
  206. }
  207. unset_in_scope:
  208. if (null === $scope) {
  209. unset($instance->$name);
  210. } else {
  211. $accessor = Registry::$classAccessors[$scope] ??= Registry::getClassAccessors($scope);
  212. $accessor['unset']($instance, $name);
  213. }
  214. }
  215. public function __clone(): void
  216. {
  217. if (!isset($this->lazyObjectState)) {
  218. if ((Registry::$parentMethods[self::class] ??= Registry::getParentMethods(self::class))['clone']) {
  219. parent::__clone();
  220. }
  221. return;
  222. }
  223. $this->lazyObjectState = clone $this->lazyObjectState;
  224. if (isset($this->lazyObjectState->realInstance)) {
  225. $this->lazyObjectState->realInstance = clone $this->lazyObjectState->realInstance;
  226. }
  227. }
  228. public function __serialize(): array
  229. {
  230. $class = self::class;
  231. $state = $this->lazyObjectState ?? null;
  232. if (!$state && (Registry::$parentMethods[$class] ??= Registry::getParentMethods($class))['serialize']) {
  233. $properties = parent::__serialize();
  234. } else {
  235. $properties = (array) $this;
  236. if ($state) {
  237. unset($properties["\0$class\0lazyObjectState"]);
  238. $properties["\0$class\0lazyObjectReal"] = $state->realInstance ??= ($state->initializer)();
  239. }
  240. }
  241. if ($state || Registry::$parentMethods[$class]['serialize'] || !Registry::$parentMethods[$class]['sleep']) {
  242. return $properties;
  243. }
  244. $scope = get_parent_class($class);
  245. $data = [];
  246. foreach (parent::__sleep() as $name) {
  247. $value = $properties[$k = $name] ?? $properties[$k = "\0*\0$name"] ?? $properties[$k = "\0$class\0$name"] ?? $properties[$k = "\0$scope\0$name"] ?? $k = null;
  248. if (null === $k) {
  249. trigger_error(\sprintf('serialize(): "%s" returned as member variable from __sleep() but does not exist', $name), \E_USER_NOTICE);
  250. } else {
  251. $data[$k] = $value;
  252. }
  253. }
  254. return $data;
  255. }
  256. public function __unserialize(array $data): void
  257. {
  258. $class = self::class;
  259. if ($instance = $data["\0$class\0lazyObjectReal"] ?? null) {
  260. unset($data["\0$class\0lazyObjectReal"]);
  261. foreach (Registry::$classResetters[$class] ??= Registry::getClassResetters($class) as $reset) {
  262. $reset($this, $data);
  263. }
  264. if ($data) {
  265. PublicHydrator::hydrate($this, $data);
  266. }
  267. $this->lazyObjectState = new LazyObjectState(Registry::$noInitializerState ??= static fn () => throw new \LogicException('Lazy proxy has no initializer.'));
  268. $this->lazyObjectState->realInstance = $instance;
  269. } elseif ((Registry::$parentMethods[$class] ??= Registry::getParentMethods($class))['unserialize']) {
  270. parent::__unserialize($data);
  271. } else {
  272. PublicHydrator::hydrate($this, $data);
  273. if (Registry::$parentMethods[$class]['wakeup']) {
  274. parent::__wakeup();
  275. }
  276. }
  277. }
  278. public function __destruct()
  279. {
  280. if (isset($this->lazyObjectState)) {
  281. return;
  282. }
  283. if ((Registry::$parentMethods[self::class] ??= Registry::getParentMethods(self::class))['destruct']) {
  284. parent::__destruct();
  285. }
  286. }
  287. }