Skip to content

Commit

Permalink
Merge pull request #7390 from VincentLanglet/exceptionCode
Browse files Browse the repository at this point in the history
Add Exception->getCode() return type provider
  • Loading branch information
orklah committed Jan 24, 2022
2 parents 3a6dc9b + 9905bae commit 0619b40
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
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) {
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'],
];
}
}

0 comments on commit 0619b40

Please sign in to comment.