laminas / laminas-inputfilter

Normalize and validate input sets from the web, APIs, the CLI, and more, including files
https://docs.laminas.dev/laminas-inputfilter/
BSD 3-Clause "New" or "Revised" License
42 stars 29 forks source link

Improve consumer type inference with InputFilter templates #91

Closed gsteel closed 1 year ago

gsteel commented 1 year ago
Q A
RFC yes

Description

Adds a template to InputFilterInterface to define the array shape of filtered values

The plan here is better inference when calling InputFilterInterface::getValues(). It might cause a lot of noise for users because psalm requires a template declaration for all inheritors, that said, it'd be useful to those who care.

Once merged, users will be able to define an input filter such as:

/**
 * @psalm-type ValidPayload = array{
 *   inputA: non-empty-string,
 *   inputB: int,
 *   inputC: DateTimeImmutable,
 * @extends InputFilter<ValidPayload>
 */
final class MyInputFilter extends InputFilter
{
  public function init(): void
  {
    // Set up inputs according to desired constraints…
  }
}

… and psalm will infer the types for whatever comes out of $inputFilter->getValues() such as:

$values = $inputFilter->getValues();

printf('The Date is %s', $values['inputC']->format('Y-m-d'));

As part of wrestling with Psalm on this patch, it's worth mentioning that all input names can now be array-key as opposed to string. This is not really related to the patch but something I had to address because CollectionInputFilter is effectively a nested list, it's actually a requirement to be able to fetch an input with something like $inputFilter->get(1)

This work has also uncovered at least one or two subtle bugs or ambiguous behaviour and fixes an issue where InputFilter::add will attempt to call Input::merge with an InputFilter as an argument

gsteel commented 1 year ago

Added a first stab at documentation @weierophinney

weierophinney commented 1 year ago

Added a first stab at documentation

Perfect!

I'm approving now, but only because I don't fully understand Marco's concern (though your explanation makes sense to me).

Ocramius commented 1 year ago

Thanks @gsteel!