Skip to content

Commit 8f9db0c

Browse files
committed
adding limit option to candidates
1 parent 2257e14 commit 8f9db0c

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

Candidates/Candidates.php

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,12 +29,25 @@ class Candidates implements CandidatesInterface
2929
*/
3030
protected $locales;
3131

32+
/**
33+
* A limit to apply to the number of candidates generated.
34+
*
35+
* This is to prevent abusive requests with a lot of "/". The limit is per
36+
* batch, that is if a locale matches you could get as many as 2 * $limit
37+
* candidates if the URL has that many slashes.
38+
*
39+
* @var int
40+
*/
41+
protected $limit;
42+
3243
/**
3344
* @param array $locales The locales to support.
45+
* @param int $limit A limit to apply to the candidates generated.
3446
*/
35-
public function __construct(array $locales = array())
47+
public function __construct(array $locales = array(), $limit = 20)
3648
{
3749
$this->setLocales($locales);
50+
$this->limit = $limit;
3851
}
3952

4053
/**
@@ -125,7 +138,11 @@ protected function getCandidatesFor($url, $prefix = '')
125138
}
126139

127140
$part = $url;
141+
$count = 0;
128142
while (false !== ($pos = strrpos($part, '/'))) {
143+
if (++$count > $this->limit) {
144+
return $candidates;
145+
}
129146
$candidates[] = $prefix . $part;
130147
$part = substr($url, 0, $pos);
131148
}

Tests/Candidates/CandidatesTest.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,4 +88,22 @@ public function testGetCandidatesLocales()
8888
$paths
8989
);
9090
}
91+
92+
public function testGetCandidatesLimit()
93+
{
94+
$candidates = new Candidates(array(), 1);
95+
96+
$request = Request::create('/my/path/is/deep.html');
97+
98+
$paths = $candidates->getCandidates($request);
99+
100+
$this->assertEquals(
101+
array(
102+
'/my/path/is/deep.html',
103+
'/my/path/is/deep',
104+
),
105+
$paths
106+
);
107+
108+
}
91109
}

0 commit comments

Comments
 (0)