Skip to content

Commit

Permalink
Added AnyOf Validator
Browse files Browse the repository at this point in the history
  • Loading branch information
vermakhushboo committed Aug 1, 2024
1 parent 8fe57da commit 9f07728
Show file tree
Hide file tree
Showing 3 changed files with 114 additions and 35 deletions.
87 changes: 87 additions & 0 deletions src/Validator/AnyOf.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
<?php

namespace Utopia\Validator;

use Utopia\Validator;

/**
* Ensure at least one validator from a list passed the check
*
* @package Utopia\Validator
*/
class AnyOf extends Validator
{
protected ?Validator $failedRule = null;

/**
* @param array<Validator> $validators
*/
public function __construct(protected array $validators, protected string $type = self::TYPE_MIXED)
{
}

/**
* Get Description
*
* Returns validator description
*
* @return string
*/
public function getDescription(): string
{
if (!(\is_null($this->failedRule))) {
$description = $this->failedRule->getDescription();
} else {
$description = $this->validators[0]->getDescription();
}

return $description;
}

/**
* Is valid
*
* Validation will pass when all rules are valid if only one of the rules is invalid validation will fail.
*
* @param mixed $value
* @return bool
*/
public function isValid(mixed $value): bool
{
foreach ($this->validators as $rule) {
$valid = $rule->isValid($value);

$this->failedRule = $rule;

if ($valid) {
return true;
}
}

return false;
}

/**
* Get Type
*
* Returns validator type.
*
* @return string
*/
public function getType(): string
{
return $this->type;
}

/**
* Is array
*
* Function will return true if object is array.
*
* @return bool
*/
public function isArray(): bool
{
return true;
}
}
27 changes: 27 additions & 0 deletions tests/Validator/MultipleOfTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

namespace Utopia\Validator;

use PHPUnit\Framework\TestCase;
use Utopia\Validator;

class MultipleOfTest extends TestCase
{
public function setUp(): void
{
}

public function testIsValid()
{
$validTextValidUrl = 'http://example.com';
$validTextInvalidUrl = 'hello world';
$invalidTextValidUrl = 'http://example.com/very-long-url';
$invalidTextInvalidUrl = 'Some very long text that is also not an URL';

$vaidator = new AnyOf([new Text(20), new URL()], Validator::TYPE_STRING);
$this->assertTrue($vaidator->isValid($validTextValidUrl));
$this->assertTrue($vaidator->isValid($validTextInvalidUrl));
$this->assertTrue($vaidator->isValid($invalidTextValidUrl));
$this->assertFalse($vaidator->isValid($invalidTextInvalidUrl));
}
}
35 changes: 0 additions & 35 deletions tests/Validator/MultipleTest.php

This file was deleted.

0 comments on commit 9f07728

Please sign in to comment.