mirror of
https://github.com/danog/psalm.git
synced 2024-11-27 04:45:20 +01:00
Merge pull request #7390 from VincentLanglet/exceptionCode
Add Exception->getCode() return type provider
This commit is contained in:
commit
0619b404e5
@ -2,6 +2,8 @@
|
||||
|
||||
namespace Psalm\Internal\Analyzer\Statements\Expression\Call\Method;
|
||||
|
||||
use Exception;
|
||||
use PDOException;
|
||||
use PhpParser;
|
||||
use Psalm\CodeLocation;
|
||||
use Psalm\Codebase;
|
||||
@ -27,6 +29,7 @@ use Psalm\Type\Atomic\TGenericObject;
|
||||
use Psalm\Type\Atomic\TNamedObject;
|
||||
use Psalm\Type\Atomic\TTemplateParam;
|
||||
use Psalm\Type\Union;
|
||||
use Throwable;
|
||||
use UnexpectedValueException;
|
||||
|
||||
use function array_filter;
|
||||
@ -92,6 +95,16 @@ class MethodCallReturnTypeFetcher
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
|
53
tests/ReturnTypeProvider/ExceptionCodeTest.php
Normal file
53
tests/ReturnTypeProvider/ExceptionCodeTest.php
Normal file
@ -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'],
|
||||
];
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user