AliasGet.php in Services 9.0.x
File
src/Plugin/ServiceDefinition/AliasGet.php
View source
<?php
namespace Drupal\services\Plugin\ServiceDefinition;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Cache\CacheableDependencyInterface;
use Drupal\path_alias\AliasManagerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\node\Entity\Node;
use Drupal\services\ServiceDefinitionBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\Serializer\SerializerInterface;
class AliasGet extends ServiceDefinitionBase implements ContainerFactoryPluginInterface {
protected $aliasManager;
protected $entity;
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('path.alias_manager'));
}
public function __construct(array $configuration, $plugin_id, $plugin_definition, AliasManagerInterface $alias_manager) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->aliasManager = $alias_manager;
}
public function processRequest(Request $request, RouteMatchInterface $route_match, SerializerInterface $serializer) {
if (!$request->query
->has('path')) {
throw new HttpException(404);
}
$this
->buildResponseObject($request);
return $this->entity
->toArray();
}
public function buildResponseObject($request) {
$alias = $request->query
->get('path');
$path = $this->aliasManager
->getPathByAlias($alias);
if (!strstr('/node/', $path)) {
throw new HttpException(404);
}
$parts = explode('/', $path);
$this->entity = Node::load($parts[2]);
return TRUE;
}
public function getCacheContexts() {
return parent::getCacheContexts();
}
public function getCacheTags() {
$tags = [];
if ($this->entity instanceof CacheableDependencyInterface) {
$tags = Cache::mergeTags($tags, $this->entity
->getCacheTags());
}
return $tags;
}
public function getCacheMaxAge() {
return parent::getCacheMaxAge();
}
}
Classes
Name |
Description |
AliasGet |
Plugin annotation
@ServiceDefinition(
id = "alias_get",
methods = {
"GET"
},
translatable = true,
deriver = "\Drupal\services\Plugin\Deriver\AliasGet"
) |