typesetsh / dynamic-property-access-assume-type
Psalm 插件,用于支持动态属性访问和对象构建。由 typeset.sh 使用。
1.0.12
2024-01-11 13:38 UTC
Requires
- php: >=7.4
- vimeo/psalm: ^4.0 || ^5.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.8.0
- phpunit/phpunit: ~9.5.0
README
当使用 __get() 方法动态访问属性时,允许假设类型。
为具有类型声明的类添加 @universal-object-crate。
<?php /** * Some file doc comment. * * @see LICENSE.md */ declare(strict_types=1); namespace Typesetsh\Psalm\DynamicPropertyAccessAssumeType\Example; /** * @universal-object-crate int|null */ class M extends \stdClass { } /** * @property int $age */ class N extends M { public string $name = ''; } $m = new M(); $m->age = 34; $n = new N(); $n->name = 'John'; $n->age = 34; return [$m, $n];
为将类型转换为 array<string, {所有属性的联合}> 的数组添加 @allow-array-casting。
<?php /** * Some file doc comment. * * @see LICENSE.md */ declare(strict_types=1); namespace Typesetsh\DynamicProperties\Example; /** * @allow-array-casting */ class Data extends \stdClass { public string $name = ''; public int $age = 0; } $data = new Data(); foreach ((array) $data as $key => $value) { echo $key, $value; }
/** * @dynamic-property-access-assume-type */ class B { public string $name = ''; public function __get(string $name): int { throw new \RuntimeException('No such property'); } } /** * @dynamic-property-access-assume-type */ class A { public function __get(string $name): B { throw new \RuntimeException('No such property'); } } // dynamic property access $prop1 = (string) rand(1000, 9999); $prop2 = (string) rand(1000, 9999); $a = new A(); return $a->{$prop1}->{$prop2};