docs icon indicating copy to clipboard operation
docs copied to clipboard

`$environment->getContext` triggers the Psalm issue UndefinedInterfaceMethod

Open Kwadz opened this issue 4 years ago • 2 comments

The example about accessing contexts from each other triggers:

  • the Psalm issue UndefinedInterfaceMethod
  • the PHPStorm issue "Potentially polymorphic call. The code may be inoperable depending on the actual class instance passed as the argument"

Indeed, the method getContext() is not necessarily present in every possible Environment interface implementation since it is not declared in this interface. Actually it is declared in InitializedContextEnvironment only.

The piece of code:

use Behat\Behat\Context\Context;
use Behat\Behat\Hook\Scope\BeforeScenarioScope;

class FeatureContext implements Context
{
    /** @var \Behat\MinkExtension\Context\MinkContext */
    private $minkContext;

    /** @BeforeScenario */
    public function gatherContexts(BeforeScenarioScope $scope)
    {
        $environment = $scope->getEnvironment();

        $this->minkContext = $environment->getContext('Behat\MinkExtension\Context\MinkContext');
    }
}

Kwadz avatar Sep 21 '21 20:09 Kwadz

This might be solved by improving types based on the different scopes. The BeforeScenarioScope is guaranteed to get an environment implementing Behat\Behat\Context\Environment\ContextEnvironment, and I think even an InitializedContextEnvironment for that one (for BeforeSuite, that might not be an InitializedContextEnvironment, but it would still be a ContextEnvironment)

stof avatar Sep 22 '21 09:09 stof

getContext public method is available only in specific ContextEnvironment implementations as it's not listed on the interface. FriendsOfBehat/SymfonyExtension implements that interface as well and provides getContext method additionally, but there's still no guarantee any other implementation will have that method.

pamil avatar Dec 13 '21 13:12 pamil