Custom PHPStan rule to disallow catching \Throwable exception
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
namespace App\PHPStan\Rules; | |
use PhpParser\Node; | |
use PhpParser\Node\Stmt; | |
use PHPStan\Analyser\Scope; | |
use PHPStan\Rules\Rule; | |
/** | |
* @implements Rule<Stmt> | |
*/ | |
class DisallowCatchingThrowableExceptionRule implements Rule | |
{ | |
private const THROWABLE_NODE_ATTRIBUTE = '__THROWABLE_NODE_ATTRIBUTE__'; | |
public function getNodeType(): string | |
{ | |
return Stmt::class; | |
} | |
/** | |
* @return string[] | |
*/ | |
public function processNode(Node $node, Scope $scope): array | |
{ | |
if ($node instanceof Stmt\TryCatch) { | |
foreach ($node->catches as $catch) { | |
$catchClasses = array_map(static function (Node\Name $node): string { | |
return $node->toString(); | |
}, $catch->types); | |
if (!in_array(\Throwable::class, $catchClasses, true)) { | |
continue; | |
} | |
$catch->setAttribute(self::THROWABLE_NODE_ATTRIBUTE, 'You cannot catch the \Throwable exception'); | |
break; | |
} | |
return []; | |
} | |
if ($node instanceof Stmt\Catch_ && $node->hasAttribute(self::THROWABLE_NODE_ATTRIBUTE)) { | |
return [$node->getAttribute(self::THROWABLE_NODE_ATTRIBUTE)]; | |
} | |
return []; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment