LoadMatchingRedirect.php in Acquia Content Hub 8.2
File
modules/acquia_contenthub_subscriber/src/EventSubscriber/LoadLocalEntity/LoadMatchingRedirect.php
View source
<?php
namespace Drupal\acquia_contenthub_subscriber\EventSubscriber\LoadLocalEntity;
use Acquia\ContentHubClient\CDF\CDFObject;
use Drupal\acquia_contenthub\AcquiaContentHubEvents;
use Drupal\acquia_contenthub\Event\LoadLocalEntityEvent;
use Drupal\redirect\Entity\Redirect;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class LoadMatchingRedirect implements EventSubscriberInterface {
public static function getSubscribedEvents() {
$events[AcquiaContentHubEvents::LOAD_LOCAL_ENTITY][] = [
'onLoadLocalEntity',
7,
];
return $events;
}
public function onLoadLocalEntity(LoadLocalEntityEvent $event) {
$cdf = $event
->getCdf();
if (!$this
->isSupported($cdf)) {
return;
}
$data = json_decode(base64_decode($cdf
->getMetadata()['data']), TRUE);
$redirect_source = $data['redirect_source'];
$langcode = $cdf
->getMetadata()['default_language'];
$redirect = $this
->getExistingRedirect($redirect_source, $langcode);
if ($redirect) {
$event
->setEntity($redirect);
$event
->stopPropagation();
}
}
protected function isSupported(CDFObject $cdf_object) : bool {
$type = $cdf_object
->getAttribute('entity_type');
return $type
->getValue()[CDFObject::LANGUAGE_UNDETERMINED] === 'redirect';
}
protected function getExistingRedirect(array $redirect_source, string $langcode) : ?Redirect {
$query = $redirect_source['value'][$langcode]['query'] ?? [];
$path = $redirect_source['value'][$langcode]['path'];
$redirect_repository = \Drupal::service('redirect.repository');
$existing_redirect = $redirect_repository
->findMatchingRedirect($path, $query, $langcode);
return $existing_redirect;
}
}