UuidLinkEnhancer.php in JSON:API Extras 8
File
src/Plugin/jsonapi/FieldEnhancer/UuidLinkEnhancer.php
View source
<?php
namespace Drupal\jsonapi_extras\Plugin\jsonapi\FieldEnhancer;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\jsonapi_extras\Plugin\ResourceFieldEnhancerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
class UuidLinkEnhancer extends ResourceFieldEnhancerBase implements ContainerFactoryPluginInterface {
protected $entityTypeManager;
public function __construct(array $configuration, $plugin_id, array $plugin_definition, EntityTypeManagerInterface $entity_type_manager) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->entityTypeManager = $entity_type_manager;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('entity_type.manager'));
}
public function postProcess($value) {
if (isset($value['uri'])) {
preg_match("/entity:(.*)\\/(.*)/", $value['uri'], $parsed_uri);
if (!empty($parsed_uri)) {
$entity_type = $parsed_uri[1];
$entity_id = $parsed_uri[2];
$entity = $this->entityTypeManager
->getStorage($entity_type)
->load($entity_id);
if (!is_null($entity)) {
$value['uri'] = 'entity:' . $entity_type . '/' . $entity
->bundle() . '/' . $entity
->uuid();
}
else {
$value = [
'uri' => '',
'title' => '',
'options' => [],
];
}
}
}
return $value;
}
public function prepareForInput($value) {
if (isset($value['uri'])) {
preg_match("/entity:(.*)\\/(.*)\\/(.*)/", $value['uri'], $parsed_uri);
if (!empty($parsed_uri)) {
$entity_type = $parsed_uri[1];
$entity_uuid = $parsed_uri[3];
$entities = $this->entityTypeManager
->getStorage($entity_type)
->loadByProperties([
'uuid' => $entity_uuid,
]);
if (!empty($entities)) {
$entity = array_shift($entities);
$value['uri'] = 'entity:' . $entity_type . '/' . $entity
->id();
}
else {
$value = [];
}
}
}
return $value;
}
public function getJsonSchema() {
return [
'type' => 'object',
];
}
}