hxv / phpstan-event-dispatcher-exceptions
PHPStan 扩展和规则,用于 Symfony 事件调度器的异常。
0.1
2021-05-13 16:54 UTC
Requires
- php: ^7.1|^8.0
- phpstan/phpstan: ^0.12.87
- symfony/event-dispatcher: ^4.3|^5.0
Requires (Dev)
- phpstan/extension-installer: ^1.1
- phpstan/phpstan-strict-rules: ^0.12.9
- phpunit/phpunit: ^9.5
This package is auto-updated.
Last update: 2024-09-13 23:46:44 UTC
README
自版本 0.12.87 PHPStan 分析和检查抛出的异常 - 好消息!pepakriz/phpstan-exception-rules
做了同样的事情(更多),但默认情况下有这个功能也是好的。
然而,有些情况对于静态分析来说“太动态”了,无法自动工作,因此需要额外的扩展。这个扩展的目标是为 Symfony 的 Event Dispatcher 提供支持。
问题
每次你分发一个事件时,任何处理程序都可以抛出一个异常 - 由于 PHPStan 对它们一无所知,你可以
- 忽略它们
- 记住哪个事件抛出哪个异常
- 分析处理程序
- 处理程序中不抛出任何异常
- 捕获一切
如果你不选择第一个或最后一个选项,在修改处理程序时要非常小心 - 新的异常可能会引起问题。如果你这样做 - 嗯,你可能不需要这个扩展。
解决方案
上述问题的解决方案是为每个事件在类级别上使用 @throws
标签注释异常
/** * @throws RuntimeException */ class SomeEvent { }
将异常分配给事件分析可以使分析更完整,并警告新的问题。
从现在开始,PHPStan 知道分发该事件可能会抛出 RuntimeException
try { $eventDispatcher->dispatch(new SomeEvent()); } catch (RuntimeException $exception) { // no more error! // handle exception } // new exceptions needs to be handled or annotated at function level - you will not miss them
还有一个规则来监控订阅者中抛出的异常
class SomeEventSubscriber implements \Symfony\Component\EventDispatcher\EventSubscriberInterface { public static function getSubscribedEvents() { return [SomeEvent::class => 'handleEvent']; } /** * @throws RuntimeException <-- this is fine * @throws LogicException <-- this is not (unless LogicException is unchecked) */ public function handleEvent(): void { } }
安装
在 composer 中要求扩展
composer require --dev hxv/phpstan-event-dispatcher-exceptions
如果你有 PHPStan 扩展安装器 - 就这么简单!
如果没有 - 你必须手动将扩展添加到你的 phpstan.neon
includes: - vendor/hxv/phpstan-event-dispatcher-exceptions/extension.neon