From 9ec53fe300824cdeaff0fde6ff9c2e3c345589e3 Mon Sep 17 00:00:00 2001 From: Sukhwinder Dhillon Date: Mon, 14 Nov 2022 17:42:57 +0100 Subject: [PATCH] Introduce `DeferredInArrayValidator` --- src/DeferredInArrayValidator.php | 59 ++++++++++++++++++++++++++ tests/DeferredInArrayValidatorTest.php | 40 +++++++++++++++++ 2 files changed, 99 insertions(+) create mode 100644 src/DeferredInArrayValidator.php create mode 100644 tests/DeferredInArrayValidatorTest.php diff --git a/src/DeferredInArrayValidator.php b/src/DeferredInArrayValidator.php new file mode 100644 index 0000000..d2a1d9f --- /dev/null +++ b/src/DeferredInArrayValidator.php @@ -0,0 +1,59 @@ +callback = $callback; + + parent::__construct($options); + } + + public function getHaystack(): array + { + if (! isset($this->haystack)) { + $this->haystack = call_user_func($this->callback); + } + + return $this->haystack; + } + + /** + * Set the callback + * + * @param callable $callback + * + * @return $this + */ + public function setCallback(callable $callback): self + { + $this->haystack = null; + $this->callback = $callback; + + return $this; + } +} diff --git a/tests/DeferredInArrayValidatorTest.php b/tests/DeferredInArrayValidatorTest.php new file mode 100644 index 0000000..afe7780 --- /dev/null +++ b/tests/DeferredInArrayValidatorTest.php @@ -0,0 +1,40 @@ +assertTrue($validator->isValid('foo'), 'foo was not found in the haystack'); + $this->assertTrue($validator->isValid(5), '5 was not found in the haystack'); + + $this->assertFalse($validator->isValid('bear'), 'bear was found in the haystack'); + $this->assertFalse($validator->isValid(60), '60 was found in the haystack'); + } + + public function testSetCallbackOverwitesTheHaystack() + { + $validator = new DeferredInArrayValidator(function () { + return ['test', 'foo', 'bar']; + }); + + $this->assertSame(['test', 'foo', 'bar'], $validator->getHaystack()); + + $validator->setCallback(function () { + return ['a', 'b', 'c']; + }); + + $this->assertSame(['a', 'b', 'c'], $validator->getHaystack()); + } +}