View source
<?php
namespace Drupal\jsonapi_extras\Plugin\jsonapi\FieldEnhancer;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Url;
use Drupal\jsonapi_extras\Plugin\ResourceFieldEnhancerBase;
use Shaper\Util\Context;
use Symfony\Component\DependencyInjection\ContainerInterface;
class UrlLinkEnhancer extends ResourceFieldEnhancerBase implements ContainerFactoryPluginInterface {
protected $languageManager;
protected $logger;
public function __construct(array $configuration, $plugin_id, array $plugin_definition, LanguageManagerInterface $language_manager, LoggerChannelFactoryInterface $logger_factory) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->languageManager = $language_manager;
$this->logger = $logger_factory
->get('jsonapi_extras');
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('language_manager'), $container
->get('logger.factory'));
}
public function defaultConfiguration() {
return [
'absolute_url' => 0,
];
}
public function getSettingsForm(array $resource_field_info) {
$settings = empty($resource_field_info['enhancer']['settings']) ? $this
->getConfiguration() : $resource_field_info['enhancer']['settings'];
$form = parent::getSettingsForm($resource_field_info);
$form['absolute_url'] = [
'#type' => 'checkbox',
'#title' => $this
->t('Get Absolute Urls'),
'#default_value' => $settings['absolute_url'],
];
return $form;
}
protected function doUndoTransform($data, Context $context) {
if (isset($data['uri'])) {
try {
$url = Url::fromUri($data['uri'], [
'language' => $this->languageManager
->getCurrentLanguage(),
]);
$configuration = $this
->getConfiguration();
if ($configuration['absolute_url']) {
$url
->setAbsolute(TRUE);
}
$data['url'] = $url
->toString();
} catch (\Exception $e) {
$this->logger
->error('Failed to create a URL from uri @uri. Error: @error', [
'@uri' => $data['uri'],
'@error' => $e
->getMessage(),
]);
}
}
return $data;
}
protected function doTransform($value, Context $context) {
}
public function getOutputJsonSchema() {
return [
'type' => 'object',
'properties' => [
'uri' => [
'type' => 'string',
],
'title' => [
'type' => 'string',
],
'options' => [
'type' => 'array',
],
'url' => [
'type' => 'string',
],
],
];
}
}