Instantiator.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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\Exception\ExceptionInterface;
  12. use Symfony\Component\VarExporter\Exception\NotInstantiableTypeException;
  13. use Symfony\Component\VarExporter\Internal\Registry;
  14. /**
  15. * A utility class to create objects without calling their constructor.
  16. *
  17. * @author Nicolas Grekas <p@tchwork.com>
  18. */
  19. final class Instantiator
  20. {
  21. /**
  22. * Creates an object and sets its properties without calling its constructor nor any other methods.
  23. *
  24. * @see Hydrator::hydrate() for examples
  25. *
  26. * @template T of object
  27. *
  28. * @param class-string<T> $class The class of the instance to create
  29. * @param array<string, mixed> $properties The properties to set on the instance
  30. * @param array<class-string, array<string, mixed>> $scopedProperties The properties to set on the instance,
  31. * keyed by their declaring class
  32. *
  33. * @return T
  34. *
  35. * @throws ExceptionInterface When the instance cannot be created
  36. */
  37. public static function instantiate(string $class, array $properties = [], array $scopedProperties = []): object
  38. {
  39. $reflector = Registry::$reflectors[$class] ??= Registry::getClassReflector($class);
  40. if (Registry::$cloneable[$class]) {
  41. $instance = clone Registry::$prototypes[$class];
  42. } elseif (Registry::$instantiableWithoutConstructor[$class]) {
  43. $instance = $reflector->newInstanceWithoutConstructor();
  44. } elseif (null === Registry::$prototypes[$class]) {
  45. throw new NotInstantiableTypeException($class);
  46. } elseif ($reflector->implementsInterface('Serializable') && !method_exists($class, '__unserialize')) {
  47. $instance = unserialize('C:'.\strlen($class).':"'.$class.'":0:{}');
  48. } else {
  49. $instance = unserialize('O:'.\strlen($class).':"'.$class.'":0:{}');
  50. }
  51. return $properties || $scopedProperties ? Hydrator::hydrate($instance, $properties, $scopedProperties) : $instance;
  52. }
  53. }