View source
<?php
namespace Drupal\Core\Action\Plugin\Action;
use Drupal\Component\Utility\UrlHelper;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Action\ConfigurableActionBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Utility\UnroutedUrlAssemblerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;
class GotoAction extends ConfigurableActionBase implements ContainerFactoryPluginInterface {
protected $dispatcher;
protected $unroutedUrlAssembler;
public function __construct(array $configuration, $plugin_id, $plugin_definition, EventDispatcherInterface $dispatcher, UnroutedUrlAssemblerInterface $url_assembler) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->dispatcher = $dispatcher;
$this->unroutedUrlAssembler = $url_assembler;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('event_dispatcher'), $container
->get('unrouted_url_assembler'));
}
public function execute($object = NULL) {
$url = $this->configuration['url'];
if (!UrlHelper::isExternal($url)) {
$parts = UrlHelper::parse($url);
if ($parts['path'] === '<front>') {
$parts['path'] = '';
}
$uri = 'base:' . $parts['path'];
$options = [
'query' => $parts['query'],
'fragment' => $parts['fragment'],
'absolute' => TRUE,
];
$url = $this->unroutedUrlAssembler
->assemble($uri, $options);
}
$response = new RedirectResponse($url);
$listener = function ($event) use ($response) {
$event
->setResponse($response);
};
$this->dispatcher
->addListener(KernelEvents::RESPONSE, $listener);
}
public function defaultConfiguration() {
return [
'url' => '',
];
}
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$form['url'] = [
'#type' => 'textfield',
'#title' => t('URL'),
'#description' => t('The URL to which the user should be redirected. This can be an internal URL like /node/1234 or an external URL like @url.', [
'@url' => 'http://example.com',
]),
'#default_value' => $this->configuration['url'],
'#required' => TRUE,
];
return $form;
}
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
$this->configuration['url'] = $form_state
->getValue('url');
}
public function access($object, AccountInterface $account = NULL, $return_as_object = FALSE) {
$access = AccessResult::allowed();
return $return_as_object ? $access : $access
->isAllowed();
}
}