Skip to content

Commit

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

namespace ipl\Validator;

/**
* Validates whether the value exists in the haystack created by the callback
*/
class DeferredInArrayValidator extends InArrayValidator
{
/** @var callable Callback to create the haystack array */
protected $callback;

/**
* Create a new deferredInArray validator
*
* **Required parameter:**
*
* - `callback`: (`callable`) The callback to create haystack
*
* **Optional parameter:**
*
* *options: (`array`) Following option can be defined:*
*
* * `strict`: (`bool`) Whether the types of the needle in the haystack should also match, default `false`
*
* @param callable $callback Validation callback
* @param array $options
*/
public function __construct(callable $callback, array $options = [])
{
$this->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;
}
}
25 changes: 25 additions & 0 deletions tests/DeferredInArrayValidatorTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

namespace ipl\Tests\Validator;

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

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

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

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

0 comments on commit 41e74e8

Please sign in to comment.