Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add multiple validator #112

Merged
merged 4 commits into from
Dec 26, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 11 additions & 8 deletions src/Validator/Multiple.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,25 +18,28 @@ class Multiple extends Validator
*/
protected $rules = [];

protected $type = self::TYPE_MIXED;

/**
* Constructor
*
* Multiple constructor can get any number of arguments containing Validator instances using PHP func_get_args function.
*
* Example:
*
* $multiple = new Multiple($validator1, $validator2, $validator3);
* $multiple = new Multiple([$validator1, $validator2]);
* $multiple = new Multiple([$validator1, $validator2, $validator3], SELF::TYPE_STRING);
*/
public function __construct()
public function __construct(array $rules, ?string $type = null)
{
// array of all method arguments
$rules = \func_get_args();

foreach ($rules as $rule) {
$this->addRule($rule);
}
}

if ($type !== null) {
$this->type = $type;
}
}
/**
* Add rule
*
Expand All @@ -63,7 +66,7 @@ public function getDescription(): string
{
$description = '';
foreach ($this->rules as $key => $rule) {
$description .= ++$key . '. ' . $rule->getDescription() . " \n";
$description .= ++$key . '. ' . $rule->getDescription() . " \\n";
}

return $description;
Expand Down Expand Up @@ -97,7 +100,7 @@ public function isValid(mixed $value): bool
*/
public function getType(): string
{
return self::TYPE_MIXED;
return $this->type;
}

/**
Expand Down
4 changes: 3 additions & 1 deletion tests/Validator/MultipleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,13 @@ class MultipleTest extends TestCase

public function setUp(): void
{
$this->validator = new Multiple(new Text(20), new URL());
$this->validator = new Multiple([new Text(20), new URL()]);
}

public function testIsValid()
{
$this->assertEquals('1. Value must be a valid string and at least 1 chars and no longer than 20 chars \n2. Value must be a valid URL \n', $this->validator->getDescription());

// Valid URL but invalid text length
$this->assertFalse($this->validator->isValid('http://example.com/very-long-url'));

Expand Down