Add support for constructor assertions#2950
Add support for constructor assertions#2950ondrejmirtes merged 1 commit intophpstan:1.10.xfrom axlon:constructor-assert
Conversation
|
You've opened the pull request against the latest branch 1.11.x. If your code is relevant on 1.10.x and you want it to be released sooner, please rebase your pull request and change its target to 1.10.x. |
ondrejmirtes
left a comment
There was a problem hiding this comment.
What do you mean by "partially"?
| } | ||
| } | ||
|
|
||
| /** |
There was a problem hiding this comment.
Move this into anonymous function and use a string parameter coming into the function.
@ondrejmirtes This PR currently does not tackle assertions on promoted properties, so for example: class Person
{
/** @phpstan-assert non-empty-string $this->firstName */
public function __construct(public string $firstName) {}
}
$person = new Person($firstName);
dumpType($person->firstName); // non-empty-stringI'm working on this as well but it needs a little more time |
|
This use case does not make sense to me, you can type the property to be non-empty-string from the start, no need to assert it. |
|
The use case is being able to annotate promoted props to be a narrowed version of the variable going in. I skipped some statements in my original example for brevity but there was supposed to be an assert call in the constructor asserting the promoted prop was not empty. Essential this, but with promoted props: class Person
{
/**
* @var non-empty-string
*/
public string $firstName;
public function __construct(string $firstName)
{
assert($firstName !== '');
$this->firstName = $firstName;
}
}I am aware I could also annotate the class with |
|
Thank you! |
Enables the following:
Fixes phpstan/phpstan#10645 (partially)