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()); + } +}