Skip to content

Commit

Permalink
Use array_diff to Check Endpoint Parameters (#514)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
chrisguitarguy authored and polyfractal committed Dec 16, 2016
1 parent b262dca commit 46f7f36
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 8 deletions.
17 changes: 9 additions & 8 deletions src/Elasticsearch/Endpoints/AbstractEndpoint.php
Original file line number Diff line number Diff line change
Expand Up @@ -214,14 +214,15 @@ private function checkUserParams($params)

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

foreach ($params as $key => $value) {
if (array_search($key, $whitelist) === false) {
throw new UnexpectedValueException(sprintf(
'"%s" is not a valid parameter. Allowed parameters are: "%s"',
$key,
implode('", "', $whitelist)
));
}
$invalid = array_diff(array_keys($params), $whitelist);
if (count($invalid) > 0) {
sort($invalid);
sort($whitelist);
throw new UnexpectedValueException(sprintf(
(count($invalid) > 1 ? '"%s" are not valid parameters.' : '"%s" is not a valid parameter.').' Allowed parameters are "%s"',
implode('", "', $invalid),
implode('", "', $whitelist)
));
}
}

Expand Down
36 changes: 36 additions & 0 deletions tests/Elasticsearch/Tests/Endpoints/AbstractEndpointTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php

namespace Elasticsearch\Tests\Endpoints;

use Elasticsearch\Endpoints\AbstractEndpoint;

class AbstractEndpointTest extends \PHPUnit_Framework_TestCase
{
private $endpoint;

public static function invalidParameters()
{
return [
[['invalid' => 10]],
[['invalid' => 10, 'invalid2' => 'another']],
];
}

/**
* @dataProvider invalidParameters
* @expectedException Elasticsearch\Common\Exceptions\UnexpectedValueException
*/
public function testInvalidParamsCauseErrorsWhenProvidedToSetParams(array $params)
{
$this->endpoint->expects($this->once())
->method('getParamWhitelist')
->willReturn(['one', 'two']);

$this->endpoint->setParams($params);
}

protected function setUp()
{
$this->endpoint = $this->getMockForAbstractClass(AbstractEndpoint::class);
}
}

0 comments on commit 46f7f36

Please sign in to comment.