soyhuce / empty-collection
正确理解Laravel空集合的PHPStan
0.1.0
2022-03-02 13:04 UTC
Requires
- php: ^8.0
- illuminate/database: ^9.0
- illuminate/support: ^9.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.6.0
- phpstan/phpstan: ^1.4.6
Suggests
- phpstan/phpstan: Install PHPStan ^1.4.6 to benefit from the static analysis
README
正确理解Laravel空集合的PHPStan
安装
您可以通过composer安装此包
composer require soyhuce/empty-collection
在您的PHPStan配置中添加提供的PHPStan扩展
includes: - ./vendor/soyhuce/empty-collection/extension.neon
此包不需要安装phpstan/phpstan
以保持其在开发依赖项中。请确保使用版本1.4.6
或更高版本。
使用方法
您是否遇到过Laravel中空集合类型错误的问题?您是否看到过这些PHPStan错误?
Property App\Service\MyService::$items (Illuminate\Support\Collection<int, App\Service\Item>) does not accept Illuminate\Support\Collection<*NEVER*, *NEVER*>.
Unable to resolve the template type TKey in call to function collect
Unable to resolve the template type TValue in call to function collect
我们来解决这个问题!
此包提供了一个简单的方法来初始化空集合,以便正确类型化PHPStan。
让我们举一个例子
class MyService { /** * @var \Illuminate\Support\Collection<int, App\Service\Item> */ private Collection $items; public function __construct() { - $this->items = collect(); + $this->items = empty_collection('int', Item::class); } }
这样,PHPStan就不会对集合的类型提出异议。
可用函数
empty_collection(string $keyType, string $valueType) : \Illuminate\Support\Collection
$keyType
必须是'int'
或'string'
。 $valueType
必须是PHPStan可以理解的类型。
示例
empty_collection('int', 'int'); // Illuminate\Support\Collection<int, int> empty_collection('int', 'string'); // Illuminate\Support\Collection<int, string> empty_collection('string', 'array<string, bool>'); // Illuminate\Support\Collection<string, array<string, bool>> empty_collection('string', Item::class); // Illuminate\Support\Collection<string, App\Service\Item>
empty_eloquent_collection(string $keyType, string $valueType) : \Illuminate\Database\Eloquent\Collection
$keyType
必须是'int'
或'string'
。 $valueType
必须是类名。
示例
empty_eloquent_collection('int', User::class); // Illuminate\Database\Eloquent\Collection<int, App\Models\User> empty_eloquent_collection('string', User::class); // Illuminate\Database\Eloquent\Collection<string, App\Models\User>
测试
测试是通过PHPStan完成的,可以使用以下命令运行
composer test
变更日志
请参阅变更日志以获取最近更改的更多信息。
许可证
MIT许可证(MIT)。请参阅许可证文件以获取更多信息。