4 * This file is part of the Symfony CMF package.
6 * (c) 2011-2015 Symfony CMF
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Cmf\Component\Routing\Candidates;
14 use Symfony\Component\HttpFoundation\Request;
17 * A straightforward strategy that splits the URL on "/".
19 * If locales is set, additionally generates candidates removing the locale if
20 * it is one of the configured locales, for non-locale specific URLs.
22 * @author David Buchmann <mail@davidbu.ch>
24 class Candidates implements CandidatesInterface
32 * A limit to apply to the number of candidates generated.
34 * This is to prevent abusive requests with a lot of "/". The limit is per
35 * batch, that is if a locale matches you could get as many as 2 * $limit
36 * candidates if the URL has that many slashes.
43 * @param array $locales The locales to support.
44 * @param int $limit A limit to apply to the candidates generated.
46 public function __construct(array $locales = array(), $limit = 20)
48 $this->setLocales($locales);
49 $this->limit = $limit;
53 * Set the locales to support by this strategy.
55 * @param array $locales The locales to support.
57 public function setLocales(array $locales)
59 $this->locales = $locales;
65 * Always returns true.
67 public function isCandidate($name)
77 public function restrictQuery($queryBuilder)
84 public function getCandidates(Request $request)
86 $url = $request->getPathInfo();
87 $candidates = $this->getCandidatesFor($url);
89 $locale = $this->determineLocale($url);
91 $candidates = array_unique(array_merge($candidates, $this->getCandidatesFor(substr($url, strlen($locale) + 1))));
98 * Determine the locale of this URL.
100 * @param string $url The url to determine the locale from.
102 * @return string|bool The locale if $url starts with one of the allowed locales.
104 protected function determineLocale($url)
106 if (!count($this->locales)) {
111 if (preg_match('#^/('.implode('|', $this->locales).')(/|$)#', $url, $matches)) {
119 * Handle a possible format extension and split the $url on "/".
121 * $prefix is prepended to every candidate generated.
123 * @param string $url The URL to split.
124 * @param string $prefix A prefix to prepend to every pattern.
126 * @return array Paths that could represent routes that match $url and are
129 protected function getCandidatesFor($url, $prefix = '')
131 $candidates = array();
133 // handle format extension, like .html or .json
134 if (preg_match('/(.+)\.[a-z]+$/i', $url, $matches)) {
135 $candidates[] = $prefix.$url;
141 while (false !== ($pos = strrpos($part, '/'))) {
142 if (++$count > $this->limit) {
145 $candidates[] = $prefix.$part;
146 $part = substr($url, 0, $pos);
150 $candidates[] = $prefix ?: '/';