MutableResourceTypeLinkProvider.php in JSON:API Hypermedia 8
File
examples/Plugin/jsonapi_hypermedia/LinkProvider/MutableResourceTypeLinkProvider.php
View source
<?php
namespace Drupal\jsonapi_hypermedia\Plugin\jsonapi_hypermedia\LinkProvider;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\jsonapi\JsonApiResource\ResourceObject;
use Drupal\jsonapi_hypermedia\AccessRestrictedLink;
use Drupal\jsonapi_hypermedia\Plugin\LinkProviderBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
final class MutableResourceTypeLinkProvider extends LinkProviderBase implements ContainerFactoryPluginInterface {
use ResourceObjectEntityLoaderTrait;
protected $operation;
protected function __construct(array $configuration, string $plugin_id, mixed $plugin_definition) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
assert(!empty($configuration['operation']) && in_array($configuration['operation'], [
'update',
'remove',
], TRUE), "The operation must be set to either 'update' or 'remove'.");
$this->operation = $configuration['operation'];
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
$provider = new static($configuration, $plugin_id, $plugin_definition);
$provider
->setEntityRepository($container
->get('entity.repository'));
return $provider;
}
public function getLink($resource_object) {
assert($resource_object instanceof ResourceObject);
$entity = $this
->loadEntityFromResourceObject($resource_object);
$entity_operation_mapping = [
'update' => 'update',
'remove' => 'delete',
];
$access = $entity
->access($entity_operation_mapping[$this->operation], NULL, TRUE);
return AccessRestrictedLink::createLink($access, new CacheableMetadata(), $resource_object
->toUrl(), $this
->getLinkRelationType());
}
}