You are here

EntityUuidConverter.php in JSON:API 8

Same filename and directory in other branches
  1. 8.2 src/ParamConverter/EntityUuidConverter.php

File

src/ParamConverter/EntityUuidConverter.php
View source
<?php

namespace Drupal\jsonapi\ParamConverter;

use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\ParamConverter\EntityConverter;
use Drupal\Core\TypedData\TranslatableInterface;
use Drupal\jsonapi\Routing\Routes;
use Symfony\Component\Routing\Route;

/**
 * Parameter converter for upcasting entity UUIDs to full objects.
 *
 * @see \Drupal\Core\ParamConverter\EntityConverter
 *
 * @todo Remove when https://www.drupal.org/node/2353611 lands.
 *
 * @internal
 */
class EntityUuidConverter extends EntityConverter {

  /**
   * {@inheritdoc}
   */
  public function convert($value, $definition, $name, array $defaults) {
    $entity_type_id = $this
      ->getEntityTypeFromDefaults($definition, $name, $defaults);
    if ($storage = $this->entityManager
      ->getStorage($entity_type_id)) {
      if (!($entities = $storage
        ->loadByProperties([
        'uuid' => $value,
      ]))) {
        return NULL;
      }
      $entity = reset($entities);

      // If the entity type is translatable, ensure we return the proper
      // translation object for the current context.
      if ($entity instanceof EntityInterface && $entity instanceof TranslatableInterface) {
        $entity = $this->entityManager
          ->getTranslationFromContext($entity, NULL, [
          'operation' => 'entity_upcast',
        ]);
      }
      return $entity;
    }
    return NULL;
  }

  /**
   * {@inheritdoc}
   */
  public function applies($definition, $name, Route $route) {
    return (bool) Routes::getResourceTypeNameFromParameters($route
      ->getDefaults()) && !empty($definition['type']) && strpos($definition['type'], 'entity') === 0;
  }

}

Classes

Namesort descending Description
EntityUuidConverter Parameter converter for upcasting entity UUIDs to full objects.