Reputation: 179
I'm using the validator component as a standalone package for data validations.
I have a class that contains methods that return common validation cases, like this one:
public function selectOneFrom(array $choices): Constraint
{
return new RequireAll([
new Symfony\Component\Validator\Constraint\NotNull(),
new Symfony\Component\Validator\Constraint\Choice($choices),
]);
}
As far as I can tell, the only option to return a compound rule is to return it as an array
. What I am after is not having a : Constraint|array
return value type hint on these methods that return compound rules.
What I do not understand is why there is no concrete Compound
constraint. Here, I created my own RequireAll
, which extends the Compound and is pretty trivial:
class RequireAll extends Compound
{
public function __construct(iterable $constraints, $options = null)
{
parent::__construct($options);
$this->constraints = is_array($constraints) ? $constraints : iterator_to_array($constraints);
}
protected function getConstraints(array $options): array
{
return $this->constraints;
}
}
Am I missing something?
P.S.: I know I'm supposed to extend the Compound
class, but this way I can parametrize the rules with less effort than creating a new class for each compound validation rule.
Upvotes: 0
Views: 271
Reputation: 4014
I know I'm supposed to extend the Compound class, but this way I can parametrize the rules with less effort than creating a new class for each compound validation rule.
Is it really less effort, though?
class SelectOneFrom extends Compound
{
public array $choices;
protected function getConstraints(array $options): array
{
return [
new Symfony\Component\Validator\Constraint\NotNull(),
new Symfony\Component\Validator\Constraint\Choice($options['choices']),
];
}
public function getRequiredOptions()
{
return ['choices'];
}
public function getDefaultOption()
{
return 'choices';
}
}
It is more code, if you are counting lines, but its still quite simple. Prior to the Compound
constraint, it was far more difficult to create the equivalent SelectOneFrom
constraint.
The benefit of having a SelectOneFrom
constraint is that it is far more portable than having to depend on a call to the ::selectOneFrom
factory method. (I.e. if you use XML or Attributes for setting constraints on object properties.)
The alternative is to neither define SelectOneFrom
nor RequireAll
constraints and just have your factory method return an array.
/**
* @return Constraint[]
*/
public function selectOneFrom(array $choices): array
{
[
new Symfony\Component\Validator\Constraint\NotNull(),
new Symfony\Component\Validator\Constraint\Choice($choices),
];
}
If its adequate for your project to call a factory method, then having it return an array of constraints is equal to it returning a single RequireAll
constraint.
Upvotes: 0