Skip to content

Commit

Permalink
Add Exception code return type provider
Browse files Browse the repository at this point in the history
  • Loading branch information
VincentLanglet committed Jan 13, 2022
1 parent 90b330f commit 1d6ae16
Show file tree
Hide file tree
Showing 2 changed files with 95 additions and 0 deletions.
@@ -0,0 +1,34 @@
<?php

namespace Psalm\Internal\Provider\ReturnTypeProvider;

use Psalm\Plugin\EventHandler\Event\MethodReturnTypeProviderEvent;
use Psalm\Type;

class ExceptionCodeReturnTypeProvider implements \Psalm\Plugin\EventHandler\MethodReturnTypeProviderInterface
{
public static function getClassLikeNames() : array
{
return ['Throwable'];
}

public static function getMethodReturnType(MethodReturnTypeProviderEvent $event): ?Type\Union
{
$method_name_lowercase = $event->getMethodNameLowercase();
$fqcn = $event->getCalledFqClasslikeName();

if ($method_name_lowercase !== 'getcode') {
return null;
}

if ($fqcn === 'Exception' || $fqcn === 'Throwable') {
return null;
}

if (is_a($fqcn, \PDOException::class, true)) {
return Type::parseString('string');
}

return Type::parseString('int');
}
}
61 changes: 61 additions & 0 deletions tests/ReturnTypeProvider/ExceptionCodeTest.php
@@ -0,0 +1,61 @@
<?php

namespace Psalm\Tests\ReturnTypeProvider;

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

class ExceptionCodeTest extends TestCase
{
use ValidCodeAnalysisTestTrait;

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

0 comments on commit 1d6ae16

Please sign in to comment.