ShortcutSetController.php 2.39 KB
Newer Older
1
<?php
2

3 4
namespace Drupal\shortcut\Controller;

5
use Drupal\Core\Controller\ControllerBase;
6
use Drupal\Core\Path\PathValidatorInterface;
7
use Drupal\shortcut\ShortcutSetInterface;
8
use Symfony\Component\DependencyInjection\ContainerInterface;
9 10
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
11 12 13 14

/**
 * Builds the page for administering shortcut sets.
 */
15
class ShortcutSetController extends ControllerBase {
16

17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
  /**
   * The path validator.
   *
   * @var \Drupal\Core\Path\PathValidatorInterface
   */
  protected $pathValidator;

  /**
   * Creates a new ShortcutSetController instance.
   *
   * @param \Drupal\Core\Path\PathValidatorInterface $path_validator
   *   The path validator.
   */
  public function __construct(PathValidatorInterface $path_validator) {
    $this->pathValidator = $path_validator;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container->get('path.validator'));
  }

41
  /**
42
   * Creates a new link in the provided shortcut set.
43
   *
44
   * @param \Drupal\shortcut\ShortcutSetInterface $shortcut_set
45 46 47 48 49 50 51 52
   *   The shortcut set to add a link to.
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The request object.
   *
   * @return \Symfony\Component\HttpFoundation\RedirectResponse
   *   A redirect response to the front page, or the previous location.
   *
   * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
53
   */
54
  public function addShortcutLinkInline(ShortcutSetInterface $shortcut_set, Request $request) {
55
    $link = $request->query->get('link');
56
    $name = $request->query->get('name');
57
    if (parse_url($link, PHP_URL_SCHEME) === NULL && $this->pathValidator->isValid($link)) {
58
      $shortcut = $this->entityManager()->getStorage('shortcut')->create([
59 60
        'title' => $name,
        'shortcut_set' => $shortcut_set->id(),
61
        'link' => [
62
          'uri' => 'internal:/' . $link,
63 64
        ],
      ]);
65 66 67

      try {
        $shortcut->save();
68
        $this->messenger()->addStatus($this->t('Added a shortcut for %title.', ['%title' => $shortcut->label()]));
69
      }
70
      catch (\Exception $e) {
71
        $this->messenger()->addError($this->t('Unable to add a shortcut for %title.', ['%title' => $shortcut->label()]));
72
      }
73

74
      return $this->redirect('<front>');
75 76 77
    }

    throw new AccessDeniedHttpException();
78 79 80
  }

}