tomasvotruba/cognitive-complexity
Composer 安装命令:
composer require tomasvotruba/cognitive-complexity
包简介
PHPStan rules to measure cognitive complexity of your classes and methods
README 文档
README
Cognitive complexity tells us, how difficult code is to understand by a reader.
How is cognitive complexity measured?
function get_words_from_number(int $number): string { $amountInWords = ''; if ($number === 1) { // + 1 $amountInWords = 'one'; } elseif ($number === 2) { // + 1 $amountInWords = 'couple'; } elseif ($number === 3) { // + 1 $amountInWords = 'a few'; } else { // + 1 $amountInWords = 'a lot'; } return $amountInWords; }
This function uses nesting, conditions and continue back and forth. It's hard to read and results in cognitive complexity of 4.
How to keep cognitive complexity on 1? Read Cognitive load is what matters or Sonar paper about cognitive complexity metrics that inspired this repository.
Install
composer require tomasvotruba/cognitive-complexity --dev
The package is available on PHP 7.4+.
Usage
With PHPStan extension installer, everything is ready to run.
Enable each item on their own with simple configuration:
# phpstan.neon parameters: cognitive_complexity: class: 50 function: 8
Detect complex Class Dependency Trees
In classes like controllers, Rector rules, PHPStan rules or other services of specific type, the complexity can be hidden in the __construct() dependencies. Simple class with 10 dependencies is more complex than complex class with 2 dependencies.
That's why there is a rule to detect these dependency trees. It checks:
- complexity of current class
- constructor dependencies and their class complexity together
Final number is compared and used as a final complexity:
# phpstan.neon parameters: cognitive_complexity: dependency_tree: 150 dependency_tree_types: # only these explicit types are checked, nothing else - Rector\Contract\Rector\RectorInterface
Happy coding!
tomasvotruba/cognitive-complexity 适用场景与选型建议
tomasvotruba/cognitive-complexity 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 5.65M 次下载、GitHub Stars 达 152, 最近一次更新时间为 2022 年 12 月 23 日, 在 PHP 生态内属于活跃度较高的组件。
我们在过去多个企业项目中使用过 tomasvotruba/cognitive-complexity 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 tomasvotruba/cognitive-complexity 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
统计信息
- 总下载量: 5.65M
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 153
- 点击次数: 30
- 依赖项目数: 176
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2022-12-23
