<?php
namespace WAM\Bundle\RoutingBundle\Sitemap;
use WAM\Bundle\RoutingBundle\Sitemap\Interfaces\AlternatesGeneratorInterface;
/**
* Class ChainAlternateRoutesGenerator.
*
* @author Santiago GarcĂa <sangarbe@gmail.com>
*/
class ChainAlternatesGenerator implements AlternatesGeneratorInterface
{
/**
* @var array
*/
private $generators;
/**
* @var array
*/
private $sortedGenerators;
/**
* AlternateRoutesGeneratorChain constructor.
*/
public function __construct()
{
$this->generators = [];
$this->sortedGenerators = [];
}
public function add(
AlternatesGeneratorInterface $alternateRoutesGenerator,
int $priority = 100
)
{
if (!isset($this->generators[$priority])) {
$this->generators[$priority] = [];
}
$this->generators[$priority][] = $alternateRoutesGenerator;
$this->sortedGenerators = [];
}
/**
* @return AlternatesGeneratorInterface[]
*/
private function all()
{
if (!empty($this->sortedGenerators)) {
return $this->sortedGenerators;
}
$this->sortedGenerators = $this->sortGenerators();
return $this->sortedGenerators;
}
private function sortGenerators()
{
if (empty($this->generators)) {
return [];
}
krsort($this->generators);
return array_merge(...$this->generators);
}
/**
* {@inheritdoc}
*/
public function getAlternateRoutes($route, $excludeCurrent = true)
{
foreach ($this->all() as $generator) {
if ($generator->handles($route)) {
return $generator->getAlternateRoutes($route);
}
}
return [];
}
/**
* {@inheritdoc}
*/
public function handles($route)
{
foreach ($this->all() as $generator) {
if ($generator->handles($route)) {
return true;
}
}
return false;
}
/**
* {@inheritdoc}
*/
public function isSitemapRoute($route, $locale)
{
foreach ($this->all() as $generator) {
if ($generator->handles($route)) {
return $generator->isSitemapRoute($route, $locale);
}
}
return false;
}
/**
* {@inheritdoc}
*/
public function getMainRouteUrl($route, $locale)
{
foreach ($this->all() as $generator) {
if ($generator->handles($route)) {
return $generator->getMainRouteUrl($route, $locale);
}
}
return '';
}
}