Skip to content

Commit 46f7f36

Browse files
chrisguitarguypolyfractal
authored andcommitted
Use array_diff to Check Endpoint Parameters (#514)
Slightly nicer than the old array_search method that iterates through every user provided param. Also gives the user feed back on *all* invalid parameters at once, rather than just one at a time.
1 parent b262dca commit 46f7f36

File tree

2 files changed

+45
-8
lines changed

2 files changed

+45
-8
lines changed

src/Elasticsearch/Endpoints/AbstractEndpoint.php

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -214,14 +214,15 @@ private function checkUserParams($params)
214214

215215
$whitelist = array_merge($this->getParamWhitelist(), array('client', 'custom', 'filter_path'));
216216

217-
foreach ($params as $key => $value) {
218-
if (array_search($key, $whitelist) === false) {
219-
throw new UnexpectedValueException(sprintf(
220-
'"%s" is not a valid parameter. Allowed parameters are: "%s"',
221-
$key,
222-
implode('", "', $whitelist)
223-
));
224-
}
217+
$invalid = array_diff(array_keys($params), $whitelist);
218+
if (count($invalid) > 0) {
219+
sort($invalid);
220+
sort($whitelist);
221+
throw new UnexpectedValueException(sprintf(
222+
(count($invalid) > 1 ? '"%s" are not valid parameters.' : '"%s" is not a valid parameter.').' Allowed parameters are "%s"',
223+
implode('", "', $invalid),
224+
implode('", "', $whitelist)
225+
));
225226
}
226227
}
227228

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
<?php
2+
3+
namespace Elasticsearch\Tests\Endpoints;
4+
5+
use Elasticsearch\Endpoints\AbstractEndpoint;
6+
7+
class AbstractEndpointTest extends \PHPUnit_Framework_TestCase
8+
{
9+
private $endpoint;
10+
11+
public static function invalidParameters()
12+
{
13+
return [
14+
[['invalid' => 10]],
15+
[['invalid' => 10, 'invalid2' => 'another']],
16+
];
17+
}
18+
19+
/**
20+
* @dataProvider invalidParameters
21+
* @expectedException Elasticsearch\Common\Exceptions\UnexpectedValueException
22+
*/
23+
public function testInvalidParamsCauseErrorsWhenProvidedToSetParams(array $params)
24+
{
25+
$this->endpoint->expects($this->once())
26+
->method('getParamWhitelist')
27+
->willReturn(['one', 'two']);
28+
29+
$this->endpoint->setParams($params);
30+
}
31+
32+
protected function setUp()
33+
{
34+
$this->endpoint = $this->getMockForAbstractClass(AbstractEndpoint::class);
35+
}
36+
}

0 commit comments

Comments
 (0)