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

Add Exception->getCode() return type provider #7390

Merged
merged 8 commits into from Jan 24, 2022
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Expand Up @@ -2,6 +2,8 @@

namespace Psalm\Internal\Analyzer\Statements\Expression\Call\Method;

use Exception;
use PDOException;
use PhpParser;
use Psalm\CodeLocation;
use Psalm\Codebase;
Expand All @@ -27,6 +29,7 @@
use Psalm\Type\Atomic\TNamedObject;
use Psalm\Type\Atomic\TTemplateParam;
use Psalm\Type\Union;
use Throwable;
use UnexpectedValueException;

use function array_filter;
Expand Down Expand Up @@ -92,6 +95,16 @@ public static function fetch(
}
}

if ($premixin_method_id->method_name === 'getcode'
&& $premixin_method_id->fq_class_name !== Exception::class
&& in_array(Throwable::class, $class_storage->class_implements)) {
if ($premixin_method_id->fq_class_name === PDOException::class) {
orklah marked this conversation as resolved.
Show resolved Hide resolved
return Type::getString();
} else {
return Type::getInt(true); // TODO: Remove the flag in Psalm 5
}
}

if ($declaring_method_id && $declaring_method_id !== $method_id) {
$declaring_fq_class_name = $declaring_method_id->fq_class_name;
$declaring_method_name = $declaring_method_id->method_name;
Expand Down
53 changes: 53 additions & 0 deletions tests/ReturnTypeProvider/ExceptionCodeTest.php
@@ -0,0 +1,53 @@
<?php

namespace Psalm\Tests\ReturnTypeProvider;

use Psalm\Tests\TestCase;
use Psalm\Tests\Traits\ValidCodeAnalysisTestTrait;

class ExceptionCodeTest extends TestCase
{
use ValidCodeAnalysisTestTrait;

public function providerValidCodeParse(): iterable
{
yield 'RuntimeException' => [
'<?php
function f(\RuntimeException $e): int {
return $e->getCode();
}
',
[],
];
yield 'LogicException' => [
'<?php
function f(\LogicException $e): int {
return $e->getCode();
}
',
[],
];
yield 'PDOException' => [
'<?php
function f(\PDOException $e): string {
return $e->getCode();
}
',
[],
];
yield 'Exception' => [
'<?php
/** @var \Throwable $e */
$code = $e->getCode();
',
['$code' => 'int|string'],
];
yield 'Throwable' => [
'<?php
/** @var \Exception $e */
$code = $e->getCode();
',
['$code' => 'int|string'],
];
}
}