respect-validation/library/Rules/Blank.php
Henrique Moody 338c186803
Invert the behaviour of NotBlank
Since we have the ability to use `not` as a prefix, having rules that
start with not becomes a bit inflexible, verbose, and harder to
understand.

This commit will refactor the `NotBlank` rule by inverting its behaviour
and renaming it to `Blank`. Although this is a breaking change, users
will not feel it because "NotBlank" will still be available by using the
`not` prefix followed by the `Blank` rule.
2025-12-27 17:18:30 +01:00

56 lines
1.2 KiB
PHP

<?php
/*
* Copyright (c) Alexandre Gomes Gaigalas <alganet@gmail.com>
* SPDX-License-Identifier: MIT
*/
declare(strict_types=1);
namespace Respect\Validation\Rules;
use Attribute;
use Respect\Validation\Message\Template;
use Respect\Validation\Result;
use Respect\Validation\Rule;
use stdClass;
use function array_filter;
use function is_array;
use function is_numeric;
use function is_string;
use function trim;
#[Attribute(Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)]
#[Template(
'{{subject}} must be blank',
'{{subject}} must not be blank',
)]
final class Blank implements Rule
{
public function evaluate(mixed $input): Result
{
return Result::of($this->isBlank($input), $input, $this);
}
private function isBlank(mixed $input): bool
{
if (is_numeric($input)) {
return $input == 0;
}
if (is_string($input)) {
$input = trim($input);
}
if ($input instanceof stdClass) {
$input = (array) $input;
}
if (is_array($input)) {
$input = array_filter($input, fn($value) => !$this->isBlank($value));
}
return empty($input);
}
}