Weebly / phpstan-laravel

Laravel plugins for PHPStan
BSD 2-Clause "Simplified" License
51 stars 22 forks source link

Dealing with trans() #20

Closed eigan closed 6 years ago

eigan commented 6 years ago
function someMethod(): string
{
   return trans('my.translation.key');
}

Method someMethod should return string but returns array|Illuminate\Contracts\Translation\Translator|string|null.

The return type Illuminate\Contracts\Translation\Translator can be fixed by a patch to HelpersReturnTypeExtension(?), but it will still fail because of array cannot be converted to a string.

Ideas:

1) Use a wrapper method:

namespace Company;

function trans(string $key, array $replace = [], ?string $locale = null): ?string
{
   $translated = \trans($key, $replace, $locale);

   if(is_array($translated) {
       return $key;
   }

   return $translated;
}

This will make trans() autocompletion no longer work in PHPStorm

  1. force_string
    
    function force_string($value): string
    {
    return is_scalar($value) ? $value : "";
    }

force_string(trans('my.translation.key'));



3. Override laravel `trans()` method with the help of https://github.com/funkjedi/composer-include-files (not tested)