EntityUuidConverter.php in Drupal 9
File
core/modules/jsonapi/src/ParamConverter/EntityUuidConverter.php
View source
<?php
namespace Drupal\jsonapi\ParamConverter;
use Drupal\Core\Entity\TranslatableInterface;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\ParamConverter\EntityConverter;
use Drupal\jsonapi\Routing\Routes;
use Drupal\Core\Routing\RouteObjectInterface;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\Routing\Route;
class EntityUuidConverter extends EntityConverter {
protected $languageManager;
public function setLanguageManager(LanguageManagerInterface $language_manager) {
$this->languageManager = $language_manager;
}
public function convert($value, $definition, $name, array $defaults) {
$entity_type_id = $this
->getEntityTypeFromDefaults($definition, $name, $defaults);
$uuid_key = $this->entityTypeManager
->getDefinition($entity_type_id)
->getKey('uuid');
if ($storage = $this->entityTypeManager
->getStorage($entity_type_id)) {
if (!($entities = $storage
->loadByProperties([
$uuid_key => $value,
]))) {
return NULL;
}
$entity = reset($entities);
if ($entity instanceof TranslatableInterface && $entity
->isTranslatable()) {
$entity = $this->entityRepository
->getTranslationFromContext($entity, NULL, [
'operation' => 'entity_upcast',
]);
$method = $defaults[RouteObjectInterface::ROUTE_OBJECT]
->getMethods()[0];
if (in_array($method, [
'PATCH',
'DELETE',
], TRUE)) {
$current_content_language = $this->languageManager
->getCurrentLanguage(LanguageInterface::TYPE_CONTENT)
->getId();
if ($method === 'DELETE' && (!$entity
->isDefaultTranslation() || $entity
->language()
->getId() !== $current_content_language)) {
throw new MethodNotAllowedHttpException([
'GET',
], 'Deleting a resource object translation is not yet supported. See https://www.drupal.org/docs/8/modules/jsonapi/translations.');
}
if ($method === 'PATCH' && $entity
->language()
->getId() !== $current_content_language) {
$available_translations = implode(', ', array_keys($entity
->getTranslationLanguages()));
throw new MethodNotAllowedHttpException([
'GET',
], sprintf('The requested translation of the resource object does not exist, instead modify one of the translations that do exist: %s.', $available_translations));
}
}
}
return $entity;
}
return NULL;
}
public function applies($definition, $name, Route $route) {
return (bool) Routes::getResourceTypeNameFromParameters($route
->getDefaults()) && !empty($definition['type']) && strpos($definition['type'], 'entity') === 0;
}
}