From 5ae871ed80b659dd76133f0ab3cf5a1584b6213b Mon Sep 17 00:00:00 2001 From: Mario Trojan Date: Wed, 3 Apr 2024 14:49:39 +0200 Subject: [PATCH] ParamBag: Avoid duplicate parameters after merge (#3368) --- .../src/VuFindSearch/ParamBag.php | 10 ++++-- .../src/VuFindTest/ParamBagTest.php | 35 +++++++++++++++++++ 2 files changed, 42 insertions(+), 3 deletions(-) diff --git a/module/VuFindSearch/src/VuFindSearch/ParamBag.php b/module/VuFindSearch/src/VuFindSearch/ParamBag.php index 44c56b82c1d..8abf07b2189 100644 --- a/module/VuFindSearch/src/VuFindSearch/ParamBag.php +++ b/module/VuFindSearch/src/VuFindSearch/ParamBag.php @@ -151,12 +151,13 @@ public function remove($name) /** * Add parameter value. * - * @param string $name Parameter name - * @param mixed $value Parameter value + * @param string $name Parameter name + * @param mixed $value Parameter value + * @param bool $deduplicate Deduplicate parameter values * * @return void */ - public function add($name, $value) + public function add($name, $value, $deduplicate = true) { if (!isset($this->params[$name])) { $this->params[$name] = []; @@ -166,6 +167,9 @@ public function add($name, $value) } else { $this->params[$name][] = $value; } + if ($deduplicate) { + $this->params[$name] = array_values(array_unique($this->params[$name])); + } } /** diff --git a/module/VuFindSearch/tests/unit-tests/src/VuFindTest/ParamBagTest.php b/module/VuFindSearch/tests/unit-tests/src/VuFindTest/ParamBagTest.php index cbb6467d656..ff7feeaa4a4 100644 --- a/module/VuFindSearch/tests/unit-tests/src/VuFindTest/ParamBagTest.php +++ b/module/VuFindSearch/tests/unit-tests/src/VuFindTest/ParamBagTest.php @@ -112,4 +112,39 @@ public function testCountability() $bag->set('xyzzy', 'baz'); $this->assertCount(2, $bag); } + + /** + * Test deduplication + * + * @return void + */ + public function testDeduplication() + { + $bag = new ParamBag(); + $bag->add('foo', 'bar'); + $bag->add('foo', 'bar'); + $bag->add('foo', ['bar', 'bar', 'bar']); + $this->assertEquals(['bar'], $bag->get('foo')); + $bag->add('foo', ['bar', 'baz', 'bar', 'baz']); + $this->assertEquals(['bar', 'baz'], $bag->get('foo')); + } + + /** + * Test disabling deduplication + * + * @return void + */ + public function testDisabledDeduplication() + { + $bag = new ParamBag(); + $bag->add('foo', 'bar', false); + $bag->add('foo', 'bar', false); + $bag->add('foo', ['bar', 'bar', 'bar'], false); + $this->assertEquals(['bar', 'bar', 'bar', 'bar', 'bar'], $bag->get('foo')); + $bag->add('foo', ['bar', 'baz', 'bar', 'baz'], false); + $this->assertEquals(['bar', 'bar', 'bar', 'bar', 'bar', 'bar', 'baz', 'bar', 'baz'], $bag->get('foo')); + // Now deduplicate everything: + $bag->add('foo', 'bar'); + $this->assertEquals(['bar', 'baz'], $bag->get('foo')); + } }