check-method-length
Analyzes PHP code to identify methods that are too long or violate single responsibility principles.
Install
mkdir -p .claude/skills/check-method-length && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/19418" && unzip -o skill.zip -d .claude/skills/check-method-length && rm skill.zipInstalls to .claude/skills/check-method-length
Activation
This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.
Analyzes PHP code for method length issues. Detects methods exceeding 30 lines, single responsibility violations, extract method opportunities.Key capabilities
- →Detect PHP methods exceeding 30 lines
- →Identify single responsibility principle violations
- →Suggest extract method refactoring opportunities
- →Classify method complexity by line count
- →Provide refactoring patterns for long parameter lists
How it works
The tool analyzes PHP method bodies by counting logical lines, excluding comments and blank lines, to identify methods that exceed defined thresholds. It then suggests specific refactoring techniques like extracting methods or introducing parameter objects to improve code organization.
Inputs & outputs
When to use check-method-length
- →Identify methods longer than 30 lines
- →Detect single responsibility principle violations
- →Refactor long methods into smaller functions
- →Evaluate code maintainability in legacy PHP projects
About this skill
Method Length Check
Analyze PHP code for method length and complexity issues.
Detection Thresholds
| Lines | Classification |
|---|---|
| 1-15 | ✅ Ideal |
| 16-30 | ⚠️ Acceptable |
| 31-50 | 🟡 Long - consider splitting |
| 51+ | 🟠 Too long - must split |
Detection Patterns
1. Methods Over 30 Lines
// TOO LONG: 50+ lines doing multiple things
public function processOrder(Order $order): void
{
// Validate order (10 lines)
if ($order->getItems()->isEmpty()) {
throw new InvalidOrderException('Empty order');
}
// ... more validation
// Calculate totals (15 lines)
$subtotal = 0;
foreach ($order->getItems() as $item) {
$subtotal += $item->getPrice() * $item->getQuantity();
}
// ... more calculations
// Apply discounts (10 lines)
$discount = $this->calculateDiscount($order);
// ... discount logic
// Process payment (10 lines)
$payment = $this->paymentGateway->charge($total);
// ... payment logic
// Send notifications (10 lines)
$this->mailer->send($order->getCustomer(), 'order_confirmation');
// ... notification logic
}
// GOOD: Split into focused methods
public function processOrder(Order $order): void
{
$this->validateOrder($order);
$totals = $this->calculateTotals($order);
$this->processPayment($order, $totals);
$this->sendNotifications($order);
}
private function validateOrder(Order $order): void
{
// 10 lines of validation
}
private function calculateTotals(Order $order): OrderTotals
{
// 15 lines of calculation
}
2. Single Responsibility Violations
// BAD: Method does too many things
public function createUser(array $data): User
{
// 1. Validate input
// 2. Hash password
// 3. Create user entity
// 4. Save to database
// 5. Send welcome email
// 6. Create activity log
// 7. Update statistics
}
// GOOD: Each method has one responsibility
public function createUser(array $data): User
{
$validatedData = $this->validateUserData($data);
$user = $this->buildUserEntity($validatedData);
$this->userRepository->save($user);
$this->eventDispatcher->dispatch(new UserCreatedEvent($user));
return $user;
}
3. Extract Method Opportunities
// BEFORE: Long conditional blocks
public function calculatePrice(Product $product, User $user): Money
{
$basePrice = $product->getPrice();
// Complex discount calculation (15 lines)
$discount = 0;
if ($user->isPremium()) {
$discount += 10;
}
if ($user->getOrderCount() > 10) {
$discount += 5;
}
if ($product->isOnSale()) {
$discount += $product->getSaleDiscount();
}
if ($this->isHolidaySeason()) {
$discount += 15;
}
$discount = min($discount, 50);
// ...
// Tax calculation (10 lines)
$taxRate = $this->getTaxRate($user->getCountry());
// ...
return $finalPrice;
}
// AFTER: Extracted methods
public function calculatePrice(Product $product, User $user): Money
{
$basePrice = $product->getPrice();
$discount = $this->calculateDiscount($product, $user);
$priceAfterDiscount = $basePrice->subtract($discount);
$tax = $this->calculateTax($priceAfterDiscount, $user);
return $priceAfterDiscount->add($tax);
}
private function calculateDiscount(Product $product, User $user): Money
{
// Focused discount logic
}
private function calculateTax(Money $price, User $user): Money
{
// Focused tax logic
}
4. Long Parameter Lists
// BAD: Too many parameters (indicates method does too much)
public function createReport(
string $title,
DateTime $startDate,
DateTime $endDate,
array $filters,
string $format,
bool $includeCharts,
bool $includeComments,
string $outputPath
): Report {}
// GOOD: Parameter object
public function createReport(ReportRequest $request): Report
{
// Method focuses on orchestration
}
final readonly class ReportRequest
{
public function __construct(
public string $title,
public DateRange $dateRange,
public array $filters,
public ReportFormat $format,
public ReportOptions $options,
) {}
}
Counting Rules
- Count logical lines, not physical lines
- Exclude blank lines and comments from count
- Include all lines in method body (opening/closing braces not counted)
- One statement per line
Refactoring Techniques
Extract Method
// Before
$validated = [];
foreach ($items as $item) {
if ($item->isValid() && $item->isInStock()) {
$validated[] = $item;
}
}
// After
$validated = $this->filterValidItems($items);
private function filterValidItems(array $items): array
{
return array_filter($items, fn($item) => $item->isValid() && $item->isInStock());
}
Introduce Parameter Object
// Before
function search($query, $page, $limit, $sort, $order, $filters) {}
// After
function search(SearchCriteria $criteria) {}
Replace Method with Method Object
// Before: Complex method with many local variables
public function calculate(): int
{
$a = ...;
$b = ...;
$c = ...;
// 50 lines using a, b, c
}
// After: Separate class
class PriceCalculator
{
private int $a;
private int $b;
private int $c;
public function calculate(): int
{
$this->initializeValues();
return $this->computeResult();
}
}
Grep Patterns
# Find method signatures
Grep: "function\s+\w+\s*\(" --glob "**/*.php"
# Count lines between method start and end (manual analysis needed)
Severity Classification
| Lines | Severity |
|---|---|
| 31-50 | 🟡 Minor |
| 51-80 | 🟠 Major |
| 81+ | 🔴 Critical |
Output Format
### Method Length: [MethodName] is too long
**Severity:** 🟠/🟡
**Location:** `file.php:line`
**Lines:** 65
**Issue:**
Method `processOrder` is 65 lines long (recommended: ≤30).
**Responsibilities Found:**
1. Order validation (lines 5-20)
2. Price calculation (lines 22-45)
3. Payment processing (lines 47-60)
4. Notification sending (lines 62-70)
**Suggested Refactoring:**
```php
public function processOrder(Order $order): void
{
$this->validateOrder($order);
$totals = $this->calculateTotals($order);
$this->processPayment($order, $totals);
$this->sendNotifications($order);
}
## When This Is Acceptable
- **CLI commands/migrations** — Long methods in console commands or database migrations are often unavoidable due to sequential operations
- **Test setup methods** — `setUp()` methods with extensive fixture creation may legitimately be long
- **Configuration methods** — Methods that configure framework services/routes often need many lines
### False Positive Indicators
- Method is in a `Command` or `Migration` class
- Method name starts with `setUp` or `configure`
- Method body is mostly configuration/declaration, not logic
When not to use it
- →CLI commands or database migrations
- →Test setup methods like setUp()
- →Configuration methods for framework services
Limitations
- →Requires manual analysis for counting lines between method start and end
- →Does not count opening or closing braces in line totals
How it compares
Unlike manual code review, this tool provides automated severity classification and specific refactoring code snippets based on established line-count thresholds.
Compared to similar skills
check-method-length side by side with the closest alternatives in the catalog.
| Skill | Installs | Updated | Safety | Difficulty |
|---|---|---|---|---|
| check-method-length (this skill) | 0 | 5mo | Review | Intermediate |
| php-best-practices | 15 | 13d | No flags | Beginner |
| php-pro | 13 | 3mo | No flags | Intermediate |
| php-guidelines-from-spatie | 6 | 5mo | No flags | Beginner |
Try saying
Example prompts that trigger this skill in your AI assistant.
More by dykyi-roman
View all by dykyi-roman →You might also like
php-best-practices
HoangNguyen0403
PHP best practices, PSR standards, and code quality guidelines.
php-pro
sickn33
Write idiomatic PHP code with generators, iterators, SPL data structures, and modern OOP features. Use PROACTIVELY for high-performance PHP applications.
php-guidelines-from-spatie
freekmurze
Describes PHP and Laravel guidelines provided by Spatie. These rules result in more maintainable, and readable code.
code-refactor-php-mediawiki
SemanticMediaWiki
>
laravel-best-practices
binotaliu
Apply this skill whenever writing, reviewing, or refactoring Laravel PHP code. This includes creating or modifying controllers, models, migrations, form requests, policies, jobs, scheduled commands, service classes, and Eloquent queries. Triggers for N+1 and query performance issues, caching strateg
woocommerce-code-review
woocommerce
Review WooCommerce code changes for coding standards compliance. Use when reviewing code locally, performing automated PR reviews, or checking code quality.