Skip to content

Commit

Permalink
Merge pull request #91 from gsteel/template-filtered-values
Browse files Browse the repository at this point in the history
[RFC] Improve consumer type inference with InputFilter templates
  • Loading branch information
Ocramius committed Jul 14, 2023
2 parents dfdb8d2 + 4af687c commit 1446fe8
Show file tree
Hide file tree
Showing 23 changed files with 522 additions and 98 deletions.
14 changes: 7 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,19 @@
[![Build Status](https://github.com/laminas/laminas-inputfilter/workflows/Continuous%20Integration/badge.svg)](https://github.com/laminas/laminas-inputfilter/actions?query=workflow%3A"Continuous+Integration")

> ## 🇷🇺 Русским гражданам
>
>
> Мы, участники Laminas, родились и живем в разных странах. У многих из нас есть друзья, родственники и коллеги как в России, так и в Украине. Некоторые из нас родились в России. Некоторые из нас живут в России. У некоторых бабушки и дедушки сражались с фашистами во Второй мировой войне. Здесь никто не поддерживает фашизм.
>
>
> У одного из нас есть украинская родственница, которая спаслась из дома вместе с сыном. Поезд задержался из-за бомбежки на дороге впереди. У нас есть друзья, которые прячутся в бомбоубежищах. Мы с тревогой ждем весточки от них после воздушных налетов, которые беспорядочно наносят удары и попадают по больницам, школам, детским садам и домам. Мы не берем это из каких-либо СМИ. Мы наблюдаем это напрямую.
>
>
> Вы доверяете нам достаточно, чтоб использовать наши программы, и мы просим вас довериться нам вновь. Мы нуждаемся в помощи. Выходите и протестуйте против этой бесполезной войны. Остановите кровопролитие. Скажите "Нет войне!"
>
>
> ## 🇺🇸 To Citizens of Russia
>
>
> We at Laminas come from all over the world. Many of us have friends, family and colleagues in both Russia and Ukraine. Some of us were born in Russia. Some of us currently live in Russia. Some have grandparents who fought Nazis in World War II. Nobody here supports fascism.
>
>
> One team member has a Ukrainian relative who fled her home with her son. The train was delayed due to bombing on the road ahead. We have friends who are hiding in bomb shelters. We anxiously follow up on them after the air raids, which indiscriminately fire at hospitals, schools, kindergartens and houses. We're not taking this from any media. These are our actual experiences.
>
>
> You trust us enough to use our software. We ask that you trust us to say the truth on this. We need your help. Go out and protest this unnecessary war. Stop the bloodshed. Say "stop the war!"
The laminas-inputfilter component can be used to filter and validate generic sets
Expand Down
4 changes: 2 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,10 @@
},
"require": {
"php": "~8.1.0 || ~8.2.0",
"laminas/laminas-filter": "^2.13",
"laminas/laminas-filter": "^2.19",
"laminas/laminas-servicemanager": "^3.21.0",
"laminas/laminas-stdlib": "^3.0",
"laminas/laminas-validator": "^2.15"
"laminas/laminas-validator": "^2.25"
},
"require-dev": {
"ext-json": "*",
Expand Down
14 changes: 7 additions & 7 deletions composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

72 changes: 72 additions & 0 deletions docs/book/cookbook/enhanced-type-inference.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
# Using Laminas InputFilter with Static Analysis Tools

It can be tedious to assert that the array returned by a given input filter contains the keys and value types that you would expect before using those values in your domain.
If you use static analysis tools such as Psalm or PHPStan, `InputFilterInterface` defines a generic template that can be used to refine the types you receive from the `getValues()` method.

```php
<?php

namespace My;

use Laminas\Filter\ToInt;
use Laminas\Filter\ToNull;
use Laminas\I18n\Validator\IsInt;
use Laminas\InputFilter\InputFilter;use Laminas\Validator\GreaterThan;

/**
* @psalm-type ValidPayload = array{
* anInteger: int<1, max>,
* }
* @extends InputFilter<ValidPayload>
*/
final class SomeInputFilter extends InputFilter
{
public function init(): void
{
$this->add([
'name' => 'anInteger',
'required' => true,
'filters' => [
['name' => ToNull::class],
['name' => ToInt::class],
],
'validators' => [
['name' => NotEmpty::class],
['name' => IsInt::class],
[
'name' => GreaterThan::class,
'options' => [
'min' => 1,
],
],
],
]);
}
}
```

With the above input filter specification, one can guarantee that, if the input payload is deemed valid, then you will receive an array with the expected shape from `InputFilter::getValues()`, therefore, your static analysis tooling will not complain when you pass that value directly to something that expects a `positive-int`, for example:

```php
/**
* @param positive-int $value
* @return positive-int
*/
function addTo5(int $value): int
{
return $value + 5;
}

$filter = new SomeInputFilter();
$filter->setData(['anInteger' => '123']);
assert($filter->isValid());

$result = addTo5($filter->getValues()['anInteger']);
```

## Further reading

- [Psalm documentation on array shapes](https://psalm.dev/docs/annotating_code/type_syntax/array_types/#array-shapes)
- [Psalm documentation on type aliases](https://psalm.dev/docs/annotating_code/type_syntax/utility_types/#type-aliases)
- [PHPStan documentation on array shapes](https://phpstan.org/writing-php-code/phpdoc-types#array-shapes)
- [PHPStan documentation on type aliases](https://phpstan.org/writing-php-code/phpdoc-types#local-type-aliases)
1 change: 1 addition & 0 deletions mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ nav:
- "Usage in a mezzio application": application-integration/usage-in-a-mezzio-application.md
- Cookbook:
- "Using Input Filters in Forms of laminas-form": cookbook/input-filter-in-forms.md
- "Using Static Analysis tools with laminas-inputfilter": cookbook/enhanced-type-inference.md
site_name: laminas-inputfilter
site_description: 'Normalize and validate input sets from the web, APIs, the CLI, and more, including files.'
repo_url: 'https://github.com/laminas/laminas-inputfilter'
Expand Down
46 changes: 11 additions & 35 deletions psalm-baseline.xml
Original file line number Diff line number Diff line change
Expand Up @@ -26,18 +26,12 @@
</NonInvariantDocblockPropertyType>
</file>
<file src="src/BaseInputFilter.php">
<DocblockTypeContradiction>
<code><![CDATA[$input instanceof InputInterface && (empty($name) || is_int($name))]]></code>
</DocblockTypeContradiction>
<InvalidReturnStatement>
<code>$messages</code>
<code>$values</code>
</InvalidReturnStatement>
<InvalidReturnType>
<code><![CDATA[array<string, array<array-key, string>>]]></code>
<code>TFilteredValues</code>
</InvalidReturnType>
<MixedArgument>
<code>$input</code>
</MixedArgument>
<MixedArgumentTypeCoercion>
<code>$inputs</code>
</MixedArgumentTypeCoercion>
Expand All @@ -49,21 +43,14 @@
<MixedPropertyTypeCoercion>
<code>$inputs</code>
</MixedPropertyTypeCoercion>
<PossiblyInvalidArgument>
<code>$input</code>
</PossiblyInvalidArgument>
<PossiblyNullArrayOffset>
<code><![CDATA[$this->inputs]]></code>
</PossiblyNullArrayOffset>
<RedundantCastGivenDocblockType>
<code>(string) $name</code>
</RedundantCastGivenDocblockType>
<TooManyArguments>
<code>isValid</code>
<code>isValid</code>
</TooManyArguments>
<UnusedPsalmSuppress>
<code>DocblockTypeContradiction</code>
<code>RedundantConditionGivenDocblockType</code>
<code>RedundantConditionGivenDocblockType</code>
</UnusedPsalmSuppress>
Expand All @@ -73,10 +60,6 @@
<code>$name</code>
<code>$name</code>
</ImplementedParamTypeMismatch>
<ImplementedReturnTypeMismatch>
<code><![CDATA[array<array-key, array<string, array<array-key, string>>>]]></code>
<code><![CDATA[array<array-key, array<string, array<array-key, string>>>]]></code>
</ImplementedReturnTypeMismatch>
<InvalidArgument>
<code>$data</code>
</InvalidArgument>
Expand All @@ -87,16 +70,21 @@
<code><![CDATA[$this->invalidInputs]]></code>
<code><![CDATA[$this->validInputs]]></code>
</InvalidPropertyAssignmentValue>
<LessSpecificImplementedReturnType>
<code><![CDATA[array<array-key, array>]]></code>
<code><![CDATA[array<array-key, array>]]></code>
</LessSpecificImplementedReturnType>
<InvalidReturnStatement>
<code><![CDATA[$this->collectionValues]]></code>
</InvalidReturnStatement>
<InvalidReturnType>
<code>TFilteredValues</code>
</InvalidReturnType>
<MixedArgument>
<code>$data</code>
</MixedArgument>
<MixedAssignment>
<code>$data</code>
</MixedAssignment>
<MixedPropertyTypeCoercion>
<code><![CDATA[$this->collectionValues]]></code>
</MixedPropertyTypeCoercion>
<PossiblyUnusedReturnValue>
<code>array[]</code>
<code>array[]</code>
Expand Down Expand Up @@ -136,7 +124,6 @@
<MixedArgumentTypeCoercion>
<code>$filter</code>
<code>$inputSpecification</code>
<code>$key</code>
</MixedArgumentTypeCoercion>
<MixedArrayAccess>
<code><![CDATA[$filter['name']]]></code>
Expand Down Expand Up @@ -359,12 +346,6 @@
<code>ModuleManager</code>
</UndefinedDocblockClass>
</file>
<file src="src/OptionalInputFilter.php">
<ImplementedReturnTypeMismatch>
<code><![CDATA[array<string, mixed>|null]]></code>
<code><![CDATA[array<string, mixed>|null]]></code>
</ImplementedReturnTypeMismatch>
</file>
<file src="test/ArrayInputTest.php">
<ArgumentTypeCoercion>
<code>$valueMap</code>
Expand Down Expand Up @@ -465,12 +446,8 @@
<code>$getMessages</code>
<code>$msg</code>
<code>$msg</code>
<code>$name</code>
</MixedArgumentTypeCoercion>
<MixedArrayAccess>
<code><![CDATA[$filter1->getValues()['nested']['nestedField1']]]></code>
<code><![CDATA[$filter1->getValues()['nested']['nestedField1']]]></code>
<code><![CDATA[$filter1->getValues()['nested']['nestedField1']]]></code>
<code>$inputTypeData[1]</code>
<code>$inputTypeData[2]</code>
</MixedArrayAccess>
Expand Down Expand Up @@ -526,7 +503,6 @@
<PossiblyUndefinedMethod>
<code>getName</code>
<code>getName</code>
<code>isRequired</code>
</PossiblyUndefinedMethod>
<PossiblyUnusedMethod>
<code>addMethodArgumentsProvider</code>
Expand Down
Loading

0 comments on commit 1446fe8

Please sign in to comment.