<?php
declare(strict_types=1);
namespace Hitso\Bundle\RoutingBundle\Router;
use Symfony\Cmf\Component\Routing\DynamicRouter as BaseDynamicRouter;
use Symfony\Cmf\Component\Routing\RouteObjectInterface;
use Symfony\Cmf\Component\Routing\RouteProviderInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Routing\RequestContext;
class AliasRouter extends BaseDynamicRouter
{
const ROUTE_KEY = 'routeDocument';
const CONTENT_KEY = 'contentDocument';
const CONTENT_TEMPLATE = 'contentTemplate';
/**
* @var Request
*/
protected $request;
public function __construct(
RequestContext $context,
$matcher,
UrlGeneratorInterface $generator,
$uriFilterRegexp = '',
EventDispatcherInterface $eventDispatcher = null,
RouteProviderInterface $provider = null
) {
parent::__construct($context, $matcher, $generator, $uriFilterRegexp, $eventDispatcher, $provider);
}
/**
* Put content and template name into the request attributes instead of the
* route defaults.
*
* {@inheritdoc}
*
* The match should identify a controller for symfony. This can either be
* the fully qualified class name or the service name of a controller that
* is registered as a service. In both cases, the action to call on that
* controller is appended, separated with two colons.
*/
public function match($url)
{
$defaults = parent::match($url);
return $this->cleanDefaults($defaults);
}
public function matchRequest(Request $request)
{
$defaults = parent::matchRequest($request);
return $this->cleanDefaults($defaults, $request);
}
/**
* Clean up the match data and move some values into the request attributes.
*
* @param array $defaults The defaults from the match
* @param Request $request The request object if available
*
* @return array the updated defaults to return for this match
*/
protected function cleanDefaults($defaults, Request $request = null)
{
if (null === $request) {
$request = $this->getRequest();
}
if (isset($defaults[RouteObjectInterface::ROUTE_OBJECT])) {
$request->attributes->set(self::ROUTE_KEY, $defaults[RouteObjectInterface::ROUTE_OBJECT]);
unset($defaults[RouteObjectInterface::ROUTE_OBJECT]);
}
return $defaults;
}
/**
* @param Request $request
*/
public function setRequest(Request $request = null)
{
$this->request = $request;
}
/**
* @return Request
*
* @throws ResourceNotFoundException
*/
public function getRequest()
{
if (null === $this->request) {
throw new ResourceNotFoundException('Request object not available from container');
}
return $this->request;
}
}