icanhazstring/phpstan-readonly-property

此包已被弃用,不再维护。未建议替代包。

支持 PHPStan 的 #[IsReadonly] 构造函数属性

0.2.0 2021-11-16 10:49 UTC

This package is auto-updated.

Last update: 2023-05-11 14:00:07 UTC


README

支持 #[IsReadonly] 类属性。此库用于从 PHP 8.0 过渡到 8.1,直到引入 readonly 关键字。

安装

composer require --dev icanhazstring/phpstan-readonly-property

然后使用 PHPStan 扩展安装器

composer require --dev phpstan/extension-installer

或者手动将 vendor/icanhazstring/phpstan-readonly-property/rules.neon 添加到您的 phpstan.neon 配置文件中。

# phpstan.neon

includes:
    - vendor/icanhazstring/phpstan-readonly-property/rules.neon

用法

#[IsReadonly] 添加到您希望为只读的属性中。

<?php

final class User
{
    public function __constrct(
        #[IsReadonly] public string $name
    ) {}
}

$user = new User('fu');
$user->name = 'bar'; // Will fail

已知限制

使用 8.1 的 readonly 标志进行静态分析有一些限制。

多个设置器的使用无法检查

如果您使用设置器初始化 #[IsReadonly] 属性,PHPStan 无法检测对该只读属性设置器的多次调用。

final class Fu
{
    #[IsReadonly]
    public string $value;

    public function setValue(string $value)
    {
        $this->value = $value;
    }
}

$fu = new Fu();
$fu->setValue('bar');
$fu->setValue('baz'); // Will work with this extension, but NOT with 8.1 `readonly`