From 41e74e860a47cc80d63ac8e6fcd67dc787781196 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 | 25 +++++++++++ 2 files changed, 84 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..4f4c8aa --- /dev/null +++ b/src/DeferredInArrayValidator.php @@ -0,0 +1,59 @@ +callback = $callback; + + parent::__construct($options); + } + + public function getHaystack(): array + { + if (empty($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 = []; + $this->callback = $callback; + + return $this; + } +} diff --git a/tests/DeferredInArrayValidatorTest.php b/tests/DeferredInArrayValidatorTest.php new file mode 100644 index 0000000..fb43755 --- /dev/null +++ b/tests/DeferredInArrayValidatorTest.php @@ -0,0 +1,25 @@ +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'); + } +}