Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Null coalescence and casting precendence #2371

Closed
BackEndTea opened this issue Aug 19, 2019 · 5 comments
Closed

Null coalescence and casting precendence #2371

BackEndTea opened this issue Aug 19, 2019 · 5 comments

Comments

@BackEndTea
Copy link
Contributor

Given the following code:

<?php

function getContent(array $array) {
    return (string) $array['content'] ?? 'no content found';
}

var_dump(getContent(['content'=> 'aaaa']));
var_dump(getContent([]));

Psalm doens't error on this (besides the var_dumps).

This will however cause a notice for an undefined offset, as the casting takes place before the null coalescence.

The correct way would be as follows:

<?php

function getContent(array $array) {
    return (string) ($array['content'] ?? 'no content found');
}

https://phpstan.org/r/7cacfb28-6ef8-4d86-b915-825566c9c3bf

I would expect this to raise an error, that the coalescence is never used.

@ondrejmirtes
Copy link
Member

PHPStan doesn't complain about specific keys existence on general arrays. It would be too annoying.

See: https://phpstan.org/r/4e0d98db-a8f7-4233-906e-8bbb830c45a0

Versus: https://phpstan.org/r/5f334a16-0f44-4b9f-981b-c326b8d0b474

You can use phpDocs for this purpose: https://phpstan.org/r/b28c885b-a896-4095-aad0-3b5d90828257

@BackEndTea
Copy link
Contributor Author

I'm sorry i think i explained it wrong.

The issue is the fact that the coalescence is never used. And it is (most likely) a bug.

If no key is set you are writing

<?php

function getContent(array $array) {
    return "" ?? 'no content found';
}

Which would never trigger the coalescence either.

(Though that is also not an issue for phpstan) https://phpstan.org/r/6282f19b-1095-4b58-908d-bbc048340be8

@ondrejmirtes
Copy link
Member

Yes, this is not yet implemented. I have it on my todolist.

@ondrejmirtes
Copy link
Member

Implemented: phpstan/phpstan-src#36

If you re-run your playground examples, it shows the new error :)

@lock
Copy link

lock bot commented Apr 2, 2020

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

@lock lock bot locked as resolved and limited conversation to collaborators Apr 2, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants