PHP code example of kenaths / phpstan-fixer

1. Go to this page and download the library: Download kenaths/phpstan-fixer library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

kenaths / phpstan-fixer example snippets


use PHPStanFixer\PHPStanFixer;

$fixer = new PHPStanFixer();
$result = $fixer->fix(['src/', 'tests/'], 5);

echo "Fixed: " . $result->getFixedCount() . " errors\n";
echo "Unfixable: " . $result->getUnfixableCount() . " errors\n";

foreach ($result->getFixedErrors() as $error) {
    echo "Fixed: {$error->getFile()}:{$error->getLine()} - {$error->getMessage()}\n";
}

use PHPStanFixer\Fixers\AbstractFixer;
use PHPStanFixer\ValueObjects\Error;

class MyCustomFixer extends AbstractFixer
{
    public function getSupportedTypes(): array
    {
        return ['my_error_type'];
    }

    public function canFix(Error $error): bool
    {
        return strpos($error->getMessage(), 'My specific error') !== false;
    }

    public function fix(string $content, Error $error): string
    {
        // Implement your fix logic here
        // Use PHP-Parser to modify the AST
        $stmts = $this->parseCode($content);

        // Modify the AST...

        return $this->printCode($stmts);
    }
}

// Register the fixer
$fixer = new PHPStanFixer();
$fixer->registerFixer(new MyCustomFixer());

class UserService
{
    private $repository;

    public function findUser($id)
    {
        if ($id == null) {
            return null;
        }

        $unused = "This will be removed";

        return $this->repository->find($id);
    }
}

class UserService
{
    private mixed $repository;

    public function findUser(mixed $id): ?object
    {
        if ($id === null) {
            return null;
        }

        return $this->repository->find($id);
    }
}

// Before
class Product
{
    private string $name;
    private float $price;

    public function __construct(string $name, float $price)
    {
        $this->name = $name;
        $this->price = $price;
    }
}

// After (with constructor promotion)
class Product
{
    public function __construct(
        private string $name,
        private float $price
    ) {
    }
}
bash
vendor/bin/phpstan-fix src/Models/User.php --level=8