brainbits/phpstan-rules

PHPStan extension with opinionated strict rules for better code in tests.

Installs: 10 607

Dependents: 8

Suggesters: 2

Security: 0

Stars: 1

Watchers: 5

Forks: 1

Open Issues: 1

Type:phpstan-extension

3.1.2 2024-02-21 11:06 UTC

This package is auto-updated.

Last update: 2024-04-22 11:21:08 UTC


README

Continuous Integration Coverage Status Codacy Badge Latest Stable Version License

This extension provides highly opinionated and strict rules for test cases for the PHPStan static analysis tool.

Installation

Run

$ composer require --dev brainbits/phpstan-rules

Usage

All of the rules provided by this library are included in rules.neon.

When you are using phpstan/extension-installer, rules.neon will be automatically included.

Otherwise you need to include rules.neon in your phpstan.neon:

# phpstan.neon
includes:
    - vendor/brainbits/phpstan-rules/rules.neon

Rules

This package provides the following rules for use with phpstan/phpstan:

CoversClassExistsRule

This rule checks that classes that are covered by @covers annotation or #[CoversClass] attribute exist.

CoversClassPresentRule

This rule forces you to specify either a @covers annotation or #[CoversClass], #[CoversFunction] or #[CoversNothing] attributes in unit tests (default: PHPUnit\Framework\TestCase).

Why:

  1. It prevents code coverage sums to show higher values than expected.

// tests/ExampleTestCase/Unit/MyInvalidClassTest.php
namespace ExampleTestCase\Unit;

final class MyInvalidClassTest extends \PHPUnit\Framework\TestCase {}

// tests/ExampleTestCase/Unit/MyClassTest.php
namespace ExampleTestCase\Unit;

#[\PHPUnit\Framework\Attributes\CoversClass(MyClass::class)
final class MyClassTest extends \PHPUnit\Framework\TestCase {}

Defaults

  • By default, this rule detects unit tests by checking the namespace (it must contain the string Unit) and the class name ending (it must end with the string Test).

Detecting unit tests namespace

If you want to change the namespace string check described above, you can set your own string to be checked in the unitTestNamespaceContainsString parameter.

# phpstan.neon
parameters:
    brainbits:
        unitTestNamespaceContainsString: CustomTestPath