Skip to content

Instantly share code, notes, and snippets.

@simesy
Created June 6, 2018 10:30
Show Gist options
  • Select an option

  • Save simesy/8d6a1980cdcb2c4d6ca92154c7dd887b to your computer and use it in GitHub Desktop.

Select an option

Save simesy/8d6a1980cdcb2c4d6ca92154c7dd887b to your computer and use it in GitHub Desktop.
Rosolve internal links - change MYMODULE and put in src/Plugin/jsonapi/FieldEnhancer
<?php
namespace Drupal\MYMODULE\Plugin\jsonapi\FieldEnhancer;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\jsonapi_extras\Plugin\ResourceFieldEnhancerBase;
use Shaper\Util\Context;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Url;
/**
* Resolve a aliased URI for internal link field value.
*
* @ResourceFieldEnhancer(
* id = "aliased_link",
* label = @Translation("Resolve an aliased URL for internal links."),
* description = @Translation("Use a aliased URL for internal links instead of links like entity:node/123")
* )
*/
class AliasedLinkEnhancer extends ResourceFieldEnhancerBase implements ContainerFactoryPluginInterface {
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* {@inheritdoc}
*/
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;
}
/**
* {@inheritdoc}
*/
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')
);
}
/**
* {@inheritdoc}
*/
protected function doUndoTransform($data, Context $context) {
$output = $data;
if (isset($output['uri'])) {
// Check if it is a link to an entity.
preg_match("/entity:(.*)\/(.*)/", $output['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)) {
$output['url'] = Url::fromUri($output['uri'], $output['options'])->toString();
}
// Unable to load the entity, so remove the value.
else {
$output = [
'uri' => '',
'url' => '',
'title' => '',
'options' => [],
];
}
}
else {
// Assume it's an external link which can be used as-is.
$output['url'] = $output['uri'];
}
}
return $output;
}
/**
* {@inheritdoc}
*/
protected function doTransform($data, Context $context) {
$input = $data;
unset($input['url']);
return $input;
}
/**
* {@inheritdoc}
*/
public function getOutputJsonSchema() {
return [
'type' => 'any',
];
}
/**
* {@inheritdoc}
*/
public function getJsonSchema() {
return [
'type' => 'array',
];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment