From a954df0c8acbdfb5abab23d52eccef24ae4c758c 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 | 36 +++++++++++++++++++++ tests/DeferredInArrayValidatorTest.php | 45 ++++++++++++++++++++++++++ 2 files changed, 81 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..b331354 --- /dev/null +++ b/src/DeferredInArrayValidator.php @@ -0,0 +1,36 @@ + `value` pair of options */ + protected $options; + + /** + * Validates whether the value exists in the haystack create by the callback + * + * Required parameter: + * + * - callback: (callable) The callback to create haystack + * + * Optional parameter: + * + * - options: (array) Following options can be defined: + * + * `strict` => true|false, default `false` + * + * `recursive` => true|false, default `false` + * + * @param callable $callback Validation callback + * @param array $options + * + * @throws \Exception + */ + public function __construct(callable $callback, array $options = []) + { + $options['haystack'] = $callback(); + + parent::__construct($options); + } +} \ No newline at end of file diff --git a/tests/DeferredInArrayValidatorTest.php b/tests/DeferredInArrayValidatorTest.php new file mode 100644 index 0000000..c2ae7fd --- /dev/null +++ b/tests/DeferredInArrayValidatorTest.php @@ -0,0 +1,45 @@ +assertTrue($validator->isValid('foo'), 'foo was found in the haystack'); + $this->assertTrue($validator->isValid(5), '5 was 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 testOptions() + { + StaticTranslator::$instance = new NoopTranslator(); + + $validator = new DeferredInArrayValidator( + function () { + return ['test', 'foo', 'bar', 5, [], 0.008]; + }, + ['strict' => true] + ); + + $this->assertTrue($validator->isStrict()); + + $validator->setStrict(false); + $this->assertFalse($validator->isStrict()); + + $validator->setRecursive(); + $this->assertTrue($validator->isRecursive()); + } +}