Giter Site home page Giter Site logo

sfp-phpstan-psr-log's Introduction

psr/log(PSR-3) extensions for PHPStan

Latest Stable Version License Psalm coverage

struggle-for-php/sfp-phpstan-psr-log is extra strict and opinionated psr/log (psr-3) rules for PHPStan.

Important

Since 0.20.0, changed default rule settings.

  • MessageStaticStringRule is enabled by default.
  • ContextRequireExceptionKeyRule is disabled by default.
  • [Recommendation] write these parameters to your project's phpstan.neon.
parameters:
    sfpPsrLog:
        enableMessageStaticStringRule: true
        enableContextRequireExceptionKeyRule: true
        reportContextExceptionLogLevel: 'info'
        contextKeyOriginalPattern: '#\A[A-Za-z0-9-_]+\z#'

Stubs

This extension depends on our psr/log stub to serve strictness.

  • eg.
    • @param LogLevel::* $level at log() method
    • @param array{exception?: \Throwable} $context

See psr/log stub repository page to get more detail.

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
sfp-psr-log.placeholderCharactersInvalidChar
  • reports when placeholder in $message characters are not, A-Z, a-z, 0-9, underscore _, and period .
// bad
$logger->info('message are {foo-hyphen}');
๐Ÿ“Œ error identifier
sfp-psr-log.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
sfp-psr-log.placeholderCorrespondToKeysMissedContext
  • reports when placeholder exists in message, but $context parameter is missed.
// bad
$logger->info('message has {nonContext} .');
๐Ÿ“Œ error identifier
sfp-psr-log.placeholderCorrespondToKeysMissedKey
  • reports when placeholder exists in message, but key in $context does 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
sfp-psr-log.contextKeyNonEmptyString
  • reports when context key is not non-empty-string.
// bad
[123 => 'foo']`, `['' => 'bar']`, `['baz']
๐Ÿ“Œ error identifier
sfp-psr-log.contextKeyOriginalPattern
  • reports when context key is not matched you defined pattern.
    • if contextKeyOriginalPattern parameter is not set, this check would be ignored.

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
sfp-psr-log.contextRequireExceptionKey
  • It forces exception key into context parameter when current scope has \Throwable object.

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 enableContextRequireExceptionKeyRule as true.
parameters:
    sfpPsrLog:
        enableContextRequireExceptionKeyRule: true

MessageStaticStringRule

๐Ÿ“Œ error identifier
sfp-psr-log.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 enableMessageStaticStringRule as false.
parameters:
    sfpPsrLog:
        enableMessageStaticStringRule: false

Installation

To use this extension, require it in Composer:

composer require --dev struggle-for-php/sfp-phpstan-psr-log

If you also install phpstan/extension-installer then you're all set.

Manual installation

If you don't want to use phpstan/extension-installer, include extension.neon & rules.neon in your project's PHPStan config:

includes:
    - vendor/struggle-for-php/sfp-phpstan-psr-log/extension.neon
    - vendor/struggle-for-php/sfp-phpstan-psr-log/rules.neon

sfp-phpstan-psr-log's People

Contributors

sasezaki avatar tonyvlcek avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

sfp-phpstan-psr-log's Issues

Rules for context array should be get values with `->getConstantArrays()`

  • ContextKeyRule
  • ContextRequireExceptionKeyRule
    • seems useless. currently already variable array is supported, and union type is not supported. union type support is meaningless for this rule.
  • also PlaceholderCorrespondToKeysRule

current implementations only checks dynamic parameter $logger->info('foo', ['key' => 'bar']);.
Rules should be checked with phpdoc parameter, method scope array variable( $context = ['key' => 'bar']; $logger->info('foo', $context); )

ContextRequireExceptionKeyRule should support `non-capturing catches`

Also see refs. phpstan/phpstan#8663 ( Catching exception without capturing on PHP 7.4 is not allowed )
https://wiki.php.net/rfc/non-capturing_catches

Currently, would not be detected by ContextRequireExceptionKeyRule below case.

try {
  print 'Lets do something nasty here.';
  throw new Exception('This is nasty');
} catch (Exception) {
  print 'Exception occured';
  $this->logger->error('error happend'); // should be reported as requires \'exception\' key. 

Because, ContextRequireExceptionKeyRule does detects with findCurrentScopeThrowableVariable.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.