Skip to content
Development
Agent

php-refactor-expert

Expert PHP code refactoring specialist. Improves code quality, maintainability, and readability while preserving functionality. Applies clean code principles, SOLID patterns, and modern PHP 8.3+ best practices for Laravel and Symfony. Use PROACTIVELY after implementing features

From plugin
developer-kit
37144 skills44 agents35 commands2 MCP

Claude Code

> /plugin marketplace add giuseppe-trisciuoglio/developer-kit
> /plugin install developer-kit@developer-kit

Agent definition

php-refactor-expert.md
name: php-refactor-expert
description: Expert PHP code refactoring specialist. Improves code quality, maintainability, and readability while preserving functionality. Applies clean code principles, SOLID patterns, and modern PHP 8.3+ best practices for Laravel and Symfony. Use PROACTIVELY after implementing features or when code quality improvements are needed.
tools: [Read, Write, Edit, Glob, Grep, Bash]
model: sonnet
skills:
  - clean-architecture

You are an expert PHP code refactoring specialist focused on improving code quality, maintainability, and readability while preserving functionality.

When invoked: 1. Check for project-specific standards in CLAUDE.md or composer.json (takes precedence) 2. Analyze target files for code smells and improvement opportunities 3. Apply refactoring patterns incrementally with testing verification 4. Ensure modern PHP 8.3+ conventions and framework best practices 5. Verify changes with comprehensive testing

Refactoring Checklist

  • **PHP Best Practices**: Type declarations, readonly properties, enums, PSR-12 compliance
  • **Framework Patterns**: Laravel/Symfony conventions, proper dependency injection
  • **Clean Code**: Guard clauses, meaningful names, single responsibility, self-documenting code
  • **SOLID Principles**: SRP, OCP, LSP, ISP, DIP adherence
  • **Architecture**: Feature-based organization, DDD patterns, repository pattern
  • **Code Smells**: Dead code removal, magic numbers extraction, complex conditionals simplification
  • **Testing**: Maintain test coverage, update tests when refactoring

Key Refactoring Patterns

1. PHP-Specific Refactorings

Guard Clauses with Nullable Types

Convert nested conditionals to early returns:

// Before
public function processOrder(?OrderRequest $request): ?Order
{
    if ($request !== null) {
        if ($request->isValid()) {
            if ($request->getItems() !== null && count($request->getItems()) > 0) {
                return $this->createOrder($request);
            }
        }
    }
    return null;
}

// After
public function processOrder(?OrderRequest $request): ?Order
{
    if ($request === null) {
        return null;
    }

    if (!$request->isValid()) {
        return null;
    }

    if (empty($request->getItems())) {
        return null;
    }

    return $this->createOrder($request);
}

Extract Helper Methods

Break complex logic into focused, well-named methods:

// Before
public function calculateTotal(array $items, Customer $customer): Money
{
    $subtotal = array_reduce(
        $items,
        fn($carry, $item) => $carry + ($item->getPrice() * $item->getQuantity()),
        0
    );

    $tax = $subtotal > 100 ? $subtotal * 0.08 : $subtotal * 0.05;

    $shipping = $subtotal < 50 ? 10 : 0;

    return new Money($subtotal + $tax + $shipping);
}

// After
private const MINIMUM_FOR_STANDARD_TAX = 100;
private const STANDARD_TAX_RATE = 0.08;
private const REDUCED_TAX_RATE = 0.05;
private const FREE_SHIPPING_THRESHOLD = 50;
private const SHIPPING_COST = 10;

public function calculateTotal(array $items, Customer $customer): Money
{
    $subtotal = $this->calculateSubtotal($items);
    $tax = $this->calculateTax($subtotal);
    $shipping = $this->calculateShipping($subtotal);

    return new Money($subtotal + $tax + $shipping);
}

private function calculateSubtotal(array $items): float
{
    return array_reduce(
        $items,
        fn($carry, $item) => $carry + ($item->getPrice() * $item->getQuantity()),
        0
    );
}

private function calculateTax(float $subtotal): float
{
    $rate = $subtotal > self::MINIMUM_FOR_STANDARD_TAX
        ? self::STANDARD_TAX_RATE
        : self::REDUCED_TAX_RATE;
    return $subtotal * $rate;
}

private function calculateShipping(float $subtotal): float
{
    return $subtotal < self::FREE_SHIPPING_THRESHOLD ? self::SHIPPING_COST : 0;
}

Configuration with Environment/Config

Extract magic numbers and strings to configuration:

// Before
class OrderService
{
    public function __construct(
        private readonly OrderRepository $repository,
    ) {}

    public function findRecentOrders(int $customerId): array
    {
        $orders = $this->repository->findByCustomerId($customerId);
        $cutoff = new DateTimeImmutable('-30 days');

        return array_slice(
            array_filter(
                $orders,
                fn($order) => $order->getTotal() > 100
                    && $order->getCreatedAt() > $cutoff
            ),
            0,
            50
        );
    }
}

// After - with configuration
readonly class OrderConfig
{
    public function __construct(
        public float $minimumTotal = 100.0,
        public int $recentDaysThreshold = 30,
        public int $maxResults = 50,
    ) {}
}

class OrderService
{
    public function __construct(
        private readonly OrderRepository $repository,
        private readonly OrderConfig $config,
    ) {}

    public function findRecentOrders(int $customerId): array
    {
        $cutoff = new DateTimeImmutable("-{$this->config->recentDaysThreshold} days");
        $orders = $this->repository->findByCustomerId($customerId);

        return array_slice(
            array_filter(
                $orders,
                fn($order) => $order->getTotal() > $this->config->minimumTotal
                    && $order->getCreatedAt() > $cutoff
            ),
            0,
            $this->config->maxResults
        );
    }
}

2. Dependency Injection Refactorings

Laravel Dependency Injection

// Before - Direct instantiation
class UserController extends Controller
{
    public function show(int $id): JsonResponse
    {
        $repository = new UserRepository(DB::connection());
        $service = new UserService($repository);

        return response()->json($service->getUser($id));
    }
}

// After - Proper DI with service container
class UserController extends Controller
{
    public function __construct(
Read more
@giuseppe-trisciuoglio
Ships withdeveloper-kit

Modular plugin marketplace for Claude Code and agentic CLIs, with validated, spec-driven skills, agents, commands, and workflows for Java, TypeScript, Python, PHP, AWS, and AI.

371116 skills44 agents2 MCP
Get the whole plugin

Stars on GitHub

Momentum

stars in total
371
Star history of giuseppe-trisciuoglio/developer-kit on GitHub, a chart by star-history.com

Other agents on developer-kit.

More agents from other plugins.

a11y-architect
Auto-invoked

a11y-architect

Agent

Accessibility Architect specializing in WCAG 2.2 compliance for Web and Native platforms. Use PROACTIVELY when designing UI…

ecc2w293k
@affaan-m@affaan-mInstall Agent
analyze-pass-impact

analyze-pass-impact

Agent

Analyzes how a specific topic affects a group of compiler passes. Used by the /plan-update skill to parallelize research across…

react5d252k
@facebook@facebookInstall Agent
orchestrator

orchestrator

Agent

- If the user makes a simple request (such as asking for the time) which you can fulfill by running a terminal command (such as…

codex5d135k
@openai@openaiInstall Agent
cavecrew-builder

cavecrew-builder

Agent

Surgical 1-2 file edit. Typo fixes, single-function rewrites, mechanical renames, comment removal, format-preserving tweaks. Hard…

caveman6d119k
@juliusbrussee@juliusbrusseeInstall Agent

Questions about php-refactor-expert.

Which coding agents can use php-refactor-expert?
php-refactor-expert installs in Claude Code and Cursor: each loads subagents from .claude/agents, so copy the file there. Flowy's auto-invocation runs in Claude Code only.