phpstan-magento icon indicating copy to clipboard operation
phpstan-magento copied to clipboard

missing check when using factory, di inyection and preference

Open esteban-serfe opened this issue 3 years ago • 2 comments
trafficstars

My current module has a preference over a class set on the di.xml file.

I'm using the factory on the constructor of a overwrite.

When using a method that only exists on the overwrited class that is created through the Factory, PHPStan reports the method as not existent.

di.xml

<preference for="Magento\Framework\View\Result\Page"                 type="ClassA" />
<preference for="Magento\Framework\View\Page\Config\Renderer" type="ClassB" />

Class with factory on constructor:

class ClassA extends Magento\Framework\View\Result\Page  {
public function __construct(
 ....
 classBFactory $pageConfigRendererFactory
) {
 ...
 parent::__construct(.... );
}

public function overwritenFunction( .... ) {
  ....
  $this->pageConfigRenderer->onlyOnThisClassMethod();
  ....
}

Class B:

class ClassB extends \Magento\Framework\View\Page\Config\Renderer 
{
  public function onlyOnThisClassMethod() { .... }
}

This is reported as: Call to an undefined method Magento\\Framework\\View\\Page\\Config\\RendererInterface::renderExtraFooter()

Complete code has been tested and battle proven on production, so it works as expected.

For now I'm just ignoring the issue reported.

esteban-serfe avatar Mar 25 '22 17:03 esteban-serfe

Thanks a lot for raising this issue. This is indeed currently a problem as the di.xml files do not yet get parsed. I will need to check with the PHPStan maintainer what options we have to implement this.

In your example, you could redeclare $pageConfigRenderer in ClassA and add the correct @var annotation. That should do the trick, I would think.

shochdoerfer avatar Mar 25 '22 19:03 shochdoerfer

The possible solution will not work on this specific case as the parameter used is passed into the parent constructor. It might help in other situations.

esteban-serfe avatar Mar 25 '22 19:03 esteban-serfe