PHPackages                             lukaszzychal/phpstan-fixer - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Testing &amp; Quality](/categories/testing)
4. /
5. lukaszzychal/phpstan-fixer

ActiveLibrary[Testing &amp; Quality](/categories/testing)

lukaszzychal/phpstan-fixer
==========================

Framework-agnostic PHP library for automatically fixing PHPStan errors using static analysis

v1.2.3(6mo ago)1834[1 issues](https://github.com/lukaszzychal/phpstan-fixer/issues)1MITPHPPHP ^8.0CI passing

Since Dec 6Pushed 6mo agoCompare

[ Source](https://github.com/lukaszzychal/phpstan-fixer)[ Packagist](https://packagist.org/packages/lukaszzychal/phpstan-fixer)[ Docs](https://github.com/lukaszzychal/phpstan-fixer)[ RSS](/packages/lukaszzychal-phpstan-fixer/feed)WikiDiscussions main Synced today

READMEChangelog (3)Dependencies (5)Versions (12)Used By (1)

PHPStan Auto-Fix
================

[](#phpstan-auto-fix)

[![CI](https://github.com/lukaszzychal/phpstan-fixer/workflows/CI/badge.svg)](https://github.com/lukaszzychal/phpstan-fixer/actions)[![License: MIT](https://camo.githubusercontent.com/fdf2982b9f5d7489dcf44570e714e3a15fce6253e0cc6b5aa61a075aac2ff71b/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d79656c6c6f772e737667)](https://opensource.org/licenses/MIT)

Framework-agnostic PHP library for automatically fixing PHPStan errors using static analysis rules. Works with Laravel, Symfony, CodeIgniter, and native PHP projects.

Features
--------

[](#features)

- Automatically detects and fixes common PHPStan errors
- Framework-agnostic (works with any PHP project)
- Offline-friendly (no AI or network access required)
- Suggest mode (preview changes) and Apply mode (write changes)
- Supports multiple fix strategies for different error types
- **Configuration system** - Control how each error type is handled (fix, ignore, or report)

Installation
------------

[](#installation)

```
composer require --dev lukaszzychal/phpstan-fixer
```

Usage
-----

[](#usage)

### Basic Usage (Default - Suggest Mode)

[](#basic-usage-default---suggest-mode)

By default, the tool runs in `suggest` mode - it shows what would be changed without modifying files:

```
vendor/bin/phpstan-fixer
```

This is equivalent to:

```
vendor/bin/phpstan-fixer --mode=suggest
```

### Suggest Mode (Preview Changes)

[](#suggest-mode-preview-changes)

Preview proposed fixes without modifying files (same as default):

```
vendor/bin/phpstan-fixer --mode=suggest
```

**Note:** Suggest mode is safe to run - it only shows what would be changed and does NOT modify your files.

### Apply Mode (Write Changes)

[](#apply-mode-write-changes)

Apply fixes directly to files:

```
vendor/bin/phpstan-fixer --mode=apply
```

**Warning:** Apply mode will modify your source files. Always review changes in suggest mode first!

### Using Existing PHPStan JSON Output

[](#using-existing-phpstan-json-output)

If you already have a PHPStan JSON output file:

```
vendor/bin/phpstan-fixer --input=phpstan-output.json --mode=apply
```

### Custom PHPStan Command

[](#custom-phpstan-command)

Specify a custom PHPStan command:

```
vendor/bin/phpstan-fixer --phpstan-command="vendor/bin/phpstan analyse src tests --level=5 --error-format=json" --mode=apply
```

### Configuration File

[](#configuration-file)

You can configure how different error types are handled using a configuration file. Create `phpstan-fixer.yaml` or `phpstan-fixer.json` in your project root:

**YAML Format** (`phpstan-fixer.yaml`):

```
rules:
  "Access to an undefined property":
    action: "fix"  # fix, ignore, or report

  "Method has no return type":
    action: "fix"

  "Unknown class":
    action: "ignore"  # Don't fix and don't show

  "Extra arguments":
    action: "report"  # Don't fix, but show in output

  # Wildcard patterns
  "Call to an undefined method *":
    action: "fix"

  # Regex patterns
  "/.*magic.*/":
    action: "report"

default:
  action: "fix"  # Default action for unmatched errors
```

**JSON Format** (`phpstan-fixer.json`):

```
{
  "rules": {
    "Access to an undefined property": {
      "action": "fix"
    },
    "Method has no return type": {
      "action": "fix"
    },
    "Unknown class": {
      "action": "ignore"
    },
    "Extra arguments": {
      "action": "report"
    }
  },
  "default": {
    "action": "fix"
  }
}
```

**Configuration Actions:**

- **`fix`** (default) - Attempt to automatically fix the error
- **`ignore`** - Don't fix and don't display the error (silent ignore)
- **`report`** - Don't fix, but display in original PHPStan format

Validation: configuration is validated on load. Invalid actions (anything other than `fix`, `ignore`, `report`) or malformed rule entries will stop execution with a clear error message.

**Using Configuration:**

```
# Auto-discover configuration file
vendor/bin/phpstan-fixer

# Specify configuration file explicitly
vendor/bin/phpstan-fixer --config=phpstan-fixer.yaml
```

**Pattern Matching:**

- **Exact match**: `"Access to an undefined property"` - matches exactly
- **Wildcard**: `"Access to an undefined *"` - matches with `*` as wildcard
- **Regex**: `"/Access to an undefined \\w+/"` - full PCRE regex pattern

**YAML Support:**

For YAML configuration files, you need either:

- `ext-yaml` PHP extension (install via `pecl install yaml`), or
- `symfony/yaml` package (add to `composer.json`)

Supported Fix Strategies
------------------------

[](#supported-fix-strategies)

> 📖 **Detailed Guide**: See [PHPStan Fixers Guide](docs/PHPSTAN_FIXERS_GUIDE.md) for comprehensive documentation on each fixer, including problem descriptions, examples, and usage scenarios.

The library automatically fixes the following types of PHPStan errors:

1. **Missing Return Type** (`MissingReturnDocblockFixer`)

    - Adds `@return` annotations when return type is missing
2. **Missing Parameter Type** (`MissingParamDocblockFixer`)

    - Adds `@param` annotations for parameters without types
3. **Undefined Properties** (`MissingPropertyDocblockFixer`)

    - Adds `@property` or `@var` annotations for undefined properties
4. **Eloquent Pivot Property** (`UndefinedPivotPropertyFixer`)

    - Adds `@property-read` annotation for Laravel Eloquent `$pivot` property
5. **Collection Generics** (`CollectionGenericDocblockFixer`)

    - Adds generic type parameters to Collection types (e.g., `Collection`)
6. **Undefined Variables** (`UndefinedVariableFixer`)

    - Adds inline `@var` annotations for undefined variables
7. **Missing Use Statements** (`MissingUseStatementFixer`)

    - Adds `use` statements for undefined classes
8. **Undefined Methods** (`UndefinedMethodFixer`)

    - Adds `@method` annotations for magic methods
9. **Missing Throws Annotation** (`MissingThrowsDocblockFixer`)

    - Adds `@throws` annotations when exceptions are thrown
10. **Callable Type Invocation** (`CallableTypeFixer`)

    - Adds `@param-immediately-invoked-callable` or `@param-later-invoked-callable` annotations
11. **Mixin Annotation** (`MixinFixer`)

    - Adds `@mixin ClassName` annotation for classes using magic methods (`__call`, `__get`, `__set`) to delegate calls

Examples
--------

[](#examples)

### Example 1: Missing Return Type

[](#example-1-missing-return-type)

**Before:**

```
function calculateSum($a, $b) {
    return $a + $b;
}
```

**After:**

```
/**
 * @return mixed
 */
function calculateSum($a, $b) {
    return $a + $b;
}
```

### Example 2: Undefined Property

[](#example-2-undefined-property)

**Before:**

```
class User {
    public function getName() {
        return $this->name; // PHPStan error: undefined property
    }
}
```

**After:**

```
/**
 * @property string $name
 */
class User {
    public function getName() {
        return $this->name;
    }
}
```

### Example 3: Collection Generics

[](#example-3-collection-generics)

**Before:**

```
/**
 * @return Collection
 */
function getItems() {
    return collect([]);
}
```

**After:**

```
/**
 * @return Collection
 */
function getItems() {
    return collect([]);
}
```

Configuration
-------------

[](#configuration)

The tool works out of the box with default settings. All fix strategies are enabled by default.

How It Works
------------

[](#how-it-works)

1. Runs PHPStan (or reads existing JSON output)
2. Parses PHPStan JSON output into structured Issue objects
3. Matches each issue to appropriate fix strategies
4. Applies fixes using AST parsing and PHPDoc manipulation
5. Shows preview (suggest mode) or writes changes (apply mode)

Requirements
------------

[](#requirements)

- PHP 8.0 or higher
- PHPStan (installed via Composer)
- nikic/php-parser (automatically installed)

Troubleshooting
---------------

[](#troubleshooting)

### Framework Compatibility Notice

[](#framework-compatibility-notice)

**⚠️ Important:** This package is **framework-agnostic** and is not officially tested or supported with specific frameworks like Laravel, Symfony, etc.

- **Laravel:** Not officially supported. Use with caution. See Laravel-specific issues below.
- **Other frameworks (Symfony, CodeIgniter, CakePHP, etc.):** Use with caution. Framework-specific features may not work as expected.

If you encounter framework-specific issues, please report them via [GitHub Issues](https://github.com/lukaszzychal/phpstan-fixer/issues).

### Laravel package:discover Error

[](#laravel-packagediscover-error)

**Problem:** Error `Call to a member function make() on null` occurs during `package:discover` in Laravel.

**Solution:** In version v1.2.2+, the package has correctly configured `dont-discover` as an array in `composer.json`:

```
{
  "extra": {
    "laravel": {
      "dont-discover": []
    }
  }
}
```

This should prevent Laravel from auto-discovering the package during `package:discover`.

**If the problem persists:**

If you still encounter the error, it may be related to how Laravel initializes the container during `package:discover`. In that case, you can use a workaround:

1. **Ensure you're using v1.2.2+**:

    ```
    composer require --dev lukaszzychal/phpstan-fixer:^1.2.2
    ```
2. **Check the package's `composer.json`** in `vendor/lukaszzychal/phpstan-fixer/composer.json`:

    - Should be: `"dont-discover": []` (array)
    - Should NOT be: `"dont-discover": true` (boolean)

**Related Issues:**

- [Issue #60](https://github.com/lukaszzychal/phpstan-fixer/issues/60) - Original bug report
- [Issue #63](https://github.com/lukaszzychal/phpstan-fixer/issues/63) - Fix (boolean → array)

Development
-----------

[](#development)

### Running Tests

[](#running-tests)

```
vendor/bin/phpunit
```

### CI/CD

[](#cicd)

The project uses GitHub Actions for continuous integration:

- **CI Workflow**: Runs tests on PHP 8.0-8.3, static analysis, and code style checks
- **Release Workflow**: Automatically creates GitHub releases on version tags
- **Self-Test Workflow**: Tests PHPStan Fixer on its own codebase

See [`.github/workflows/`](.github/workflows/) for details.

### Compatibility Testing

[](#compatibility-testing)

This package uses [PHP Compatibility Tester](https://github.com/lukaszzychal/php-compatibility-tester) to ensure compatibility across different frameworks and PHP versions:

- **Packagist**: [lukaszzychal/php-compatibility-tester](https://packagist.org/packages/lukaszzychal/php-compatibility-tester)
- **GitHub**: [lukaszzychal/php-compatibility-tester](https://github.com/lukaszzychal/php-compatibility-tester)

Compatibility tests run automatically:

- **Monthly**: On the 1st day of each month via GitHub Actions
- **Manually**: Trigger via GitHub Actions UI (workflow\_dispatch)
- **Locally**: Run `vendor/bin/compatibility-tester test` to test locally

This automatically tests `phpstan-fixer` against various frameworks (Laravel 11/12, Symfony 7/8, CodeIgniter 4/5) and PHP versions (8.1-8.4) to ensure it works correctly in different environments. Test reports are available as GitHub Actions artifacts.

#### Initializing Compatibility Testing

[](#initializing-compatibility-testing)

To set up compatibility testing in your project:

1. **Run the init command**:

    ```
    vendor/bin/compatibility-tester init
    ```
2. **The command will**:

    - Create `.compatibility.yml` configuration file
    - Copy PHPUnit test templates to `tests/compatibility/`
    - Copy GitHub Actions workflow to `.github/workflows/compatibility-tests.yml`
    - Copy test scripts to `scripts/`
3. **Edit `.compatibility.yml`** to configure:

    - Your package name
    - PHP versions to test
    - Frameworks and versions
    - Test scripts to run

**Note**: If the example configuration file is not found in the package, you can use the example from `vendor/lukaszzychal/php-compatibility-tester/tests/fixtures/test-package/.compatibility.yml` as a reference.

### Contributing

[](#contributing)

Contributions are welcome! Please feel free to submit a Pull Request.

FAQ
---

[](#faq)

### What's the difference between the execution modes?

[](#whats-the-difference-between-the-execution-modes)

There are three ways to run the tool:

1. **`vendor/bin/phpstan-fixer`** (default, no parameters)

    - Equivalent to `--mode=suggest`
    - Shows what would be changed
    - Does NOT modify files
    - Safe to run - preview only
2. **`vendor/bin/phpstan-fixer --mode=suggest`**

    - Explicit suggest mode (same as default)
    - Shows proposed changes
    - Does NOT modify files
    - Safe to run - preview only
3. **`vendor/bin/phpstan-fixer --mode=apply`**

    - Actually writes changes to files
    - Modifies source code
    - Use with caution - creates permanent changes

**Recommendation:** Always run with `--mode=suggest` first to preview changes before applying them.

### What happens to errors that can't be fixed?

[](#what-happens-to-errors-that-cant-be-fixed)

If a fixer strategy cannot automatically fix an error, it will be displayed at the end of the output in PHPStan format. These are errors that require manual intervention or are not yet supported by any fixer strategy.

License
-------

[](#license)

MIT License - see LICENSE file for details.

Author
------

[](#author)

**Łukasz Zychal**

- Email:
- GitHub Issues: [Report issues and bugs](https://github.com/lukaszzychal/phpstan-fixer/issues)
- Discussions: [Join the discussion](https://github.com/lukaszzychal/phpstan-fixer/discussions)

Contributing
------------

[](#contributing-1)

Contributions are welcome! Please feel free to submit a Pull Request.

For bug reports and feature requests, please use the [GitHub Issues](https://github.com/lukaszzychal/phpstan-fixer/issues) page.

###  Health Score

33

—

LowBetter than 72% of packages

Maintenance46

Moderate activity, may be stable

Popularity20

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity47

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 98.5% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~1 days

Total

9

Last Release

201d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/ee8c63c432f2a2f711c623a12eb524149d97de33a0d5c63f0c48b1151c358e0b?d=identicon)[Lukasz Zychal](/maintainers/Lukasz%20Zychal)

---

Top Contributors

[![lukaszzychal](https://avatars.githubusercontent.com/u/9255872?v=4)](https://github.com/lukaszzychal "lukaszzychal (67 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (1 commits)")

---

Tags

phpphpdocPHPStanstatic analysisautomationcode qualitycode-fixer

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/lukaszzychal-phpstan-fixer/health.svg)

```
[![Health](https://phpackages.com/badges/lukaszzychal-phpstan-fixer/health.svg)](https://phpackages.com/packages/lukaszzychal-phpstan-fixer)
```

###  Alternatives

[vimeo/psalm

A static analysis tool for finding errors in PHP applications

5.9k82.2M7.7k](/packages/vimeo-psalm)[behat/behat

Scenario-oriented BDD framework for PHP

4.0k101.8M2.2k](/packages/behat-behat)[phan/phan

A static analyzer for PHP

5.6k11.9M1.2k](/packages/phan-phan)[laraveldaily/filacheck

Static analysis for Filament projects - detect deprecated patterns and code issues

11975.6k](/packages/laraveldaily-filacheck)[psalm/plugin-laravel

Psalm plugin for Laravel

3355.3M346](/packages/psalm-plugin-laravel)[phparkitect/phparkitect

Enforce architectural constraints in your PHP applications

9224.3M28](/packages/phparkitect-phparkitect)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
