php-ds / ext-ds

An extension providing efficient data structures for PHP 7
https://medium.com/p/9dda7af674cd
MIT License
2.11k stars 95 forks source link

Allow passing `null` as `$length` to `slice()` methods #197

Closed HypeMC closed 1 year ago

HypeMC commented 1 year ago

Currently the slice() methods don't work if the value of $length is null, eg:

$vec = new \Ds\Vector();
$vec->push(1, 2, 3, 4, 5, 6, 7, 8, 9);

var_dump($vec->slice(2, null));
PHP Deprecated:  Ds\Vector::slice(): Passing null to parameter #2 ($length) of type ?int is deprecated in /test.php on line 7
PHP Stack trace:
PHP   1. {main}() /test.php:0
PHP   2. Ds\Vector->slice($index = 2, $length = NULL) /test.php:7

Deprecated: Ds\Vector::slice(): Passing null to parameter #2 ($length) of type ?int is deprecated in /test.php on line 7

Call Stack:
    0.0001     402344   1. {main}() /test.php:0
    0.0001     402608   2. Ds\Vector->slice($index = 2, $length = NULL) /test.php:7

/test.php:7:
class Ds\Vector#2 (0) {
}

This is inconsistent with how array_slice(), and by extension the polyfill work, which treat null the same as when no argument is passed: https://3v4l.org/rqsnF . It also makes using a variable harder, eg:

if ($length === null) {
    var_dump($vec->slice(2));
} else {
    var_dump($vec->slice(2, $length));
}

This PR proposes allowing passing null as the length and treating it the same as when the argument isn't passed.

Tests: https://github.com/php-ds/tests/pull/23

rtheunissen commented 1 year ago

@HypeMC this is great, thank you. Feels like we could simplify the parsing a bit, but this looks great. I'm looking forward to coming back to this project a bit, it's been too long.