Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve inference for InputFilterPluginManager::get() #97

Merged
merged 6 commits into from
Jan 10, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 7 additions & 11 deletions psalm-baseline.xml
Original file line number Diff line number Diff line change
Expand Up @@ -104,12 +104,6 @@
</PossiblyUnusedReturnValue>
</file>
<file src="src/Factory.php">
<InvalidReturnStatement>
<code>$inputFilter</code>
</InvalidReturnStatement>
<InvalidReturnType>
<code>InputFilterInterface</code>
</InvalidReturnType>
<MixedArgument>
<code><![CDATA[$inputFilterSpecification['count']]]></code>
<code><![CDATA[$inputFilterSpecification['input_filter']]]></code>
Expand Down Expand Up @@ -142,10 +136,6 @@
<code>$value</code>
<code>$value</code>
</PossiblyInvalidArgument>
<PossiblyUndefinedMethod>
<code>add</code>
<code>add</code>
</PossiblyUndefinedMethod>
<UnusedPsalmSuppress>
<code>DeprecatedMethod</code>
<code>DocblockTypeContradiction</code>
Expand Down Expand Up @@ -289,8 +279,14 @@
<code>InputFilterPluginManager</code>
</MethodSignatureMismatch>
<MethodSignatureMustProvideReturnType>
<code>Plu</code>
<code>get</code>
</MethodSignatureMustProvideReturnType>
Comment on lines -292 to 283
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why psalm complains about plugin manager get? Does it want simple typehinted return and conditional be in psalm-return?

Also what is the MethodSignatureMismatch just above that was previously baselined? Is it due to psr container aliasing shenanigans?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To answer it: some inherited weirdness going on.

ERROR: MethodSignatureMismatch - src/InputFilterPluginManager.php:30:7 - Method Laminas\ServiceManager\ServiceManager::has with return type '' is different to return type 'bool' of inherited method Psr\Container\ContainerInterface::has (see https://psalm.dev/042)
ERROR: MethodSignatureMismatch - src/InputFilterPluginManager.php:30:7 - Method Laminas\InputFilter\InputFilterPluginManager::get with return type '' is different to return type 'object' of inherited method Psr\Container\ContainerInterface::get (see https://psalm.dev/042)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think a lot of this will be solved with SMv4 when we can drop PSR container v1 and tighten up the templates and types in the plugin manager.

<MixedInferredReturnType>
<code><![CDATA[($name is class-string<T1> ? T1 : ($name is class-string<T2> ? T2 : T1|T2))]]></code>
</MixedInferredReturnType>
<MixedReturnStatement>
<code>parent::get($name, $options)</code>
</MixedReturnStatement>
<NonInvariantDocblockPropertyType>
<code>$factories</code>
</NonInvariantDocblockPropertyType>
Expand Down
8 changes: 8 additions & 0 deletions psalm.xml.dist
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,14 @@
<pluginClass class="Psalm\PhpUnitPlugin\Plugin"/>
</plugins>

<issueHandlers>
<UnusedClass>
<errorLevel type="suppress">
<directory name="test/StaticAnalysis" />
</errorLevel>
</UnusedClass>
</issueHandlers>

<stubs>
<file name=".psr-container.php.stub" preloadClasses="true" />
</stubs>
Expand Down
2 changes: 2 additions & 0 deletions src/Factory.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
use Laminas\Validator\ValidatorInterface;
use Traversable;

use function assert;
use function class_exists;
use function get_debug_type;
use function gettype;
Expand Down Expand Up @@ -317,6 +318,7 @@ public function createInputFilter($inputFilterSpecification)
}

$inputFilter = $this->getInputFilterManager()->get($type);
assert($inputFilter instanceof InputFilterInterface); // As opposed to InputInterface
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How do we know it is not an InputInterface here? InputFilterManager allows both

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because the createInputFilter method expects a spec (Array of type InputFilterSpecification). Here $type defaults to InputFilter::class and InputFilterSpecification['type'] is class-string<InputFilterInterface>

Copy link
Member

@Xerkus Xerkus Jan 9, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this ought to be full check for input filter with meaningful exception, not just an assert since the method is user facing and there is no soft guard somewhere else.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

An exception here would be a BC break though wouldn't it? The assertion will blow up in tests, it verifies the intended type for static analysis, and otherwise is a no-op for users

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It wouldn't be. It would just be a fatal error if method not implemented or kinda work with anything as long as object has add() or __call()

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is more of a usability concern really. Exception would allow to say it needs to be input filter and get_debug_type was returned for the requested type $type.


if ($inputFilter instanceof CollectionInputFilter) {
$inputFilter->setFactory($this);
Expand Down
14 changes: 13 additions & 1 deletion src/InputFilterPluginManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@
* @psalm-import-type ServiceManagerConfiguration from ServiceManager
* @template InstanceType of InputFilterInterface|InputInterface
* @extends AbstractPluginManager<InstanceType>
* @method InputFilterInterface|InputInterface get(string $name, ?array $options = null)
*/
class InputFilterPluginManager extends AbstractPluginManager
{
Expand Down Expand Up @@ -188,4 +187,17 @@ public function validatePlugin($plugin)
throw new Exception\RuntimeException($e->getMessage(), $e->getCode(), $e);
}
}

/**
* @inheritDoc
* @template T1 of InputInterface
* @template T2 of InputFilterInterface
* @param class-string<T1>|class-string<T2>|string $name
* @return T1|T2
* @psalm-return ($name is class-string<T1> ? T1 : ($name is class-string<T2> ? T2 : T1|T2))
*/
public function get($name, ?array $options = null)
{
return parent::get($name, $options);
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Isn't the entire signature the same as @param class-string<T> @return T?

Overall OK with this, just seems redundant with the parent DIC declarations

Copy link
Member

@Xerkus Xerkus Jan 9, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am testing this locally. It seems it could be simplified.

Copy link
Member

@Xerkus Xerkus Jan 9, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tried following:

    /**
     * @inheritDoc
     * @template T of InputInterface|InputFilterInterface
     * @param class-string<T>|string $name
     * @psalm-return ($name is class-string<T> ? T : T)
     */
    public function get($name, ?array $options = null)

Result is close:

ERROR: Trace - test/StaticAnalysis/InputFilterPluginManagerType.php:27:9 - $input: Laminas\InputFilter\Input (see https://psalm.dev/224)
        /** @psalm-trace $input */
        $input = $this->manager->get(Input::class);

ERROR: Trace - test/StaticAnalysis/InputFilterPluginManagerType.php:29:9 - $input: Laminas\InputFilter\InputInterface (see https://psalm.dev/224)
        /** @psalm-trace $input */
        $input = $this->manager->get('string');

ERROR: Trace - test/StaticAnalysis/InputFilterPluginManagerType.php:31:9 - $input: Laminas\InputFilter\InputInterface (see https://psalm.dev/224)
        /** @psalm-trace $input */
        $input = $this->manager->get('stdClass');

ERROR: Trace - test/StaticAnalysis/InputFilterPluginManagerType.php:33:9 - $input: LaminasTest\InputFilter\StaticAnalysis\InputFilterWithTemplatedValues (see https://psalm.dev/224)
        /** @psalm-trace $input */
        $input = $this->manager->get(InputFilterWithTemplatedValues::class);

For string parameters values are wrong.

However if I replace conditional fallback with explicit types it works out:

    /**
     * @inheritDoc
     * @template T of InputInterface|InputFilterInterface
     * @param class-string<T>|string $name
     * @psalm-return ($name is class-string<T> ? T : InputInterface|InputFilterInterface)
     */
    public function get($name, ?array $options = null)
ERROR: Trace - test/StaticAnalysis/InputFilterPluginManagerType.php:27:9 - $input: Laminas\InputFilter\Input (see https://psalm.dev/224)
        /** @psalm-trace $input */
        $input = $this->manager->get(Input::class);

ERROR: Trace - test/StaticAnalysis/InputFilterPluginManagerType.php:29:9 - $input: Laminas\InputFilter\InputFilterInterface|Laminas\InputFilter\InputInterface (see https://psalm.dev/224)
        /** @psalm-trace $input */
        $input = $this->manager->get('string');

ERROR: Trace - test/StaticAnalysis/InputFilterPluginManagerType.php:31:9 - $input: Laminas\InputFilter\InputFilterInterface|Laminas\InputFilter\InputInterface (see https://psalm.dev/224)
        /** @psalm-trace $input */
        $input = $this->manager->get('stdClass');

ERROR: Trace - test/StaticAnalysis/InputFilterPluginManagerType.php:33:9 - $input: LaminasTest\InputFilter\StaticAnalysis\InputFilterWithTemplatedValues (see https://psalm.dev/224)
        /** @psalm-trace $input */
        $input = $this->manager->get(InputFilterWithTemplatedValues::class);

Copy link
Member

@Xerkus Xerkus Jan 9, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually nevermind. This is wrong with both your version and my smiplification

ERROR: Trace - test/StaticAnalysis/InputFilterPluginManagerType.php:32:9 - $input: PHPUnit\Framework\TestCase (see https://psalm.dev/224)
        /** @psalm-trace $input */
        $input = $this->manager->get(TestCase::class);

I don't think conditional actually uses template there. It creates transient template instead used only for conditional.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was having problems with class-string<InstanceType> where InstanceType is the union, and similarly with class-string<InputInterface|InputFilterInterface> so that's why I went for class-string<InputInterface>|class-string<InputFilterInterface> - the simplified version is much better. I'll update the patch. Perhaps the cache was messing it up for me…

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, so here is the results:
This is not a valid expression @template T of InputInterface|InputFilterInterface. If I drop string from parameter I get:

ERROR: InvalidArgument - test/StaticAnalysis/InputFilterPluginManagerType.php:34:38 - Argument 1 of Laminas\InputFilter\InputFilterPluginManager::get expects class-string<Laminas\InputFilter\InputInterface>, but LaminasTest\InputFilter\StaticAnalysis\InputFilterWithTemplatedValues::class provided (see https://psalm.dev/004)
        $input = $this->manager->get(InputFilterWithTemplatedValues::class);

This indicates that template constraint is InputInterface and union part was ignored.

This is closer but has other issues:

    /**
     * @inheritDoc
     * @template T
     * @param class-string<T>|string $name
     * @return ($name is class-string<InputInterface>|class-string<InputFilterInterface> ? T : InputInterface|InputFilterInterface)
     */

Psalm then insists on throwing in mixed here

ERROR: MixedAssignment - src/Factory.php:174:13 - Unable to determine the type that $managerInstance is being assigned to (see https://psalm.dev/032)
            /** @psalm-trace $managerInstance */
            $managerInstance = $this->getInputFilterManager()->get($class);

  The type of $managerInstance is sourced from here - src/InputFilterPluginManager.php:194:16
     * @return ($name is class-string<InputInterface>|class-string<InputFilterInterface> ? T : InputInterface|InputFilterInterface)

ERROR: Trace - src/Factory.php:174:13 - $managerInstance: Laminas\InputFilter\InputFilterInterface|Laminas\InputFilter\InputInterface|mixed (see https://psalm.dev/224)
            /** @psalm-trace $managerInstance */
            $managerInstance = $this->getInputFilterManager()->get($class);


ERROR: MixedInferredReturnType - test/StaticAnalysis/InputFilterPluginManagerType.php:21:8 - Could not verify return type 'Laminas\InputFilter\InputFilterInterface|Laminas\InputFilter\InputInterface' for LaminasTest\InputFilter\StaticAnalysis\InputFilterPluginManagerType::getWillReturnAnInputOrInputFilterGivenAString (see https://psalm.dev/047)
    ): InputInterface|InputFilterInterface {


ERROR: MixedReturnStatement - test/StaticAnalysis/InputFilterPluginManagerType.php:22:16 - Possibly-mixed return value (see https://psalm.dev/138)
        return $this->manager->get($anyString);


ERROR: MixedReturnStatement - test/StaticAnalysis/InputFilterPluginManagerType.php:22:16 - Could not infer a return type (see https://psalm.dev/138)
        return $this->manager->get($anyString);


ERROR: Trace - test/StaticAnalysis/InputFilterPluginManagerType.php:28:9 - $input: Laminas\InputFilter\Input (see https://psalm.dev/224)
        /** @psalm-trace $input */
        $input = $this->manager->get(Input::class);


ERROR: Trace - test/StaticAnalysis/InputFilterPluginManagerType.php:30:9 - $input: Laminas\InputFilter\InputFilterInterface|Laminas\InputFilter\InputInterface (see https://psalm.dev/224)
        /** @psalm-trace $input */
        $input = $this->manager->get('string');


ERROR: Trace - test/StaticAnalysis/InputFilterPluginManagerType.php:32:9 - $input: Laminas\InputFilter\InputFilterInterface|Laminas\InputFilter\InputInterface (see https://psalm.dev/224)
        /** @psalm-trace $input */
        $input = $this->manager->get(TestCase::class);


ERROR: Trace - test/StaticAnalysis/InputFilterPluginManagerType.php:34:9 - $input: LaminasTest\InputFilter\StaticAnalysis\InputFilterWithTemplatedValues (see https://psalm.dev/224)
        /** @psalm-trace $input */
        $input = $this->manager->get(InputFilterWithTemplatedValues::class);

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is uncharted waters and I feel we are hitting at least couple edge case bugs here.

So, for current psalm version following works:

    /**
     * @inheritDoc
     * // Template constraint required or we get mixed added to output. Two templates because union does not work
     * @template T1 of InputInterface
     * @template T2 of InputFilterInterface
     * // string would allow anything and both templates currently receive the passed class ignoring constraint
     * // use both templates because of the first point.
     * @param class-string<T1>|class-string<T2>|string $name
     * // We can combine conditionals and use one of templates or swap templates and it will still work. Keep both as it will likely remain working in the future
     * @return ($name is class-string<InputInterface> ? T1 : ($name is class-string<InputFilterInterface> ? T2 : InputInterface|InputFilterInterface))
     */

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@gsteel Psalm tests could be improved with https://psalm.dev/docs/annotating_code/supported_annotations/#psalm-check-type to ensure we get expected types

I am sure it will not cause us any more grief on another lockfile maintenance PR 😆

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Xerkus - just looking at this now and unfortunately, the string case union return type is messed up:

https://psalm.dev/r/84bf036569

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

https://psalm.dev/r/6e213fb5a6 Looks like a bug with @psalm-check-type not resolving FQCN against use statements and resolving against namespace for right side of union.

}
1 change: 0 additions & 1 deletion test/StaticAnalysis/AddingInputsWithArraySpecs.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@

/**
* @extends InputFilter<array<string, mixed>>
* @psalm-suppress UnusedClass
*/
final class AddingInputsWithArraySpecs extends InputFilter
{
Expand Down
27 changes: 27 additions & 0 deletions test/StaticAnalysis/InputFilterPluginManagerType.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

declare(strict_types=1);

namespace LaminasTest\InputFilter\StaticAnalysis;

use Laminas\InputFilter\InputFilterInterface;
use Laminas\InputFilter\InputFilterPluginManager;
use Laminas\InputFilter\InputInterface;

final class InputFilterPluginManagerType
{
public function __construct(private InputFilterPluginManager $manager)
{
}

public function getWillReturnAnInputOrInputFilterGivenAString(
string $anyString,
): InputInterface|InputFilterInterface {
return $this->manager->get($anyString);
}

public function getWithFQCNWillReturnTheObjectOfType(): InputFilterWithTemplatedValues
{
return $this->manager->get(InputFilterWithTemplatedValues::class);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
use function count;
use function reset;

/** @psalm-suppress UnusedClass */
final class InputFilterTemplateInfersFilterValueTypes
{
public function __construct(
Expand Down