Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 17 additions & 2 deletions src/Type/Constant/ConstantArrayType.php
Original file line number Diff line number Diff line change
Expand Up @@ -939,8 +939,23 @@ public function sliceArray(Type $offsetType, Type $lengthType, TrinaryLogic $pre
return $this;
}

$offset = $offsetType instanceof ConstantIntegerType ? $offsetType->getValue() : 0;
$length = $lengthType instanceof ConstantIntegerType ? $lengthType->getValue() : $keyTypesCount;
$offset = $offsetType instanceof ConstantIntegerType ? $offsetType->getValue() : null;

if ($lengthType instanceof ConstantIntegerType) {
$length = $lengthType->getValue();
} elseif ($lengthType->isNull()->yes()) {
$length = $keyTypesCount;
} else {
$length = null;
}

if ($offset === null || $length === null) {
$builder = ConstantArrayTypeBuilder::createFromConstantArray($this);
$builder->degradeToGeneralArray();

return $builder->getArray()
->sliceArray($offsetType, $lengthType, $preserveKeys);
}

if ($length < 0) {
// Negative lengths prevent access to the most right n elements
Expand Down
1 change: 1 addition & 0 deletions tests/PHPStan/Analyser/nsrt/array-slice.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ public function constantArrays(array $arr): void
/** @var array{17: 'foo', b: 'bar', 19: 'baz'} $arr */
assertType('array{b: \'bar\', 0: \'baz\'}', array_slice($arr, 1, 2));
assertType('array{b: \'bar\', 19: \'baz\'}', array_slice($arr, 1, 2, true));
assertType('array<17|19|\'b\', \'bar\'|\'baz\'|\'foo\'>', array_slice($arr, rand(0, 1) ? 0 : 1, rand(0, 1) ? 0 : 1));

/** @var array{17: 'foo', 19: 'bar', 21: 'baz'}|array{foo: 17, bar: 19, baz: 21} $arr */
assertType('array{\'bar\', \'baz\'}|array{bar: 19, baz: 21}', array_slice($arr, 1, 2));
Expand Down
Loading