4a3b0a20591d3bc69f3a4a1b10134445e404ead3
[yaffs-website] / web / core / modules / serialization / src / EntityResolver / UuidResolver.php
1 <?php
2
3 namespace Drupal\serialization\EntityResolver;
4
5 use Drupal\Core\Entity\EntityManagerInterface;
6 use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
7
8 /**
9  * Resolves entities from data that contains an entity UUID.
10  */
11 class UuidResolver implements EntityResolverInterface {
12
13   /**
14    * The entity manager.
15    *
16    * @var \Drupal\Core\Entity\EntityManagerInterface
17    */
18   protected $entityManager;
19
20   /**
21    * Constructs a UuidResolver object.
22    *
23    * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
24    *   The entity manager.
25    */
26   public function __construct(EntityManagerInterface $entity_manager) {
27     $this->entityManager = $entity_manager;
28   }
29
30   /**
31    * {@inheritdoc}
32    */
33   public function resolve(NormalizerInterface $normalizer, $data, $entity_type) {
34     // The normalizer is what knows the specification of the data being
35     // deserialized. If it can return a UUID from that data, and if there's an
36     // entity with that UUID, then return its ID.
37     if (($normalizer instanceof UuidReferenceInterface) && ($uuid = $normalizer->getUuid($data))) {
38       if ($entity = $this->entityManager->loadEntityByUuid($entity_type, $uuid)) {
39         return $entity->id();
40       }
41     }
42     return NULL;
43   }
44
45 }