From 46f7f3697a739ba88716431fc60f92f437d1d56e Mon Sep 17 00:00:00 2001 From: Christopher Davis Date: Fri, 16 Dec 2016 16:14:38 -0500 Subject: [PATCH] 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. --- .../Endpoints/AbstractEndpoint.php | 17 ++++----- .../Tests/Endpoints/AbstractEndpointTest.php | 36 +++++++++++++++++++ 2 files changed, 45 insertions(+), 8 deletions(-) create mode 100644 tests/Elasticsearch/Tests/Endpoints/AbstractEndpointTest.php diff --git a/src/Elasticsearch/Endpoints/AbstractEndpoint.php b/src/Elasticsearch/Endpoints/AbstractEndpoint.php index 0cfb68ea2..115e11064 100644 --- a/src/Elasticsearch/Endpoints/AbstractEndpoint.php +++ b/src/Elasticsearch/Endpoints/AbstractEndpoint.php @@ -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) + )); } } diff --git a/tests/Elasticsearch/Tests/Endpoints/AbstractEndpointTest.php b/tests/Elasticsearch/Tests/Endpoints/AbstractEndpointTest.php new file mode 100644 index 000000000..51701e37e --- /dev/null +++ b/tests/Elasticsearch/Tests/Endpoints/AbstractEndpointTest.php @@ -0,0 +1,36 @@ + 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); + } +}