magento2 icon indicating copy to clipboard operation
magento2 copied to clipboard

Unclear/invalid return types in Magento\Framework\Escaper

Open navarr opened this issue 4 months ago • 2 comments

Summary

When running phpstan against phtml files on max level, the proper use of the Escaper can cause all sorts of errors due to the poor return types in this class.

First: Almost every method takes a value that can be cast to a string, but all declare that the type is string. This methods should document that it is a type equivalent to \Stringable|scalar instead of string.

Second: escapeHtml outputs either an array or a string, which causes typesafety concerns when having code as simple as <?= $escaper->escapeHtml($stringVariable) ?> since phpstan knows escapeHtml could return an array. To fix this, we should instruct phpstan under what circumstances an array might be returned. For example: @phpstan-return ($data is array ? string[] : string)

To fix this in my own code, I've ended up having to stub out the Escaper class (see https://github.com/bitExpert/phpstan-magento/issues/343 )

Examples

(see summary)

Proposed solution

No response

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.
  • [x] 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”.

navarr avatar Jun 19 '25 15:06 navarr