assert
assert copied to clipboard
[FR] Assert property initialized
Would it make sense to add a new assertion that would check that property is initialized?
Oh, How would that assertion look like?
Since we can't access the property before we know it's initialized I see only this way
class X {
public ?string $a;
}
function isInit(object $object, string $prop) : void {
$rp = new ReflectionProperty($object::class, $prop);
if($rp->isInitialized($object)) {
return;
}
throw new Exception('Not init');
}
$x = new X;
$x->a = null;
isInit($x, 'a');
$x = new X;
isInit($x, 'a');
Maybe instead of this, it could be written as Assert::true(isset($a->id)); ?
@ruudk have you tried it? isset cannot distinguish between not not defined variable, not initialised property and a null value.
@zerkms You're right.
However, in my use case, using Doctrine entities with autoincrement ids, this was fine as I just want to make sure there is a value.
class Entity {
/**
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private int $id;
public function getId(): int
{
Assert::true(isset($this->id));
return $this->id;
}
}
@ruudk Assert::notNull($this->id);
@zerkms private int $id cannot ever be null. PHPStan: Call to static method Webmozart\Assert\Assert::notNull() with int will always evaluate to true.
@ruudk if it can never be null - why do you check it with isset? Your typing lies then and phpstan should report that as well.
It's a long time since I opened the FR and I did not find the use case I needed it for. But yes, one can't use isset(), the only way it currently through reflection AFAIK. That's why there's public ?string $a; in my example.