Skip to content
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[*]
charset = utf-8
end_of_line = lf
trim_trailing_whitespace = true
insert_final_newline = true
indent_style = space
indent_size = 4
12 changes: 12 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
* text=auto

/cache export-ignore
/.editorconfig export-ignore
/.gitattributes export-ignore
/.github export-ignore
/.gitignore export-ignore
/temp-clone export-ignore
/composer-dependency-analyser.php export-ignore
/phpcs.xml.dist export-ignore
/phpstan.neon.dist export-ignore
/phpunit.xml.dist export-ignore
30 changes: 30 additions & 0 deletions .github/workflows/checks.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
name: Checks
on:
pull_request:
push:
branches:
- "master"
- "v[0-9]"
jobs:
checks:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
php-version: ['7.4', '8.0', '8.1', '8.2', '8.3', '8.4']
steps:
-
name: Checkout code
uses: actions/checkout@v4
-
name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php-version }}
-
name: Install dependencies
run: composer install --no-progress --prefer-dist --no-interaction

-
name: Run checks
run: composer check
26 changes: 26 additions & 0 deletions .github/workflows/lint.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
name: phpcs.xml lint
on:
pull_request:
push:
branches:
- "master"
- "v[0-9]"

jobs:
xml-linter:
runs-on: ubuntu-latest
steps:
-
name: Checkout code
uses: actions/checkout@v4

-
name: Install dependencies
run: composer install --no-progress --no-interaction

-
name: Lint
uses: ChristophWurst/xmllint-action@v1
with:
xml-file: phpcs.xml.dist
xml-schema-file: vendor/squizlabs/php_codesniffer/phpcs.xsd
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
/vendor
/cache/*
!/cache/.gitkeep
/.idea
/phpstan.neon
composer.lock
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2025 Bedabox, LLC dba ShipMonk

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
206 changes: 206 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,206 @@
# PHPStan Development Utilities

Development utilities for PHPStan rules testing, extracted from [shipmonk/phpstan-rules](https://github.com/shipmonk-rnd/phpstan-rules).

This package provides the `RuleTestCase` class - an enhanced testing framework specifically designed for testing PHPStan rules with additional validation and convenience features.

## Installation

```bash
composer require --dev shipmonk/phpstan-dev
```

## Quick Start

### 1. Create Your Rule Test Class

```php
<?php declare(strict_types = 1);

namespace YourNamespace;

use ShipMonk\PHPStanDev\RuleTestCase;
use PHPStan\Rules\Rule;

/**
* @extends RuleTestCase<YourRule>
*/
class YourRuleTest extends RuleTestCase
{
protected function getRule(): Rule
{
return new YourRule();
}

public function testRule(): void
{
$this->analyseFile(__DIR__ . '/Data/YourRule/code.php');
}
}
```

### 2. Create Test Data File

Create `tests/Rule/Data/YourRule/code.php`:

```php
<?php declare(strict_types = 1);

namespace YourRule;

function test() {
$valid = 'This is valid code';
$invalid = something(); // error: Your custom error message here
}
```

### 3. Run Your Test

```bash
vendor/bin/phpunit tests/Rule/YourRuleTest.php
```

## Key Features

### 🎯 Error Comment System

Use `// error: <message>` comments in test files to specify expected errors:

```php
<?php

$validCode = 'No error expected here';
$invalidCode = forbidden(); // error: This is forbidden
$alsoInvalid = another(); // error: Another error message
```

### 🔧 Autofix Mode

During development, automatically generate error comments:

```php
public function testRule(): void
{
// Set to true temporarily to generate error comments
$this->analyseFile(__DIR__ . '/Data/code.php', autofix: true);
}
```

**⚠️ Important**: Remove `autofix: true` before committing - tests will fail if autofix is enabled.

### 🛡️ Automatic Error Validation

Every error is automatically validated:
- ✅ Must have an identifier
- ✅ Errors are matched to specific line numbers

## Advanced Usage

### Multiple Test Scenarios

```php
class ComplexRuleTest extends RuleTestCase
{
private bool $strictMode = false;

protected function getRule(): Rule
{
return new ComplexRule($this->strictMode);
}

public function testDefault(): void
{
$this->analyseFile(__DIR__ . '/Data/ComplexRule/default.php');
}

public function testStrict(): void
{
$this->strictMode = true;
$this->analyseFile(__DIR__ . '/Data/ComplexRule/strict.php');
}
}
```

### PHP Version-Specific Tests

```php
public function testPhp82Features(): void
{
$this->phpVersion = $this->createPhpVersion(80_200);
$this->analyseFile(__DIR__ . '/Data/Rule/php82-features.php');
}
```

### Custom PHPStan Configuration

Create `tests/Rule/Data/YourRule/config.neon`:

```neon
parameters:
customParameter: value
```

Then reference it in your test:

```php
public static function getAdditionalConfigFiles(): array
{
return array_merge(
parent::getAdditionalConfigFiles(),
[__DIR__ . '/Data/YourRule/config.neon'],
);
}
```

### Rules with Dependencies

```php
protected function getRule(): Rule
{
$dependency = self::getContainer()->getByType(SomeService::class);
return new RuleWithDependencies($dependency);
}
```

## File Organization

Recommended directory structure:

```
tests/
├── Rule/
│ ├── YourRuleTest.php
│ ├── AnotherRuleTest.php
│ └── Data/
│ ├── YourRule/
│ │ ├── code.php # Main test file
│ │ ├── edge-cases.php # Additional scenarios
│ │ └── config.neon # Optional PHPStan config
│ └── AnotherRule/
│ └── code.php
```

## Development

```bash
# Install dependencies
composer install

# Run all checks
composer check

# Individual checks
composer check:composer # Validate composer.json
composer check:ec # Check EditorConfig compliance
composer check:cs # Check coding standards (PHPCS)
composer check:types # Run PHPStan analysis
composer check:dependencies # Analyze dependencies
composer check:collisions # Check for name collisions

# Fix coding standards
composer fix:cs
```

## License

MIT License - see [LICENSE](LICENSE) file.
1 change: 1 addition & 0 deletions cache/.gitkeep
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

10 changes: 10 additions & 0 deletions composer-dependency-analyser.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php declare(strict_types = 1);

use ShipMonk\ComposerDependencyAnalyser\Config\Configuration;

$pharFile = __DIR__ . '/vendor/phpstan/phpstan/phpstan.phar';
Phar::loadPhar($pharFile, 'phpstan.phar');

require_once('phar://phpstan.phar/preload.php'); // prepends PHPStan's PharAutolaoder to composer's autoloader

return (new Configuration());
69 changes: 69 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
{
"name": "shipmonk/phpstan-dev",
"description": "Development utilities for PHPStan rules testing, extracted from shipmonk/phpstan-rules",
"license": [
"MIT"
],
"type": "library",
"keywords": [
"phpstan",
"testing",
"static analysis"
],
"require": {
"php": "^7.4 || ^8.0",
"phpstan/phpstan": "^2.1.8"
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe it works just fine even on much lower versions. Maybe even 2.*

},
"require-dev": {
"editorconfig-checker/editorconfig-checker": "^10.6.0",
"ergebnis/composer-normalize": "^2.45.0",
"phpstan/phpstan-deprecation-rules": "^2.0.1",
"phpstan/phpstan-phpunit": "^2.0.4",
"phpstan/phpstan-strict-rules": "^2.0.3",
"phpunit/phpunit": "^9.6.22",
"shipmonk/composer-dependency-analyser": "^1.8.1",
"shipmonk/dead-code-detector": "^0.9.0",
"shipmonk/name-collision-detector": "^2.1.1",
"slevomat/coding-standard": "^8.16.0"
},
"suggest": {
"phpunit/phpunit": "^9.6.22 for running tests that use RuleTestCase"
},
"autoload": {
"psr-4": {
"ShipMonk\\PHPStanDev\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"ShipMonkTests\\PHPStanDev\\": "tests/"
}
},
"config": {
"allow-plugins": {
"dealerdirect/phpcodesniffer-composer-installer": false,
"ergebnis/composer-normalize": true
},
"sort-packages": true
},
"scripts": {
"check": [
"@check:composer",
"@check:ec",
"@check:cs",
"@check:types",
"@check:dependencies",
"@check:collisions"
],
"check:collisions": "detect-collisions src",
"check:composer": [
"composer normalize --dry-run --no-check-lock --no-update-lock",
"composer validate --strict"
],
"check:cs": "phpcs",
"check:dependencies": "composer-dependency-analyser",
"check:ec": "ec src",
"check:types": "phpstan analyse -vv --ansi",
"fix:cs": "phpcbf"
}
}
Loading