You are here

public function EntityPublishedInterfaceLinkProvider::getLink in JSON:API Hypermedia 8

Adds, alters or removes hyperlinks from a link collection.

Parameters

\Drupal\jsonapi\JsonApiResource\JsonApiDocumentTopLevel|\Drupal\jsonapi\JsonApiResource\ResourceObject|\Drupal\jsonapi\JsonApiResource\Relationship $context: The context object from which links should be generated.

Return value

\Drupal\jsonapi_hypermedia\AccessRestrictedLink A link to be added to the context object. An AccessRestrictedLink should be returned if the link target may be inaccessible to some users.

Overrides LinkProviderInterface::getLink

File

examples/Plugin/jsonapi_hypermedia/LinkProvider/EntityPublishedInterfaceLinkProvider.php, line 65

Class

EntityPublishedInterfaceLinkProvider
Class EntityPublishedInterfaceLinkProvider.

Namespace

Drupal\jsonapi_hypermedia\Plugin\jsonapi_hypermedia\LinkProvider

Code

public function getLink($resource_object) {
  assert($resource_object instanceof ResourceObject);
  $resource_type = $resource_object
    ->getResourceType();
  $entity = $this
    ->loadEntityFromResourceObject($resource_object);
  assert($entity instanceof EntityPublishedInterface);
  $plugin_definition = $this
    ->getPluginDefinition();
  $published = $entity
    ->isPublished();
  $publish_operation = $plugin_definition['link_key'] === 'publish';
  $access_result = AccessResult::allowedIf($publish_operation !== $published)
    ->andIf($entity
    ->access('update', NULL, TRUE))
    ->andIf($entity->{$this->statusFieldName}
    ->access('edit', NULL, TRUE))
    ->addCacheableDependency($entity);
  $link_attributes = [
    'data' => [
      'type' => $resource_object
        ->getTypeName(),
      'id' => $resource_object
        ->getId(),
      'attributes' => [
        $resource_type
          ->getPublicName($this->statusFieldName) => (int) (!$published),
      ],
    ],
  ];
  return AccessRestrictedLink::createLink($access_result, CacheableMetadata::createFromObject($resource_object), $resource_object
    ->toUrl(), $this
    ->getLinkRelationType(), $link_attributes);
}