You are here

class RequestSubscriber in Content Translation Redirect 8

Redirect subscriber for controller requests.

Hierarchy

Expanded class hierarchy of RequestSubscriber

1 string reference to 'RequestSubscriber'
content_translation_redirect.services.yml in ./content_translation_redirect.services.yml
content_translation_redirect.services.yml
1 service uses RequestSubscriber
content_translation_redirect.request_subscriber in ./content_translation_redirect.services.yml
Drupal\content_translation_redirect\EventSubscriber\RequestSubscriber

File

src/EventSubscriber/RequestSubscriber.php, line 23

Namespace

Drupal\content_translation_redirect\EventSubscriber
View source
class RequestSubscriber implements EventSubscriberInterface {
  use StringTranslationTrait;
  use MessengerTrait;

  /**
   * Configuration object with default settings.
   *
   * @var \Drupal\Core\Config\ImmutableConfig
   */
  protected $config;

  /**
   * The language manager.
   *
   * @var \Drupal\Core\Language\LanguageManagerInterface
   */
  protected $languageManager;

  /**
   * Content translation redirects storage.
   *
   * @var \Drupal\Core\Config\Entity\ConfigEntityStorageInterface
   */
  protected $storage;

  /**
   * The currently active route match object.
   *
   * @var \Drupal\Core\Routing\RouteMatchInterface
   */
  protected $routeMatch;

  /**
   * ContentTranslationRedirectRequestSubscriber constructor.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The config factory.
   * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
   *   The language manager.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
   *   The currently active route match object.
   */
  public function __construct(ConfigFactoryInterface $config_factory, LanguageManagerInterface $language_manager, EntityTypeManagerInterface $entity_type_manager, RouteMatchInterface $route_match) {
    $this->config = $config_factory
      ->get('content_translation_redirect.default');
    $this->languageManager = $language_manager;
    $this->storage = $entity_type_manager
      ->getStorage('content_translation_redirect');
    $this->routeMatch = $route_match;
  }

  /**
   * Handles the redirect if any found.
   *
   * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
   *   The event to process.
   */
  public function onRequestCheckRedirect(GetResponseEvent $event) {

    /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
    $entity = $this
      ->checkContentEntityCanonicalRoute();
    if ($entity && $entity
      ->isTranslatable()) {

      // Get current language and entity translation language.
      $current_language = $this->languageManager
        ->getCurrentLanguage(LanguageInterface::TYPE_CONTENT);
      $entity_language = $entity
        ->language();

      // Get redirect entity ID.
      $redirect_entity_id = $entity
        ->getEntityTypeId() . '__' . $entity
        ->bundle();

      // Check translation into current language.

      /** @var \Drupal\content_translation_redirect\ContentTranslationRedirectInterface $redirect_entity */
      if ($entity_language
        ->getId() != $current_language
        ->getId() && ($redirect_entity = $this->storage
        ->load($redirect_entity_id))) {

        // Get current path.
        $url = Url::fromRoute('<current>')
          ->setAbsolute();
        $current_path = $url
          ->toString();

        // Get redirect path to page in original language.
        $original_language = $entity
          ->getUntranslated()
          ->language();
        $url
          ->setOption('language', $original_language);
        $redirect_path = $url
          ->toString();

        // Redirect if the current path is not equal to the redirection path.
        if ($redirect_path != $current_path) {
          $status_code = $redirect_entity
            ->getStatusCode() ?: $this->config
            ->get('code');
          $message = $redirect_entity
            ->getMessage() ?: $this->config
            ->get('message');
          $response = new LocalRedirectResponse($redirect_path, $status_code);
          $response
            ->addCacheableDependency($url);
          $event
            ->setResponse($response);

          // Show warning message.
          if ($message) {

            // Get translated language name.
            $language_name = $this->languageManager
              ->getLanguageName($current_language
              ->getId());

            // Give the opportunity to display the name of the language
            // for which there is no translation.
            $message = new FormattableMarkup($message, [
              '%language' => $language_name,
            ]);
            $this
              ->messenger()
              ->addWarning($message);
          }
        }
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = [
      'onRequestCheckRedirect',
    ];
    return $events;
  }

  /**
   * Check that the current route is the content entity canonical route.
   *
   * @return \Drupal\Core\Entity\ContentEntityInterface|bool
   *   The entity instance. FALSE if no entity is matched.
   */
  protected function checkContentEntityCanonicalRoute() {

    // Get current route name from route match.
    $route_name = $this->routeMatch
      ->getRouteName();

    // If no route is matched.
    if (empty($route_name)) {
      return FALSE;
    }

    // Trying to find the Entity Type ID in the route parameters.
    foreach ($this->routeMatch
      ->getParameters() as $parameter) {
      if ($parameter instanceof ContentEntityInterface) {
        try {

          // Compare entity canonical URL with current URL.
          $entity_route_name = $parameter
            ->toUrl()
            ->getRouteName();
          if ($entity_route_name == $route_name) {
            return $parameter;
          }
        } catch (\Exception $e) {

          // There is no canonical URL for this entity,
          // proceed to the next entity.
          continue;
        }
      }
    }
    return FALSE;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RequestSubscriber::$config protected property Configuration object with default settings.
RequestSubscriber::$languageManager protected property The language manager.
RequestSubscriber::$routeMatch protected property The currently active route match object.
RequestSubscriber::$storage protected property Content translation redirects storage.
RequestSubscriber::checkContentEntityCanonicalRoute protected function Check that the current route is the content entity canonical route.
RequestSubscriber::getSubscribedEvents public static function Returns an array of event names this subscriber wants to listen to.
RequestSubscriber::onRequestCheckRedirect public function Handles the redirect if any found.
RequestSubscriber::__construct public function ContentTranslationRedirectRequestSubscriber constructor.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.