Hi,
I want to validate min/max count of items in CollectionInputFilter. My config is:
<?php
declare(strict_types=1);
use Laminas\InputFilter;
use Laminas\Validator;
include_once __DIR__ . '/vendor/autoload.php';
$config = [
'items' => [
'required' => true,
'type' => InputFilter\CollectionInputFilter::class,
'input_filter' => [
'id' => [
'required' => true,
],
],
'validators' => [
[
'name' => Validator\IsCountable::class,
'options' => [
'max' => 1,
],
],
],
],
];
$data = [
'items' => [
[
'id' => 'foo',
],
[
'id' => 'bar',
],
],
];
$factory = new InputFilter\Factory();
$inputFilter = $factory->createInputFilter($config);
$inputFilter->setData($data);
var_dump($inputFilter->isValid()); // outputs true
But InputFilterInterface is not validated itself.
Any suggestions how to validate max count of passed $data
?
Correct, you can not add validators to an input filter or collection input filter itself. An input filter does not have a validator chain like an input.
Unfortunately, I have no real idea at the moment. Maybe a custom input filter which adapts the count option of the collection input filter.
Some pseudo code:
class CustomCollectionInputFilter extends Laminas\InputFilter\CollectionInputFilter
{
private ?int $min = null;
private ?int $max = null;
public function getMin(): ?int
{
return $this->min;
}
public function setMin(?int $min): void
{
$this->min = $min;
}
public function getMax(): ?int
{
return $this->max;
}
public function setMax(?int $max): void
{
$this->max = $max;
}
public function isValid($context = null): bool
{
$valid = true;
if (is_int($this->getMin()) && count($this->data) < $this->getMin()) {
$this->collectionMessages[] = '…';
$valid = false;
}
if (is_int($this->getMax()) && count($this->data) > $this->getMax()) {
$this->collectionMessages[] = '…';
$valid = false;
}
if (! $valid) {
return false;
}
return parent::isValid($context);
}
}
$inputFilter = $factory->createInputFilter($config);
$inputFilter->get('items')->setMin(1);
$inputFilter->get('items')->setMax(3);
$inputFilter->setData($data);
Thanks for hint. I have another idea. Create InputFilterFilter class. Basically InputFilter which consumes InputFilter object. What do you think?
How does it solve the problem of adding validators? Only an input has a validator chain:
And a collection input filter is already an input filter object: