Skip to content

PHPStan returns false positives because of incoherent PHPDocs on functions/parameters that accept Phrase objects #36063

@guvra

Description

@guvra

Preconditions and environment

  • Magento version: 2.4.5
  • Using PHPStan with the following conditions:
    • Level >= 5
    • Adding declare(strict_types=1); at the top of php files

Steps to reproduce

  1. At the root of your Magento project, create a file named Test.php with the following contents:
<?php

declare(strict_types=1);

namespace Foo\Bar\Controller;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\HttpGetActionInterface;
use Magento\Framework\View\Result\Page;

class Test extends Action implements HttpGetActionInterface
{
    public function execute()
    {
        $this->messageManager->addErrorMessage(__('foobar'));

        return $this->resultFactory->create(Page::class);
    }
}
  1. Run PHPStan:
vendor/bin/phpstan analyse --level 6 -c dev/tests/static/testsuite/Magento/Test/Php/_files/phpstan/phpstan.neon Test.php

Expected result

PHPStan shouldn't report any error.

Actual result

PHPStan reports the following error:

Parameter #1 $message of method Magento\Framework\Message\ManagerInterface::addErrorMessage() expects string, Magento\Framework\Phrase given.

Additional information

To fix this issue, the typehints of parameters and methods that accept Phrase objects should be changed from string to string|Phrase.

A few examples:

In Magento\Backend\Block\Widget\Container:

    /**
     * @var string
     */
    protected $_headerText = 'Container Widget Header';

Must be changed to:

    /**
     * @var string|Phrase
     */
    protected $_headerText = 'Container Widget Header';

In Magento\Backend\Block\Widget\Button\ButtonList:

    /**
     * Update specified button property
     *
     * @param string $buttonId
     * @param string|null $key
     * @param string $data
     * @return void
     */
    public function update($buttonId, $key, $data)
    {

Must be changed to:

    /**
     * Update specified button property
     *
     * @param string $buttonId
     * @param string|null $key
     * @param string|Phrase $data
     * @return void
     */
    public function update($buttonId, $key, $data)
    {

In Magento\Framework\Message\ManagerInterface:

    /**
     * Adds new error message
     *
     * @param string $message
     * @param string|null $group
     * @return ManagerInterface
     */
    public function addErrorMessage($message, $group = null);

Must be changed to:

    /**
     * Adds new error message
     *
     * @param string|Phrase $message
     * @param string|null $group
     * @return ManagerInterface
     */
    public function addErrorMessage($message, $group = null);

(same for the other addXxX methods of the same class).

In Magento\Framework\View\Page\Title:

    /**
     * Set page title
     *
     * @param string $title
     * @return $this
     */
    public function set($title)
    {

Must be changed to:

    /**
     * Set page title
     *
     * @param string|Phrase $title
     * @return $this
     */
    public function set($title)
    {

Other option: add Stringable interface to the phrase class and use string|Stringable.

Release note

No response

Triage and priority

  • Severity: S0 - Affects critical data or functionality and leaves users without workaround.
    Severity: S1 - Affects critical data or functionality and forces users to employ a workaround.
    Severity: S2 - Affects non-critical data or functionality and forces users to employ a workaround.
    Severity: S3 - Affects non-critical data or functionality and does not force users to employ a workaround.
    Severity: S4 - Affects aesthetics, professional look and feel, “quality” or “usability”.

Sub-issues

Sub-issues

1 of 2 Issues completed

Activity

m2-assistant

m2-assistant commented on Aug 31, 2022

@m2-assistant

Hi @guvra. Thank you for your report.
To speed up processing of this issue, make sure that you provided the following information:

  • Summary of the issue
  • Information on your environment
  • Steps to reproduce
  • Expected and actual results

Make sure that the issue is reproducible on the vanilla Magento instance following Steps to reproduce. To deploy vanilla Magento instance on our environment, Add a comment to the issue:

@magento give me 2.4-develop instance - upcoming 2.4.x release

For more details, review the Magento Contributor Assistant documentation.

Add a comment to assign the issue: @magento I am working on this

To learn more about issue processing workflow, refer to the Code Contributions.


⚠️ According to the Magento Contribution requirements, all issues must go through the Community Contributions Triage process. Community Contributions Triage is a public meeting.

🕙 You can find the schedule on the Magento Community Calendar page.

📞 The triage of issues happens in the queue order. If you want to speed up the delivery of your contribution, join the Community Contributions Triage session to discuss the appropriate ticket.

✏️ Feel free to post questions/proposals/feedback related to the Community Contributions Triage process to the corresponding Slack Channel

guvra

guvra commented on Sep 15, 2022

@guvra
Author

Until it is fixed, I implemented a workaround with a phpstan extension:

<?php

declare(strict_types=1);

namespace Magento\PhpStan\Type\Php;

use Magento\Framework\Phrase;
use PhpParser\Node\Expr\FuncCall;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\FunctionReflection;
use PHPStan\Type\DynamicFunctionReturnTypeExtension;
use PHPStan\Type\ObjectType;
use PHPStan\Type\StringType;
use PHPStan\Type\Type;
use PHPStan\Type\UnionType;

class TranslationFunctionReturnTypeExtension implements DynamicFunctionReturnTypeExtension
{
    public function isFunctionSupported(FunctionReflection $functionReflection): bool
    {
        return $functionReflection->getName() === '__';
    }

    public function getTypeFromFunctionCall(
        FunctionReflection $functionReflection,
        FuncCall $functionCall,
        Scope $scope
    ): ?Type {
        return new UnionType([new StringType(), new ObjectType(Phrase::class)]);
    }
}

This workaround is not ideal, because this extension will prevent phpstan from displaying an error when a Phrase object is passed to a function that only accepts strings (e.g. public function foo(string $text).

added
Triage: Dev.ExperienceIssue related to Developer Experience and needs help with Triage to Confirm or Reject it
on Sep 27, 2022
self-assigned this
on Sep 28, 2022
m2-assistant

m2-assistant commented on Sep 28, 2022

@m2-assistant

Hi @engcom-Hotel. Thank you for working on this issue.
In order to make sure that issue has enough information and ready for development, please read and check the following instruction: 👇

  • 1. Verify that issue has all the required information. (Preconditions, Steps to reproduce, Expected result, Actual result).

    DetailsIf the issue has a valid description, the label Issue: Format is valid will be added to the issue automatically. Please, edit issue description if needed, until label Issue: Format is valid appears.

    2. Verify that issue has a meaningful description and provides enough information to reproduce the issue. If the report is valid, add Issue: Clear Description label to the issue by yourself.

    3. Add Component: XXXXX label(s) to the ticket, indicating the components it may be related to.

    4. Verify that the issue is reproducible on 2.4-develop branch

    Details- Add the comment @magento give me 2.4-develop instance to deploy test instance on Magento infrastructure.
    - If the issue is reproducible on 2.4-develop branch, please, add the label Reproduced on 2.4.x.
    - If the issue is not reproducible, add your comment that issue is not reproducible and close the issue and stop verification process here!

    5. Add label Issue: Confirmed once verification is complete.

    6. Make sure that automatic system confirms that report has been added to the backlog.

engcom-Hotel

engcom-Hotel commented on Sep 28, 2022

@engcom-Hotel
Contributor

Hello @guvra,

Thanks for the report and collaboration!

We have tried to reproduce the issue in Magento 2.4-develop instance and the issue is reproducible for us with the same steps as mentioned in the main description:

  1. At the root of your Magento project, create a file named Test.php with the following contents:
<?php

declare(strict_types=1);

namespace Foo\Bar\Controller;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\HttpGetActionInterface;
use Magento\Framework\View\Result\Page;

class Test extends Action implements HttpGetActionInterface
{
    public function execute()
    {
        $this->messageManager->addErrorMessage(__('foobar'));

        return $this->resultFactory->create(Page::class);
    }
}
  1. Run PHPStan:
vendor/bin/phpstan analyse --level 6 -c dev/tests/static/testsuite/Magento/Test/Php/_files/phpstan/phpstan.neon Test.php

Please find below the screenshot of the error for reference:

image

Hence confirming the issue.

Thanks

github-jira-sync-bot

github-jira-sync-bot commented on Sep 28, 2022

@github-jira-sync-bot

✅ Jira issue https://jira.corp.adobe.com/browse/AC-6760 is successfully created for this GitHub issue.

m2-assistant

m2-assistant commented on Sep 28, 2022

@m2-assistant

✅ Confirmed by @engcom-Hotel. Thank you for verifying the issue.
Issue Available: @engcom-Hotel, You will be automatically unassigned. Contributors/Maintainers can claim this issue to continue. To reclaim and continue work, reassign the ticket to yourself.

antoniocarboni

antoniocarboni commented on Apr 30, 2024

@antoniocarboni

I temp. fix with this row on ignoreErrors on phpstan config file

'#Parameter \#1 \$data of method Magento\\Framework\\Escaper::escapeHtml\(\) expects array\|string, Magento\\Framework\\Phrase given.#'

moved this to Ready for Development in Low Priority Backlogon Aug 19, 2024
ihor-sviziev

ihor-sviziev commented on Jan 31, 2025

@ihor-sviziev
Contributor

TBH I would not say that phpstan is reporting "false positives", because when used strict types - it will actually fail, so that's all the real issues.

I also found that related issue + pr that fixing a small sub-set of this issue, so I added it as a sub-task to this one

PS: I wrote my thoughts on how to properly fix the issue, maybe you @guvra or @antoniocarboni can write your thoughts on it?
#39572 (review)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Area: FrameworkComponent: ObjectManagerIssue: ConfirmedGate 3 Passed. Manual verification of the issue completed. Issue is confirmedPriority: P3May be fixed according to the position in the backlog.Progress: ready for devReported on 2.4.5Indicates original Magento version for the Issue report.Reproduced on 2.4.xThe issue has been reproduced on latest 2.4-develop branchTriage: Dev.ExperienceIssue related to Developer Experience and needs help with Triage to Confirm or Reject it

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @antoniocarboni@ihor-sviziev@guvra@engcom-Hotel@engcom-November

        Issue actions

          PHPStan returns false positives because of incoherent PHPDocs on functions/parameters that accept Phrase objects · Issue #36063 · magento/magento2