struggle-for-php/sfp-phpstan-psr-log
Composer 安装命令:
composer require --dev struggle-for-php/sfp-phpstan-psr-log
包简介
Extra strict and opinionated psr/log (psr-3) rules for PHPStan
README 文档
README
struggle-for-php/sfp-phpstan-psr-log is extra strict and opinionated psr/log (psr-3) rules for PHPStan.
Installation
To use this extension, require it in Composer:
composer require --dev struggle-for-php/sfp-phpstan-psr-log
Manual installation
include extension.neon & rules.neon in your project's PHPStan config:
includes: - vendor/struggle-for-php/sfp-phpstan-psr-log/rules.neon
Recommendation Settings
Write these parameters to your project's phpstan.neon.
parameters: sfpPsrLog: enableMessageStaticStringRule: false # default:true enableContextRequireExceptionKeyRule: true reportContextExceptionLogLevel: 'info' contextKeyOriginalPattern: '#\A[A-Za-z0-9-_]+\z#'
Rules
This package provides the following rules.
PlaceholderCharactersRule
Placeholder names SHOULD be composed only of the characters A-Z, a-z, 0-9, underscore _, and period .
| 📌 error identifier |
|---|
| sfpPsrLog.placeholderCharactersInvalidChar |
- reports when placeholder in
$messagecharacters are not,A-Z,a-z,0-9, underscore_, and period.
// bad $logger->info('message are {foo-hyphen}');
| 📌 error identifier |
|---|
| sfpPsrLog.placeholderCharactersDoubleBraces |
- reports when double braces pair
{{}}are used.
// bad $logger->info('message are {{foo}}');
PlaceholderCorrespondToKeysRule
Placeholder names MUST correspond to keys in the context array.
| 📌 error identifier |
|---|
| sfpPsrLog.placeholderCorrespondToKeysMissedContext |
- reports when placeholder exists in message, but
$contextparameter is missed.
// bad $logger->info('message has {nonContext} .');
| 📌 error identifier |
|---|
| sfpPsrLog.placeholderCorrespondToKeysMissedKey |
- reports when placeholder exists in message, but key in
$contextdoes not exist against them.
// bad $logger->info('user {user_id} gets an error {error} .', ['user_id' => $user_id]);
ContextKeyRule
Note
PSR-3 has no provisions for array keys, but this is useful in many cases.
| 📌 error identifier |
|---|
| sfpPsrLog.contextKeyNonEmptyString |
- reports when context key is not non-empty-string.
// bad [123 => 'foo']`, `['' => 'bar']`, `['baz']
| 📌 error identifier |
|---|
| sfpPsrLog.contextKeyOriginalPattern |
- reports when context key is not matched you defined pattern.
- if
contextKeyOriginalPatternparameter is not set, this check would be ignored.
- if
Configuration
- You can set specific key pattern by regex.(
preg_match())
parameters: sfpPsrLog: contextKeyOriginalPattern: '#\A[A-Za-z0-9-]+\z#'
ContextRequireExceptionKeyRule
Note
This is not a rule for along with PSR-3 specification, but provides best practices.
| 📌 error identifier |
|---|
| sfpPsrLog.contextRequireExceptionKey |
- It forces
exceptionkey into context parameter when current scope has\Throwableobject.
Example
<?php /** @var \Psr\Log\LoggerInterface $logger */ try { // } catch (LogicException $exception) { $logger->warning("foo"); }
$ ../vendor/bin/phpstan analyse Note: Using configuration file /tmp/your-project/phpstan.neon. 2/2 [▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓] 100% ------ ------------------------------------------------------------- Line Demo.php ------ ------------------------------------------------------------- 6 Parameter $context of logger method Psr\Log\LoggerInterface::warning() requires \'exception\' key. Current scope has Throwable variable - $exception ------ ------------------------------------------------------------- [ERROR] Found 1 error
Configuration
- You can set the minimum required level to report. (default level is
debug)
parameters: sfpPsrLog: reportContextExceptionLogLevel: 'warning'
Then, debug| info | notice LogLevel is ignored for report.
} catch (\Exception $e) { $logger->info('more info'); // allow $logger->warning($e->getMessage(), ['exception' => $e]); }
- If you want to enable this rule, please add
enableContextRequireExceptionKeyRuleas true.
parameters: sfpPsrLog: enableContextRequireExceptionKeyRule: true
ContextTypeRule
Note
This rule validates that the $context parameter has the correct type according to PSR-3 specification.
| 📌 error identifier |
|---|
| sfpPsrLog.contextType |
- reports when
$contextparameter type does not match the expected type.- The default expected type is
array{exception?: Throwable}according to PSR-3.
- The default expected type is
// bad $logger->info('message', ['exception' => 'string value']); // exception must be Throwable
Configuration
- If you want to disable this rule, please add
enableContextTypeRuleas false.
parameters: sfpPsrLog: enableContextTypeRule: false
Advanced: Custom Context Type Provider
You can enforce stricter context types by implementing ContextTypeProviderInterface and injecting it via dependency injection.
- Example: Restricting to specific context keys
<?php // src/YourCustomContextTypeProvider.php use PHPStan\Type\ArrayType; use PHPStan\Type\Constant\ConstantArrayTypeBuilder; use PHPStan\Type\Constant\ConstantStringType; use PHPStan\Type\ObjectType; use PHPStan\Type\StringType; use PHPStan\Type\Type; use Sfp\PHPStan\Psr\Log\TypeProvider\ContextTypeProviderInterface; final class YourCustomContextTypeProvider implements ContextTypeProviderInterface { public function getType(): Type { $builder = ConstantArrayTypeBuilder::createEmpty(); // Define allowed context keys with their types $builder->setOffsetValueType( new ConstantStringType('user_id'), new StringType(), true // optional ); $builder->setOffsetValueType( new ConstantStringType('exception'), new ObjectType(\Throwable::class), true // optional ); return $builder->getArray(); } }
Configure in phpstan.neon:
services: yourCustomContextTypeProvider: class: YourCustomContextTypeProvider contextTypeProviderResolver: class: Sfp\PHPStan\Psr\Log\TypeProviderResolver\AnyScopeContextTypeProviderResolver arguments: contextTypeProvider: @yourCustomContextTypeProvider - class: Sfp\PHPStan\Psr\Log\Rules\ContextTypeRule arguments: contextTypeProviderResolver: @contextTypeProviderResolver tags: - phpstan.rules.rule
This allows you to enforce project-specific context types, such as structured logging schemas (e.g., BigQuery) or custom application requirements.
MessageStaticStringRule
| 📌 error identifier |
|---|
| sfpPsrLog.messageNotStaticString |
- reports when $message is not static string value.
// bad $logger->info(sprintf('Message contains %s variable', $var));
Configuration
- If you want to disable this rule, please add
enableMessageStaticStringRuleas false.
parameters: sfpPsrLog: enableMessageStaticStringRule: false
LogMethodLevelRule
Implementors MUST implement the following interface, which describes the eight methods to write logs to the eight RFC 5424 levels (debug, info, notice, warning, error, critical, alert, emergency). — PSR-3 Logger Interface
| 📌 error identifier |
|---|
| sfpPsrLog.logMethodLevel |
- reports when the
$levelparameter oflog()method is not a valid PSR-3 log level.- Valid log levels:
emergency,alert,critical,error,warning,notice,info,debug
- Valid log levels:
// bad $logger->log('panic', 'message'); // 'panic' is not a valid PSR-3 log level $logger->log(100, 'message'); // level must be a string
Configuration
- If you want to disable this rule, please add
enableLogMethodLevelRuleas false.
parameters: sfpPsrLog: enableLogMethodLevelRule: false
struggle-for-php/sfp-phpstan-psr-log 适用场景与选型建议
struggle-for-php/sfp-phpstan-psr-log 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 315.46k 次下载、GitHub Stars 达 42, 最近一次更新时间为 2020 年 03 月 14 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「logging」 「static analysis」 「psr-3」 「PSR3」 「PHPStan」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 struggle-for-php/sfp-phpstan-psr-log 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 struggle-for-php/sfp-phpstan-psr-log 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 struggle-for-php/sfp-phpstan-psr-log 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Bookdown.io With Bootswatch Styles And Prism Syntax Highlighting
TwigStan is a static analyzer for Twig templates powered by PHPStan
A Zend Framework module that sets up Monolog for logging in applications.
Sentiment analysis library for PHP.
Database Standardization and Analysis Tool for Laravel
Asynchronous Sentry for Symfony - Fire and forget
统计信息
- 总下载量: 315.46k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 43
- 点击次数: 28
- 依赖项目数: 9
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2020-03-14