Skip to content
Open
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: 13 additions & 6 deletions src/Rules/Arrays/ArrayDestructuringRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,13 @@
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
use PHPStan\Rules\RuleLevelHelper;
use PHPStan\Type\ArrayType;
use PHPStan\Type\Constant\ConstantIntegerType;
use PHPStan\Type\ErrorType;
use PHPStan\Type\MixedType;
use PHPStan\Type\ObjectType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use PHPStan\Type\VerbosityLevel;
use function array_merge;
use function sprintf;
Expand Down Expand Up @@ -68,15 +71,19 @@ private function getErrors(Scope $scope, Node\Expr\List_ $var, Expr $expr): arra
if ($exprType instanceof ErrorType) {
return [];
}
$errors = [];
if (!$exprType->isArray()->yes() && !(new ObjectType(ArrayAccess::class))->isSuperTypeOf($exprType)->yes()) {
return [
RuleErrorBuilder::message(sprintf('Cannot use array destructuring on %s.', $exprType->describe(VerbosityLevel::typeOnly())))
->identifier('offsetAccess.nonArray')
->build(),
];
$errors[] = RuleErrorBuilder::message(sprintf('Cannot use array destructuring on %s.', $exprType->describe(VerbosityLevel::typeOnly())))
->identifier('offsetAccess.nonArray')
->build();
if (!$exprType->isArray()->maybe()) {
return $errors;
}

// array{0?: int}|false: the keys can also be missing on the array part
$expr = new TypeExpr(TypeCombinator::intersect($exprType, new ArrayType(new MixedType(), new MixedType())));
}

$errors = [];
$i = 0;
foreach ($var->items as $item) {
if ($item === null) {
Expand Down
5 changes: 5 additions & 0 deletions src/Rules/Arrays/NonexistentOffsetInArrayDimFetchCheck.php
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,11 @@ public function check(
: TypeCombinator::intersect(AllowedArrayKeysTypes::getType(), $dimType);

foreach ($flattenedTypes as $innerType) {
if (!$innerType->isOffsetAccessible()->yes()) {
// array{host: string}|false: the rule already reports the offset access on false
continue;
}

$dimTypeToCheck = $innerType->isArray()->yes() ? $validArrayDimType : $dimType;

if (
Expand Down
39 changes: 27 additions & 12 deletions src/Rules/Arrays/NonexistentOffsetInArrayDimFetchRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use PHPStan\DependencyInjection\AutowiredParameter;
use PHPStan\DependencyInjection\RegisteredRule;
use PHPStan\Internal\SprintfHelper;
use PHPStan\Rules\IdentifierRuleError;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
use PHPStan\Rules\RuleLevelHelper;
Expand All @@ -18,6 +19,7 @@
use PHPStan\Type\ErrorType;
use PHPStan\Type\Type;
use PHPStan\Type\VerbosityLevel;
use function array_merge;
use function count;
use function in_array;
use function is_string;
Expand Down Expand Up @@ -83,18 +85,13 @@ public function processNode(Node $node, Scope $scope): array
return [];
}

$errors = [];
if (!$isOffsetAccessible->yes()) {
if ($isOffsetAccessible->no() || $this->reportMaybes) {
if ($dimType !== null) {
return [
RuleErrorBuilder::message(sprintf(
'Cannot access offset %s on %s.',
$dimType->describe(count($dimType->getConstantStrings()) > 0 ? VerbosityLevel::precise() : VerbosityLevel::value()),
$isOffsetAccessibleType->describe(VerbosityLevel::value()),
))->identifier('offsetAccess.nonOffsetAccessible')->build(),
];
}
if (!$isOffsetAccessible->no() && !$this->reportMaybes) {
return [];
}

if ($dimType === null) {
return [
RuleErrorBuilder::message(sprintf(
'Cannot access an offset on %s.',
Expand All @@ -103,13 +100,31 @@ public function processNode(Node $node, Scope $scope): array
];
}

return [];
$errors[] = RuleErrorBuilder::message(sprintf(
'Cannot access offset %s on %s.',
$dimType->describe(count($dimType->getConstantStrings()) > 0 ? VerbosityLevel::precise() : VerbosityLevel::value()),
$isOffsetAccessibleType->describe(VerbosityLevel::value()),
))->identifier('offsetAccess.nonOffsetAccessible')->build();
// a write creates the offset, so only a read can find it missing
if ($isOffsetAccessible->no() || $scope->isInExpressionAssign($node)) {
return $errors;
}

// array{host?: string}|false: the offset can also be missing on the offset-accessible part
}

if ($dimType === null) {
return [];
return $errors;
}

return array_merge($errors, $this->checkOffset($node, $scope, $dimType, $unknownClassPattern));
}

/**
* @return list<IdentifierRuleError>
*/
private function checkOffset(Node\Expr\ArrayDimFetch $node, Scope $scope, Type $dimType, string $unknownClassPattern): array
{
if (
$node->dim instanceof Node\Expr\FuncCall
&& !$node->dim->isFirstClassCallable()
Expand Down
5 changes: 5 additions & 0 deletions tests/PHPStan/Levels/data/arrayDimFetches-7.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@
"line": 28,
"ignorable": true
},
{
"message": "Offset 'b' might not exist on array{a: 1}|stdClass.",
"line": 28,
"ignorable": true
},
{
"message": "Offset 'b' might not exist on array{a: 1, b?: 1}.",
"line": 40,
Expand Down
30 changes: 30 additions & 0 deletions tests/PHPStan/Rules/Arrays/ArrayDestructuringRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -123,4 +123,34 @@ public function testRuleWithNullsafeVariant(): void
]);
}

public function testMaybeArray(): void
{
$this->analyse([__DIR__ . '/data/array-destructuring-maybe-array.php'], [
[
'Cannot use array destructuring on array<int, int>|false.',
13,
],
[
'Offset 0 might not exist on array{0?: int, 1: int}.',
13,
],
[
'Cannot use array destructuring on list<int>|false.',
21,
],
[
'Cannot use array destructuring on list<list<int>>|false.',
29,
],
[
'Offset 0 might not exist on array{0?: int}.',
29,
],
[
'Cannot use array destructuring on ArrayAccess<int, int>|false.',
37,
],
]);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -1444,4 +1444,54 @@ public function testUnsealedArrayShapes(bool $reportPossiblyNonexistentGeneralAr
$this->analyse([__DIR__ . '/data/unsealed-array-shapes-has-offset.php'], $expectedErrors);
}

public function testOffsetOnMaybeAccessible(): void
{
$this->analyse([__DIR__ . '/data/offset-on-maybe-accessible.php'], [
[
'Cannot access offset \'host\' on array{host?: string}|false.',
13,
],
[
'Offset \'host\' might not exist on array{host?: string}|false.',
13,
],
[
'Cannot access offset \'host\' on array{host: string}|false.',
21,
],
[
'Cannot access offset \'host\' on array{host?: string}|int.',
29,
],
[
'Offset \'host\' might not exist on array{host?: string}|int.',
29,
],
[
'Cannot access offset \'host\' on array{scheme?: string, host?: string, port?: int<0, 65535>, user?: string, pass?: string, path?: string, query?: string, fragment?: string}|false.',
35,
],
[
'Offset \'host\' might not exist on array{scheme?: string, host?: string, port?: int<0, 65535>, user?: string, pass?: string, path?: string, query?: string, fragment?: string}|false.',
35,
],
[
'Offset \'host\' might not exist on array{host?: string}.',
47,
],
[
'Cannot access offset \'host\' on array{host?: string}|false.',
55,
],
[
'Cannot access offset \'host\' on array{host: string}|stdClass.',
67,
],
[
'Cannot access offset \'host\' on array{host: string}|iterable<int, int>.',
75,
],
]);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

namespace ArrayDestructuringMaybeArray;

class Foo
{

/**
* @param array{0?: int, 1: int}|false $value
*/
public function optionalKeyOrFalse($value): void
{
[$a, $b] = $value;
}

/**
* @param array{0: int, 1: int}|false $value
*/
public function requiredKeysOrFalse($value): void
{
[$a, $b] = $value;
}

/**
* @param array{0: array{0?: int}}|false $value
*/
public function nested($value): void
{
[[$a]] = $value;
}

/**
* @param \ArrayAccess<int, int>|false $value
*/
public function arrayAccessOrFalse($value): void
{
[$a] = $value;
}

}
78 changes: 78 additions & 0 deletions tests/PHPStan/Rules/Arrays/data/offset-on-maybe-accessible.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
<?php

namespace OffsetOnMaybeAccessible;

class Foo
{

/**
* @param array{host?: string}|false $value
*/
public function optionalKeyOrFalse($value): void
{
echo $value['host'];
}

/**
* @param array{host: string}|false $value
*/
public function requiredKeyOrFalse($value): void
{
echo $value['host'];
}

/**
* @param array{host?: string}|int $value
*/
public function optionalKeyOrInt($value): void
{
echo $value['host'];
}

public function parseUrl(string $url): void
{
$parsed = parse_url($url);
echo $parsed['host'];
}

/**
* @param array{host?: string}|false $value
*/
public function guarded($value): void
{
if ($value === false) {
return;
}

echo $value['host'];
}

/**
* @param array{host?: string}|false $value
*/
public function writes($value): void
{
$value['host'] = 'x';
$value['host'] ??= 'x';
$value['host'][] = 'x';
$ref = &$value['host'];
[$value['host']] = ['x'];
}

/**
* @param array{host: string}|\stdClass $value
*/
public function requiredKeyOrObject($value): void
{
echo $value['host'];
}

/**
* @param array{host: string}|iterable<int, int> $value
*/
public function requiredKeyOrIterable($value): void
{
echo $value['host'];
}

}
Loading