Slamdunk / phpstan-laminas-framework

Laminas Framework 3 extensions for PHPStan
MIT License
16 stars 10 forks source link

Method ::getRequest() in controller returns wrong class #17

Closed MatyCZ closed 3 years ago

MatyCZ commented 3 years ago

PhpStan shows following errors after installation of phpstan-laminas-framework. The problem is that this Controller is never called from console (only phpstan is called from cli). Is there any option to set right class for method getRequest()?

PhpStan output:

 ------ -------------------------------------------------------------------
  Line   app/src/Controller/TestController.php
 ------ -------------------------------------------------------------------
  59     Call to an undefined method Laminas\Console\Request::getMethod().
  113    Call to an undefined method Laminas\Console\Request::isPost().
 ------ -------------------------------------------------------------------

Example:

public function testAction() {
    if (!in_array($this->getRequest()->getMethod(), [Request::METHOD_POST])) {
        throw new \Exception(...)
    }

    ...

    if ($this->getRequest()->isPost()) {
        $post = $this->getPost();
        ...
    }
}
Slamdunk commented 3 years ago

I'd need a complete example of the code you're running, but you could for example leverage assert():

public function testAction() {
    $request = $this->getRequest();
    assert($request instanceof \Laminas\Http\Request);
    if (!in_array($request->getMethod(), [Request::METHOD_POST])) {
        throw new \Exception(...)
    }

    if ($request->isPost()) {
        $post = $this->getPost();
    }
}
MatyCZ commented 3 years ago

This is example of the code:

<?php

namespace App\Controller;

use Laminas\Mvc\Controller\AbstractActionController;
use Laminas\View\Model\ViewModel;

class TestController extends AbstractActionController
{
    public function updateAction(): ViewModel
    {
        if ($this->getRequest()->isPost()) {
            $post = $this->getRequest()->getPost();

            var_dump($post);
        }

        return new ViewModel([
            'test' => true
        ]);
    }
}
MatyCZ commented 3 years ago

I solved this problem with phpstan config:

  ignoreErrors:
    - '#Call to an undefined method Laminas\\Console\\Request::getMethod\(\)#'
    - '#Call to an undefined method Laminas\\Console\\Request::isPatch\(\)#'
    - '#Call to an undefined method Laminas\\Console\\Request::isPost\(\)#'
    - '#Call to an undefined method Laminas\\Console\\Response::getHeaders\(\)#'