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

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