Skip to content

Instantly share code, notes, and snippets.

  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save stloyd/8a2f6fa3612c141fee8f75e1f6fef2e5 to your computer and use it in GitHub Desktop.
Custom PHPStan rule to disallow catching \Throwable exception
<?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