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

Allow asserting array offset certainty #3503

Merged
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
20 changes: 9 additions & 11 deletions src/Rules/Debug/FileAssertRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -171,15 +171,14 @@ private function processAssertVariableCertainty(array $args, Scope $scope): arra
// @phpstan-ignore staticMethod.dynamicName
$expectedCertaintyValue = TrinaryLogic::{$certainty->name->toString()}();
$variable = $args[1]->value;
if (!$variable instanceof Node\Expr\Variable) {
return [
RuleErrorBuilder::message('Invalid assertVariableCertainty call.')
->nonIgnorable()
->identifier('phpstan.unknownExpectation')
->build(),
];
}
if (!is_string($variable->name)) {
if ($variable instanceof Node\Expr\Variable && is_string($variable->name)) {
$actualCertaintyValue = $scope->hasVariableType($variable->name);
$variableDescription = sprintf('variable $%s', $variable->name);
} elseif ($variable instanceof Node\Expr\ArrayDimFetch && $variable->dim !== null) {
$offset = $scope->getType($variable->dim);
$actualCertaintyValue = $scope->getType($variable->var)->hasOffsetValueType($offset);
$variableDescription = sprintf('offset %s', $offset->describe(VerbosityLevel::precise()));
} else {
return [
RuleErrorBuilder::message('Invalid assertVariableCertainty call.')
->nonIgnorable()
Expand All @@ -188,13 +187,12 @@ private function processAssertVariableCertainty(array $args, Scope $scope): arra
];
}

$actualCertaintyValue = $scope->hasVariableType($variable->name);
if ($expectedCertaintyValue->equals($actualCertaintyValue)) {
return [];
}

return [
RuleErrorBuilder::message(sprintf('Expected variable certainty %s, actual: %s', $expectedCertaintyValue->describe(), $actualCertaintyValue->describe()))
RuleErrorBuilder::message(sprintf('Expected %s certainty %s, actual: %s', $variableDescription, $expectedCertaintyValue->describe(), $actualCertaintyValue->describe()))
->nonIgnorable()
->identifier('phpstan.variable')
->build(),
Expand Down
17 changes: 10 additions & 7 deletions src/Testing/TypeInferenceTestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ public function assertFileAsserts(
$variableName = $args[2];
$this->assertTrue(
$expectedCertainty->equals($actualCertainty),
sprintf('Expected %s, actual certainty of variable $%s is %s in %s on line %d.', $expectedCertainty->describe(), $variableName, $actualCertainty->describe(), $file, $args[3]),
sprintf('Expected %s, actual certainty of %s is %s in %s on line %d.', $expectedCertainty->describe(), $variableName, $actualCertainty->describe(), $file, $args[3]),
);
}
}
Expand Down Expand Up @@ -216,15 +216,18 @@ public static function gatherAssertTypes(string $file): array
// @phpstan-ignore staticMethod.dynamicName
$expectedertaintyValue = TrinaryLogic::{$certainty->name->toString()}();
$variable = $node->getArgs()[1]->value;
if (!$variable instanceof Node\Expr\Variable) {
self::fail(sprintf('ERROR: Invalid assertVariableCertainty call.'));
}
if (!is_string($variable->name)) {
if ($variable instanceof Node\Expr\Variable && is_string($variable->name)) {
$actualCertaintyValue = $scope->hasVariableType($variable->name);
$variableDescription = sprintf('variable $%s', $variable->name);
} elseif ($variable instanceof Node\Expr\ArrayDimFetch && $variable->dim !== null) {
$offset = $scope->getType($variable->dim);
$actualCertaintyValue = $scope->getType($variable->var)->hasOffsetValueType($offset);
$variableDescription = sprintf('offset %s', $offset->describe(VerbosityLevel::precise()));
} else {
self::fail(sprintf('ERROR: Invalid assertVariableCertainty call.'));
}

$actualCertaintyValue = $scope->hasVariableType($variable->name);
$assert = ['variableCertainty', $file, $expectedertaintyValue, $actualCertaintyValue, $variable->name, $node->getStartLine()];
$assert = ['variableCertainty', $file, $expectedertaintyValue, $actualCertaintyValue, $variableDescription, $node->getStartLine()];
} else {
$correctFunction = null;

Expand Down
2 changes: 1 addition & 1 deletion tests/PHPStan/Analyser/LegacyNodeScopeResolverTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -906,7 +906,7 @@ private function assertVariables(
$this->assertTrue(
$expectedCertainty->equals($certainty),
sprintf(
'Certainty of variable $%s is %s, expected %s',
'Certainty of %s is %s, expected %s',
$variableName,
$certainty->describe(),
$expectedCertainty->describe(),
Expand Down
2 changes: 1 addition & 1 deletion tests/PHPStan/Analyser/NodeScopeResolverTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,7 @@ public function testFile(string $file): void
$variableName = $args[2];

if ($expectedCertainty->equals($actualCertainty) !== true) {
$failures[] = sprintf("Certainty of variable \$%s on line %d:\nExpected: %s\nActual: %s\n", $variableName, $args[3], $expectedCertainty->describe(), $actualCertainty->describe());
$failures[] = sprintf("Certainty of %s on line %d:\nExpected: %s\nActual: %s\n", $variableName, $args[3], $expectedCertainty->describe(), $actualCertainty->describe());
}
}
}
Expand Down
28 changes: 28 additions & 0 deletions tests/PHPStan/Analyser/nsrt/assert-variable-certainty-on-array.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

declare(strict_types=1);

namespace AssertVariableCertaintyOnArray;

use PHPStan\TrinaryLogic;
use function PHPStan\Testing\assertVariableCertainty;

class Foo
{
/**
* @param array{firstName: string, lastName?: string, sub: array{other: string}} $context
*/
public function __invoke(array $context) : void
{
assertVariableCertainty(TrinaryLogic::createYes(), $context['firstName']);
assertVariableCertainty(TrinaryLogic::createYes(), $context['sub']);
assertVariableCertainty(TrinaryLogic::createYes(), $context['sub']['other']);

assertVariableCertainty(TrinaryLogic::createMaybe(), $context['lastName']);
assertVariableCertainty(TrinaryLogic::createMaybe(), $context['nonexistent']['somethingElse']);

assertVariableCertainty(TrinaryLogic::createNo(), $context['sub']['nonexistent']);
assertVariableCertainty(TrinaryLogic::createNo(), $context['email']);
}

}
8 changes: 6 additions & 2 deletions tests/PHPStan/Rules/Debug/FileAssertRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,17 @@ public function testRule(): void
37,
],
[
'Expected variable certainty Yes, actual: No',
'Expected variable $b certainty Yes, actual: No',
45,
],
[
'Expected variable certainty Maybe, actual: No',
'Expected variable $b certainty Maybe, actual: No',
46,
],
[
"Expected offset 'firstName' certainty No, actual: Yes",
65,
],
]);
}

Expand Down
19 changes: 19 additions & 0 deletions tests/PHPStan/Rules/Debug/data/file-asserts.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,23 @@ public function doBaz($a): void
assertVariableCertainty(TrinaryLogic::createMaybe(), $b);
}

/**
* @param array{firstName: string, lastName?: string, sub: array{other: string}} $context
*/
public function arrayOffset(array $context) : void
{
assertVariableCertainty(TrinaryLogic::createYes(), $context['firstName']);
assertVariableCertainty(TrinaryLogic::createYes(), $context['sub']);
assertVariableCertainty(TrinaryLogic::createYes(), $context['sub']['other']);

assertVariableCertainty(TrinaryLogic::createMaybe(), $context['lastName']);
assertVariableCertainty(TrinaryLogic::createMaybe(), $context['nonexistent']['somethingElse']);

assertVariableCertainty(TrinaryLogic::createNo(), $context['sub']['nonexistent']);
assertVariableCertainty(TrinaryLogic::createNo(), $context['email']);

// Deliberate error:
assertVariableCertainty(TrinaryLogic::createNo(), $context['firstName']);
}

}
11 changes: 11 additions & 0 deletions tests/PHPStan/Testing/TypeInferenceTestCaseTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use PHPStan\File\FileHelper;
use PHPUnit\Framework\AssertionFailedError;
use function array_values;
use function sprintf;

final class TypeInferenceTestCaseTest extends TypeInferenceTestCase
Expand Down Expand Up @@ -90,4 +91,14 @@ public function testFileAssertionFailedErrors(string $filePath, string $errorMes
$this->gatherAssertTypes($filePath);
}

public function testVariableOrOffsetDescription(): void
{
$filePath = __DIR__ . '/data/assert-certainty-variable-or-offset.php';

[$variableAssert, $offsetAssert] = array_values($this->gatherAssertTypes($filePath));

$this->assertSame('variable $context', $variableAssert[4]);
$this->assertSame("offset 'email'", $offsetAssert[4]);
Comment on lines +100 to +101
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I did it this way, because the rest in this test did not actually ran the assertions, it only waited for thrown acceptors. See line 91 above.

So if you think we should actually call the asserts, please tell me how, and I'll make the change.

Then we can assert on the full error message.

}

}
15 changes: 15 additions & 0 deletions tests/PHPStan/Testing/data/assert-certainty-variable-or-offset.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

namespace AssertCertaintyVariableOrOffset;

use PHPStan\TrinaryLogic;
use function PHPStan\Testing\assertVariableCertainty;

/**
* @param array{} $context
*/
function someMethod(array $context) : void
{
assertVariableCertainty(TrinaryLogic::createNo(), $context);
assertVariableCertainty(TrinaryLogic::createYes(), $context['email']);
}
Loading