Specify detailed return type of parse()#79
Conversation
Codecov Report
@@ Coverage Diff @@
## master #79 +/- ##
=======================================
Coverage 98.54% 98.54%
=======================================
Files 1 1
Lines 137 137
=======================================
Hits 135 135
Misses 2 2
📣 We’re building smart automated test selection to slash your CI/CD build times. Learn more |
|
Note: if I go up to phpstan level 9, then it does not like me just using |
|
Level9 is very brutal. It does not allow mixed. Most of the time this means you need a lot of typing and/or ignores |
| // Removing last component from base path. | ||
| $path = $base['path']; | ||
| $length = strrpos((string) $path, '/'); | ||
| $path = (string) $base['path']; | ||
| $length = strrpos($path, '/'); | ||
| if (false !== $length) { | ||
| $path = substr($path, 0, $length); |
There was a problem hiding this comment.
with the detailed types, and level 9, phpstan found this.
To be really safe, we cast $path to a string straight away. Then its use at line 60 - passing to substr() is also safe.
| * @phpstan-ignore-next-line | ||
| */ | ||
| return | ||
| $result + [ |
There was a problem hiding this comment.
I guess my recent fix regarding + will resolve this phpstan error on the next release
|
If the type can be expressed in detail, then phpstan at a high level seems good at finding places where something is used in the wrong way. It takes effort to specify everything, but in the end it seems a good way to avoid dumb-type-errors and regressions. |
|
I will make a patch release to get this published, so that other repos that pull in sabre/uri as a dependency will get the updated type information and code... |
|
👍 thx for doing all this.. library users will benefit a lot from it |
If I increase phpstan level to 9, then it detects that
function parse(string $uri): arraycan returnarray<string, int|string|null>and that is correct.Key "port" is an int value. Other keys have a string value. "Unused" keys have value null.
If I actually document:
Then phpstan complains about:
because it has not been told the detail that:
Key "port" can have value
int|nullAll other keys have value
string|nullIf there is some way to express this in PHPdoc, then that would be good - because the line numbers above are processing keys that do not have
intvalue.For now, I set the type of the keys to
mixed- at least that recognizes that the values are definitely not all string.