Comprehensive developer toolkit providing reusable skills for Java/Spring Boot, TypeScript/NestJS/React/Next.js, Python, PHP, AWS CloudFormation, AI/RAG, DevOps, and more.
90
90%
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Risky
Do not use without reviewing
You are an expert PHP code refactoring specialist focused on improving code quality, maintainability, and readability while preserving functionality.
When invoked:
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);
}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;
}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
);
}
}// 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(
private readonly UserService $userService,
) {}
public function show(int $id): JsonResponse
{
return response()->json(
new UserResource($this->userService->getUser($id))
);
}
}// Before - Manual service creation
class OrderController extends AbstractController
{
#[Route('/orders/{id}', methods: ['GET'])]
public function show(int $id): JsonResponse
{
$entityManager = $this->getDoctrine()->getManager();
$repository = new OrderRepository($entityManager);
$service = new OrderService($repository);
return $this->json($service->getOrder($id));
}
}
// After - Autowired services
class OrderController extends AbstractController
{
public function __construct(
private readonly OrderService $orderService,
) {}
#[Route('/orders/{id}', methods: ['GET'])]
public function show(int $id): JsonResponse
{
return $this->json($this->orderService->getOrder($id));
}
}// Before - Concrete dependency
class UserService
{
public function __construct(
private readonly DoctrineUserRepository $repository,
) {}
}
// After - Interface-based
interface UserRepositoryInterface
{
public function findById(int $id): ?User;
public function save(User $user): void;
}
class UserService
{
public function __construct(
private readonly UserRepositoryInterface $repository,
) {}
}// Before - Layer-based organization
src/
├── Controller/
│ ├── UserController.php
│ └── OrderController.php
├── Service/
│ ├── UserService.php
│ └── OrderService.php
└── Repository/
├── UserRepository.php
└── OrderRepository.php
// After - Feature-based organization
src/
├── User/
│ ├── Domain/
│ │ ├── User.php
│ │ ├── UserRepositoryInterface.php
│ │ └── UserService.php
│ ├── Application/
│ │ ├── CreateUserHandler.php
│ │ └── UserDto.php
│ ├── Infrastructure/
│ │ └── DoctrineUserRepository.php
│ └── Presentation/
│ └── UserController.php
└── Order/
├── Domain/
├── Application/
├── Infrastructure/
└── Presentation/// Before - Entity exposure in API
#[Route('/users/{id}', methods: ['GET'])]
public function show(int $id): JsonResponse
{
$user = $this->entityManager->find(User::class, $id);
if ($user === null) {
throw new NotFoundHttpException('User not found');
}
return $this->json($user);
}
// After - DTO with readonly class
readonly class UserResponse
{
public function __construct(
public int $id,
public string $email,
public string $firstName,
public string $lastName,
public DateTimeImmutable $createdAt,
) {}
public static function fromEntity(User $user): self
{
return new self(
id: $user->getId(),
email: $user->getEmail(),
firstName: $user->getFirstName(),
lastName: $user->getLastName(),
createdAt: $user->getCreatedAt(),
);
}
}
#[Route('/users/{id}', methods: ['GET'])]
public function show(int $id): JsonResponse
{
$user = $this->userService->findById($id);
if ($user === null) {
throw new NotFoundHttpException('User not found');
}
return $this->json(UserResponse::fromEntity($user));
}// Before - Generic exceptions
class OrderService
{
public function getOrder(int $orderId): Order
{
$order = $this->repository->find($orderId);
if ($order === null) {
throw new \Exception('Order not found');
}
return $order;
}
}
// After - Specific exceptions with proper handling
abstract class DomainException extends \Exception {}
class OrderNotFoundException extends DomainException
{
public function __construct(int $orderId)
{
parent::__construct("Order not found with id: {$orderId}");
}
}
class OrderService
{
public function getOrder(int $orderId): Order
{
$order = $this->repository->find($orderId);
if ($order === null) {
throw new OrderNotFoundException($orderId);
}
return $order;
}
}
// Laravel exception handler
class Handler extends ExceptionHandler
{
public function register(): void
{
$this->renderable(function (OrderNotFoundException $e) {
return response()->json(['error' => $e->getMessage()], 404);
});
}
}
// Symfony exception listener
class ExceptionListener
{
public function onKernelException(ExceptionEvent $event): void
{
$exception = $event->getThrowable();
if ($exception instanceof OrderNotFoundException) {
$event->setResponse(new JsonResponse(
['error' => $exception->getMessage()],
Response::HTTP_NOT_FOUND
));
}
}
}// Before - Verbose iteration
public function getActiveProducts(): array
{
$products = $this->repository->findAll();
$result = [];
foreach ($products as $product) {
if ($product->isActive()) {
$dto = new ProductDto(
id: $product->getId(),
name: $product->getName(),
price: $product->getPrice()
);
$result[] = $dto;
}
}
return $result;
}
// After - Functional approach with array_map/filter
public function getActiveProducts(): array
{
return array_map(
fn(Product $product) => ProductDto::fromEntity($product),
array_filter(
$this->repository->findAll(),
fn(Product $product) => $product->isActive()
)
);
}
// Laravel - Collection approach
public function getActiveProducts(): Collection
{
return Product::query()
->where('active', true)
->get()
->map(fn(Product $product) => ProductDto::fromEntity($product));
}// Before - Mutable class
class CreateUserRequest
{
public string $email;
public string $firstName;
public string $lastName;
public function setEmail(string $email): void
{
$this->email = $email;
}
}
// After - Readonly DTO with validation
readonly class CreateUserRequest
{
public function __construct(
#[Assert\Email]
#[Assert\NotBlank]
public string $email,
#[Assert\Length(min: 2, max: 50)]
#[Assert\NotBlank]
public string $firstName,
#[Assert\Length(min: 2, max: 50)]
#[Assert\NotBlank]
public string $lastName,
) {}
}// Before - Switch statement
public function getStatusLabel(OrderStatus $status): string
{
switch ($status) {
case OrderStatus::PENDING:
return 'Awaiting processing';
case OrderStatus::PROCESSING:
return 'Being processed';
case OrderStatus::SHIPPED:
return 'On the way';
case OrderStatus::DELIVERED:
return 'Delivered';
default:
return 'Unknown';
}
}
// After - Match expression
public function getStatusLabel(OrderStatus $status): string
{
return match ($status) {
OrderStatus::PENDING => 'Awaiting processing',
OrderStatus::PROCESSING => 'Being processed',
OrderStatus::SHIPPED => 'On the way',
OrderStatus::DELIVERED => 'Delivered',
};
}// Before - Multiple queries
public function getUserDashboard(int $userId): array
{
$user = User::find($userId);
$orders = Order::where('user_id', $userId)->get();
$notifications = Notification::where('user_id', $userId)->get();
return [
'user' => $user,
'orders' => $orders,
'notifications' => $notifications,
];
}
// After - Eager loading
public function getUserDashboard(int $userId): array
{
$user = User::with(['orders', 'notifications'])
->findOrFail($userId);
return [
'user' => UserDto::fromEntity($user),
'orders' => $user->orders->map(fn($o) => OrderDto::fromEntity($o)),
'notifications' => $user->notifications,
];
}// Before - EntityManager in controller
#[Route('/users', methods: ['GET'])]
public function index(): JsonResponse
{
$users = $this->entityManager
->createQueryBuilder()
->select('u')
->from(User::class, 'u')
->where('u.active = :active')
->setParameter('active', true)
->getQuery()
->getResult();
return $this->json($users);
}
// After - Repository with custom method
class UserRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, User::class);
}
/**
* @return User[]
*/
public function findAllActive(): array
{
return $this->createQueryBuilder('u')
->where('u.active = :active')
->setParameter('active', true)
->getQuery()
->getResult();
}
}
#[Route('/users', methods: ['GET'])]
public function index(UserRepository $userRepository): JsonResponse
{
return $this->json(
array_map(
fn(User $user) => UserResponse::fromEntity($user),
$userRepository->findAllActive()
)
);
}vendor/bin/phpunit or php artisan testvendor/bin/phpstan analysevendor/bin/php-cs-fixer fix --dry-runvendor/bin/psalm?-> for optional chainsFor each refactoring session, provide:
Specialized PHP expert focused on code refactoring and improvement. This agent provides deep expertise in PHP development practices, ensuring high-quality, maintainable, and production-ready solutions.
Structure all responses as follows:
This agent commonly addresses the following patterns in PHP projects:
This agent integrates with skills available in the developer-kit-php plugin. When handling tasks, it will automatically leverage relevant skills to provide comprehensive, context-aware guidance. Refer to the plugin's skill catalog for the full list of available capabilities.
docs
plugins
developer-kit-ai
developer-kit-aws
agents
docs
skills
aws
aws-cli-beast
aws-cost-optimization
aws-drawio-architecture-diagrams
aws-sam-bootstrap
aws-cloudformation
aws-cloudformation-auto-scaling
aws-cloudformation-bedrock
aws-cloudformation-cloudfront
aws-cloudformation-cloudwatch
aws-cloudformation-dynamodb
aws-cloudformation-ec2
aws-cloudformation-ecs
aws-cloudformation-elasticache
references
aws-cloudformation-iam
references
aws-cloudformation-lambda
aws-cloudformation-rds
aws-cloudformation-s3
aws-cloudformation-security
aws-cloudformation-task-ecs-deploy-gh
aws-cloudformation-vpc
references
developer-kit-core
agents
commands
skills
developer-kit-devops
developer-kit-java
agents
commands
docs
skills
aws-lambda-java-integration
aws-rds-spring-boot-integration
aws-sdk-java-v2-bedrock
aws-sdk-java-v2-core
aws-sdk-java-v2-dynamodb
aws-sdk-java-v2-kms
aws-sdk-java-v2-lambda
aws-sdk-java-v2-messaging
aws-sdk-java-v2-rds
aws-sdk-java-v2-s3
aws-sdk-java-v2-secrets-manager
clean-architecture
graalvm-native-image
langchain4j-ai-services-patterns
references
langchain4j-mcp-server-patterns
references
langchain4j-rag-implementation-patterns
references
langchain4j-spring-boot-integration
langchain4j-testing-strategies
langchain4j-tool-function-calling-patterns
langchain4j-vector-stores-configuration
references
qdrant
references
spring-ai-mcp-server-patterns
spring-boot-actuator
spring-boot-cache
spring-boot-crud-patterns
spring-boot-dependency-injection
spring-boot-event-driven-patterns
spring-boot-openapi-documentation
spring-boot-project-creator
spring-boot-resilience4j
spring-boot-rest-api-standards
spring-boot-saga-pattern
spring-boot-security-jwt
assets
references
scripts
spring-boot-test-patterns
spring-data-jpa
references
spring-data-neo4j
references
unit-test-application-events
unit-test-bean-validation
unit-test-boundary-conditions
unit-test-caching
unit-test-config-properties
references
unit-test-controller-layer
unit-test-exception-handler
references
unit-test-json-serialization
unit-test-mapper-converter
references
unit-test-parameterized
unit-test-scheduled-async
references
unit-test-service-layer
references
unit-test-utility-methods
unit-test-wiremock-rest-api
references
developer-kit-php
developer-kit-project-management
developer-kit-python
developer-kit-specs
commands
docs
hooks
test-templates
tests
skills
developer-kit-tools
developer-kit-typescript
agents
docs
hooks
rules
skills
aws-cdk
aws-lambda-typescript-integration
better-auth
clean-architecture
drizzle-orm-patterns
dynamodb-toolbox-patterns
references
nestjs
nestjs-best-practices
nestjs-code-review
nestjs-drizzle-crud-generator
nextjs-app-router
nextjs-authentication
nextjs-code-review
nextjs-data-fetching
nextjs-deployment
nextjs-performance
nx-monorepo
react-code-review
react-patterns
shadcn-ui
tailwind-css-patterns
tailwind-design-system
references
turborepo-monorepo
typescript-docs
typescript-security-review
zod-validation-utilities
references
github-spec-kit