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 cfcf70b
Show file tree
Hide file tree
Showing 2 changed files with 90 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');
}
}
56 changes: 56 additions & 0 deletions tests/ReturnTypeProvider/ExceptionCodeTest.php
@@ -0,0 +1,56 @@
<?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;
use InvalidCodeAnalysisTestTrait;

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()
}
',
];
}

public function providerInvalidCodeParse(): iterable
{
yield 'Exception' => [
'<?php
function f(\Exception $e): int {
return $e->getCode()
}
',
];
yield 'Throwable' => [
'<?php
function f(\Throwable $e): int {
return $e->getCode()
}
',
];
}
}

0 comments on commit cfcf70b

Please sign in to comment.