vendor/sulu/sulu/src/Sulu/Component/DocumentManager/Subscriber/Core/InstantiatorSubscriber.php line 89

Open in your IDE?
  1. <?php
  2. /*
  3. * This file is part of Sulu.
  4. *
  5. * (c) Sulu GmbH
  6. *
  7. * This source file is subject to the MIT license that is bundled
  8. * with this source code in the file LICENSE.
  9. */
  10. namespace Sulu\Component\DocumentManager\Subscriber\Core;
  11. use PHPCR\NodeInterface;
  12. use Sulu\Component\DocumentManager\Event\CreateEvent;
  13. use Sulu\Component\DocumentManager\Event\HydrateEvent;
  14. use Sulu\Component\DocumentManager\Events;
  15. use Sulu\Component\DocumentManager\Metadata;
  16. use Sulu\Component\DocumentManager\MetadataFactoryInterface;
  17. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  18. /**
  19. * Responsible for instantiating documents from PHPCR nodes and
  20. * setting the document in the event so that other listeners can
  21. * take further actions (such as hydrating it for example).
  22. *
  23. * NOTE: This should always be the first thing to be called
  24. */
  25. class InstantiatorSubscriber implements EventSubscriberInterface
  26. {
  27. public function __construct(private MetadataFactoryInterface $metadataFactory)
  28. {
  29. }
  30. public static function getSubscribedEvents()
  31. {
  32. return [
  33. Events::HYDRATE => ['handleHydrate', 500],
  34. Events::CREATE => ['handleCreate', 500],
  35. ];
  36. }
  37. public function handleHydrate(HydrateEvent $event)
  38. {
  39. // don't need to instantiate the document if it is already existing.
  40. if ($event->hasDocument()) {
  41. return;
  42. }
  43. $node = $event->getNode();
  44. $document = $this->getDocumentFromNode($node);
  45. $event->setDocument($document);
  46. }
  47. public function handleCreate(CreateEvent $event)
  48. {
  49. $metadata = $this->metadataFactory->getMetadataForAlias($event->getAlias());
  50. $document = $this->instantiateFromMetadata($metadata);
  51. $event->setDocument($document);
  52. }
  53. /**
  54. * Instantiate a new document. The class is determined from
  55. * the mixins present in the PHPCR node for legacy reasons.
  56. *
  57. * @return object
  58. */
  59. private function getDocumentFromNode(NodeInterface $node)
  60. {
  61. $metadata = $this->metadataFactory->getMetadataForPhpcrNode($node);
  62. return $this->instantiateFromMetadata($metadata);
  63. }
  64. /**
  65. * @return object
  66. */
  67. private function instantiateFromMetadata(Metadata $metadata)
  68. {
  69. $class = $metadata->getClass();
  70. if (!\class_exists($class)) {
  71. throw new \RuntimeException(\sprintf(
  72. 'Document class "%s" does not exist', $class
  73. ));
  74. }
  75. $document = new $class();
  76. return $document;
  77. }
  78. }