Skip to content

Commit ad6f7e6

Browse files
authored
Merge pull request #112 from utopia-php/feat-add-multiple-validator
Add multiple validator
2 parents e50d2d1 + f1a2fee commit ad6f7e6

File tree

3 files changed

+190
-40
lines changed

3 files changed

+190
-40
lines changed

composer.lock

Lines changed: 40 additions & 40 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/Validator/Multiple.php

Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
<?php
2+
3+
namespace Utopia\Validator;
4+
5+
use Utopia\Validator;
6+
7+
/**
8+
* Multiple
9+
*
10+
* Multiple validator is a container of multiple validations each acting as a rule.
11+
*
12+
* @package Utopia\Validator
13+
*/
14+
class Multiple extends Validator
15+
{
16+
/**
17+
* @var Validator[]
18+
*/
19+
protected $rules = [];
20+
21+
protected $type = self::TYPE_MIXED;
22+
23+
/**
24+
* Constructor
25+
*
26+
* Multiple constructor can get any number of arguments containing Validator instances using PHP func_get_args function.
27+
*
28+
* Example:
29+
*
30+
* $multiple = new Multiple([$validator1, $validator2]);
31+
* $multiple = new Multiple([$validator1, $validator2, $validator3], self::TYPE_STRING);
32+
*/
33+
public function __construct(array $rules, ?string $type = self::TYPE_MIXED)
34+
{
35+
foreach ($rules as $rule) {
36+
$this->addRule($rule);
37+
}
38+
39+
$this->type = $type;
40+
}
41+
/**
42+
* Add rule
43+
*
44+
* Add a new rule to the end of the rules containing array
45+
*
46+
* @param Validator $rule
47+
* @return $this
48+
*/
49+
public function addRule(Validator $rule)
50+
{
51+
$this->rules[] = $rule;
52+
53+
return $this;
54+
}
55+
56+
/**
57+
* Get Description
58+
*
59+
* Returns validator description
60+
*
61+
* @return string
62+
*/
63+
public function getDescription(): string
64+
{
65+
$description = '';
66+
foreach ($this->rules as $key => $rule) {
67+
$description .= ++$key . '. ' . $rule->getDescription() . " \n";
68+
}
69+
70+
return $description;
71+
}
72+
73+
/**
74+
* Is valid
75+
*
76+
* Validation will pass when all rules are valid if only one of the rules is invalid validation will fail.
77+
*
78+
* @param mixed $value
79+
* @return bool
80+
*/
81+
public function isValid(mixed $value): bool
82+
{
83+
foreach ($this->rules as $rule) { /* @var $rule Validator */
84+
if (false === $rule->isValid($value)) {
85+
return false;
86+
}
87+
}
88+
89+
return true;
90+
}
91+
92+
/**
93+
* Get Type
94+
*
95+
* Returns validator type.
96+
*
97+
* @return string
98+
*/
99+
public function getType(): string
100+
{
101+
return $this->type;
102+
}
103+
104+
/**
105+
* Is array
106+
*
107+
* Function will return true if object is array.
108+
*
109+
* @return bool
110+
*/
111+
public function isArray(): bool
112+
{
113+
return true;
114+
}
115+
}

0 commit comments

Comments
 (0)