respect-validation/library/Transformers/Prefix.php
Henrique Moody 97b243daa1
Allow building rules using prefixes
Although helpful, the changes in the Min, Max, and Length rules made
using those rules more verbose. This commit will simplify their use by
allowing users to use them as prefixes.

Because I was creating prefixes for those rules, I made other cool
prefixes. Doing that is scary because it will generate more code to
support, and I would have liked to avoid that. However, that's a
valuable addition, and it's worth the risk.

I might reconsider that in the future, but for now, that looks like a
good idea.

Signed-off-by: Henrique Moody <henriquemoody@gmail.com>
2024-03-24 16:58:24 +01:00

88 lines
2.6 KiB
PHP

<?php
/*
* Copyright (c) Alexandre Gomes Gaigalas <alganet@gmail.com>
* SPDX-License-Identifier: MIT
*/
declare(strict_types=1);
namespace Respect\Validation\Transformers;
use function array_shift;
use function in_array;
use function str_starts_with;
use function substr;
final class Prefix implements Transformer
{
private const RULES_TO_SKIP = [
'key',
'keyExists',
'keyOptional',
'keySet',
'length',
'max',
'maxAge',
'min',
'minAge',
'not',
'notBlank',
'notEmoji',
'notEmpty',
'notOptional',
'property',
'propertyExists',
'propertyOptional',
];
public function transform(RuleSpec $ruleSpec): RuleSpec
{
if ($ruleSpec->wrapper !== null || in_array($ruleSpec->name, self::RULES_TO_SKIP, true)) {
return $ruleSpec;
}
if (str_starts_with($ruleSpec->name, 'key')) {
$arguments = $ruleSpec->arguments;
array_shift($arguments);
$wrapperArguments = [$ruleSpec->arguments[0]];
return new RuleSpec(substr($ruleSpec->name, 3), $arguments, new RuleSpec('key', $wrapperArguments));
}
if (str_starts_with($ruleSpec->name, 'length')) {
return new RuleSpec(substr($ruleSpec->name, 6), $ruleSpec->arguments, new RuleSpec('length'));
}
if (str_starts_with($ruleSpec->name, 'max')) {
return new RuleSpec(substr($ruleSpec->name, 3), $ruleSpec->arguments, new RuleSpec('max'));
}
if (str_starts_with($ruleSpec->name, 'min')) {
return new RuleSpec(substr($ruleSpec->name, 3), $ruleSpec->arguments, new RuleSpec('min'));
}
if (str_starts_with($ruleSpec->name, 'not')) {
return new RuleSpec(substr($ruleSpec->name, 3), $ruleSpec->arguments, new RuleSpec('not'));
}
if (str_starts_with($ruleSpec->name, 'nullOr')) {
return new RuleSpec(substr($ruleSpec->name, 6), $ruleSpec->arguments, new RuleSpec('nullable'));
}
if (str_starts_with($ruleSpec->name, 'property')) {
$arguments = $ruleSpec->arguments;
array_shift($arguments);
$wrapperArguments = [$ruleSpec->arguments[0]];
return new RuleSpec(substr($ruleSpec->name, 8), $arguments, new RuleSpec('property', $wrapperArguments));
}
if (str_starts_with($ruleSpec->name, 'undefOr')) {
return new RuleSpec(substr($ruleSpec->name, 7), $ruleSpec->arguments, new RuleSpec('optional'));
}
return $ruleSpec;
}
}