prestaconcept/PrestaSitemapBundle — pull request #67 by fazy (2014-10-25 13:39:06+00:00)
Title: Make RouteAnnotationEventListener more extensible

An extending class might want to access or filter the routes used in generating the sitemap. Opening the $router property from private to protected and wrapping it in a protected getter allows the child class to influence (e.g. filter) the route collection before it is used by addUrlsFromRoutes().

Here's an example of a class that extends the modified RouteAnnotationEventListener. In this case, I have also injected the `request_stack` service in order to perform host-based matching on the routes, but the main thing is being able to override `getRouteCollection()` and do anything here.

class SitemapEventListener extends RouteAnnotationEventListener
{
/**
* @var \Symfony\Component\HttpFoundation\RequestStack
*/
protected $requestStack;

/**
* @param RouterInterface $router
* @param RequestStack $requestStack
*/
public function __construct(RouterInterface $router, RequestStack $requestStack)
{
parent::__construct($router);
$this->requestStack = $requestStack;
}

/**
* @return \Symfony\Component\Routing\RouteCollection
*/
protected function getRouteCollection()
{
$collection = clone $this->router->getRouteCollection();
$requestHost = $this->requestStack->getCurrentRequest()->getHost();

foreach ($collection as $name => $route) {
$routeHost = $route->getHost();
if (('' !== $routeHost) && ($requestHost !== $routeHost)) {
$collection->remove($name);
}
}

return $collection;
}
}