Skip to content

Commit

Permalink
Introduce DeferredInArrayValidator
Browse files Browse the repository at this point in the history
  • Loading branch information
sukhwinder33445 committed Nov 14, 2022
1 parent 3086373 commit a954df0
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 0 deletions.
36 changes: 36 additions & 0 deletions src/DeferredInArrayValidator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php

namespace ipl\Validator;

class DeferredInArrayValidator extends InArrayValidator
{
/** @var array `key` => `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);
}
}
45 changes: 45 additions & 0 deletions tests/DeferredInArrayValidatorTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php

namespace ipl\Tests\Validator;

use ipl\I18n\NoopTranslator;
use ipl\I18n\StaticTranslator;
use ipl\Validator\DeferredInArrayValidator;

class DeferredInArrayValidatorTest extends TestCase
{
public function testWithValidAndInvalidValue()
{
StaticTranslator::$instance = new NoopTranslator();

$validator = new DeferredInArrayValidator(function () {
return ['test', 'foo', 'bar', 5, [], 0.008];
});

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

0 comments on commit a954df0

Please sign in to comment.