Skip to content

Commit

Permalink
Redirector can redirect
Browse files Browse the repository at this point in the history
  • Loading branch information
I-Valchev committed Jul 30, 2021
1 parent c82304d commit 0d9f477
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 11 deletions.
10 changes: 8 additions & 2 deletions config/config.yaml
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
# Reference extension configuration file

redirects:
foo: bar
#redirects:
# from: to
#
# from can be the full URI or the absolute path,
# e.g. https://example.org/page/about or /page/about
#
# "https://example.org/page/about: "/page/about-us"
# "/page/mission": "/page/our-mission"
4 changes: 0 additions & 4 deletions config/routes.yaml
Original file line number Diff line number Diff line change
@@ -1,4 +0,0 @@

reference_extension:
resource: '../../vendor/acmecorp/reference-extension/src/Controller/'
type: annotation
17 changes: 14 additions & 3 deletions src/RedirectSubscriber.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,20 @@
use Bolt\Widget\Injector\RequestZone;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class RedirectSubscriber implements EventSubscriberInterface
{
public function onKernelRequest(RequestEvent $event): void
/** @var Redirector */
private $redirector;

public function __construct(Redirector $redirector)
{
$this->redirector = $redirector;
}

public function onKernelResponse(ResponseEvent $event): void
{
$request = $event->getRequest();

Expand All @@ -25,6 +33,7 @@ public function onKernelRequest(RequestEvent $event): void
$request->getPathInfo()
];


$redirect = $this->redirector->findFor($locations);

if ($redirect) {
Expand All @@ -34,8 +43,10 @@ public function onKernelRequest(RequestEvent $event): void

public static function getSubscribedEvents()
{
// todo: If we can get the config from Bolt in the request,
// let's listen to that instead, because it's faster.
return [
KernelEvents::REQUEST => [['onKernelRequest', 20]]
KernelEvents::RESPONSE => [['onKernelResponse', 0]]
];
}
}
9 changes: 7 additions & 2 deletions src/Redirector.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,13 @@ public function __construct(Config $config)

public function findFor(array $locations): ?string
{
$redirects = array_intersect_key($locations, $this->config->getRedirects());
$redirects = $this->config->getRedirects();
$redirectKey = current(array_intersect($locations, array_keys($redirects)));

return current($redirects) ?? null;
if ($redirectKey) {
return $this->config->getRedirects()[$redirectKey];
}

return null;
}
}

0 comments on commit 0d9f477

Please sign in to comment.