check-nesting-depth

Analyze nesting depth issues in PHP code. Detect deep nesting beyond 3 levels, complex conditional statements, and cases that can be simplified with early returns.

Last repository push
GitHub Stars
109
Forks
26
Issues / PRs
1

Installation

Review the source and dependencies with a prompt. A package is available to download.

Install with an AI assistant

Copy the prompt so your assistant can review the pinned revision and dependencies first.

View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "check-nesting-depth" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-366572ff1fd18ca7d8f8fb97df1983f4fe49f2bbcf149af88eca9ad6b667c313. Verify the upstream source and version against https://github.com/dykyi-roman/awesome-claude-code before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.

Source and setup

github.com

Setup guidance pending

See the original source for supported tools, dependencies, and permissions.

Installation test pending

Analyze nesting depth issues in PHP code. Detect deep nesting beyond 3 levels, complex conditional statements, and cases that can be simplified with early returns.

0 Downloads

Introduction source: third_party · dykyi-roman · 0.0.1 Reference

SkillPi interpretation

Tasks
Analyzes PHP code for nesting depth issues. Detects deep nesting over 3 levels, complex conditionals, early return opportunities.
Inputs and outputs
```markdown
Testing
Not tested

Browse files

Browse files at the source ↗

Original SKILL.md

Open original ↗
Frontmatter
name: check-nesting-depth
description: Analyzes PHP code for nesting depth issues. Detects deep nesting over 3 levels, complex conditionals, early return opportunities.

Nesting Depth Check

Analyze PHP code for excessive nesting depth and complexity.

Detection Thresholds

Depth Classification
1-2 ✅ Ideal
3 ⚠️ Acceptable
4 🟡 Deep - refactor recommended
5+ 🟠 Too deep - must refactor

Detection Patterns

1. Deep Nesting

// DEPTH 5: Arrow code / pyramid of doom
public function process(Request $request): Response
{
    if ($request->isValid()) {                           // 1
        if ($user = $request->getUser()) {               // 2
            if ($user->hasPermission('edit')) {          // 3
                foreach ($request->getItems() as $item) { // 4
                    if ($item->isActive()) {              // 5
                        $this->handle($item);
                    }
                }
            }
        }
    }
}

// DEPTH 2: Using early returns
public function process(Request $request): Response
{
    if (!$request->isValid()) {
        return $this->badRequest();
    }

    $user = $request->getUser();
    if (!$user) {
        return $this->unauthorized();
    }

    if (!$user->hasPermission('edit')) {
        return $this->forbidden();
    }

    $activeItems = array_filter(
        $request->getItems(),
        fn($item) => $item->isActive()
    );

    foreach ($activeItems as $item) {
        $this->handle($item);
    }
}

2. Complex Conditionals

// COMPLEX: Multiple nested conditions
if ($order->isPaid()) {
    if ($order->isShipped()) {
        if ($order->isDelivered()) {
            if (!$order->isReturned()) {
                $this->complete($order);
            }
        }
    }
}

// SIMPLIFIED: Combined condition
if ($order->canBeCompleted()) {
    $this->complete($order);
}

// Or with early return
if (!$order->isPaid()) return;
if (!$order->isShipped()) return;
if (!$order->isDelivered()) return;
if ($order->isReturned()) return;

$this->complete($order);

3. Nested Loops

// DEEP: Triple nested loop
foreach ($categories as $category) {
    foreach ($category->getProducts() as $product) {
        foreach ($product->getVariants() as $variant) {
            foreach ($variant->getOptions() as $option) {
                $this->process($option);
            }
        }
    }
}

// BETTER: Extract methods
foreach ($categories as $category) {
    $this->processCategory($category);
}

private function processCategory(Category $category): void
{
    foreach ($category->getProducts() as $product) {
        $this->processProduct($product);
    }
}

private function processProduct(Product $product): void
{
    foreach ($product->getVariants() as $variant) {
        $this->processVariant($variant);
    }
}

4. Callback Nesting (Callback Hell)

// DEEP: Nested callbacks
$this->service->fetch($id, function($result) {
    $this->processor->process($result, function($processed) {
        $this->sender->send($processed, function($sent) {
            $this->logger->log($sent, function($logged) {
                $this->cleanup($logged);
            });
        });
    });
});

// FLAT: Sequential or promise-based
$result = $this->service->fetch($id);
$processed = $this->processor->process($result);
$sent = $this->sender->send($processed);
$this->logger->log($sent);
$this->cleanup($sent);

5. Switch in If in Loop

// DEEP: Mixed control structures
foreach ($items as $item) {
    if ($item->isActive()) {
        switch ($item->getType()) {
            case 'A':
                if ($item->hasFeature()) {
                    $this->handleTypeA($item);
                }
                break;
            case 'B':
                if ($item->isValid()) {
                    $this->handleTypeB($item);
                }
                break;
        }
    }
}

// BETTER: Strategy pattern + filter
$activeItems = array_filter($items, fn($i) => $i->isActive());
foreach ($activeItems as $item) {
    $handler = $this->handlerFactory->create($item->getType());
    $handler->handle($item);
}

Refactoring Techniques

Early Return / Guard Clauses

// Before
function process($data) {
    if ($data !== null) {
        if ($data->isValid()) {
            if ($data->canProcess()) {
                // actual logic
            }
        }
    }
}

// After
function process($data) {
    if ($data === null) return;
    if (!$data->isValid()) return;
    if (!$data->canProcess()) return;

    // actual logic (no nesting)
}

Extract Method

// Before
foreach ($orders as $order) {
    if ($order->isPaid()) {
        foreach ($order->getItems() as $item) {
            if ($item->needsShipping()) {
                $this->ship($item);
            }
        }
    }
}

// After
foreach ($orders as $order) {
    $this->processOrder($order);
}

private function processOrder(Order $order): void
{
    if (!$order->isPaid()) return;
    $this->shipItems($order->getItems());
}

private function shipItems(array $items): void
{
    foreach ($items as $item) {
        if ($item->needsShipping()) {
            $this->ship($item);
        }
    }
}

Replace Conditional with Polymorphism

// Before: Deep switch
switch ($type) {
    case 'email':
        if ($config['html']) {
            // ...
        } else {
            // ...
        }
        break;
    case 'sms':
        // ...
}

// After: Strategy pattern
interface NotificationChannel {
    public function send(Notification $notification): void;
}

class EmailChannel implements NotificationChannel { }
class SmsChannel implements NotificationChannel { }

Decompose Conditional

// Before
if ($date->before($SUMMER_START) || $date->after($SUMMER_END)) {
    $charge = $quantity * $winterRate + $winterServiceCharge;
} else {
    $charge = $quantity * $summerRate;
}

// After
if ($this->isWinter($date)) {
    $charge = $this->winterCharge($quantity);
} else {
    $charge = $this->summerCharge($quantity);
}

Grep Patterns

# Find nested if statements
Grep: "if\s*\([^)]+\)\s*\{[^}]*if\s*\(" --glob "**/*.php"

# Find nested foreach
Grep: "foreach.*foreach" --glob "**/*.php"

# Count indentation levels (manual analysis)

Severity Classification

Depth Severity
4 🟡 Minor
5 🟠 Major
6+ 🔴 Critical

Output Format

### Nesting Depth: [Description]

**Severity:** 🟠/🟡
**Location:** `file.php:line`
**Depth:** 5 levels

**Issue:**
Method `processOrder` has 5 levels of nesting, making it difficult to follow.

**Code Structure:**

if ($request->isValid()) // Level 1 if ($user = getUser()) // Level 2 if ($user->hasPermission()) // Level 3 foreach ($items) // Level 4 if ($item->isActive()) // Level 5


**Suggested Refactoring:**
```php
// Use early returns to flatten
if (!$request->isValid()) return;
if (!$user = getUser()) return;
if (!$user->hasPermission()) return;

$activeItems = $this->filterActiveItems($items);
foreach ($activeItems as $item) {
    $this->handle($item);
}

Current listing version

0.0.1

Verify the source revision ↗

Quality assessment

Out of 100 · Assessment report from SkillPi LAB.

Scenario Value85/100

Highlights

  • 提供 PHP 代码嵌套深度检测的完整解决方案
  • 覆盖多种常见嵌套问题场景(深层嵌套、复杂条件、回调地狱等)
  • 包含实用的重构技术和代码示例
Trigger Precision90/100

Highlights

  • 触发描述精准完整,明确限定为 PHP 代码嵌套深度分析
  • 覆盖多种变体场景,边界清晰不易误触
Structure and Standards95/100

Areas to improve

  • 缺少 When to Use 章节 Reported severity: Minor

    文档结构完整但缺少明确的使用场景说明章节

    Recommendation: 建议补充 'When to Use' 或 '适用场景' 章节,说明何时应使用此 Skill

Highlights

  • 文档结构清晰,分阶段组织内容(检测阈值→模式→重构→工具→输出)
  • 提供完整的 Before/After 代码对比示例
  • frontmatter 完整,单文件长度合理
Execution Reliability90/100

Highlights

  • 提供可执行的 grep 模式用于实际检测
  • 重构建议具体可行,包含多种技术方案
  • 严重性分类明确,便于优先级判断
Evidence Verifiability (mean of the first four)90/100

The arithmetic mean of the first four original scores, rounded to a whole number.

Static text checks

100 / 100 · skillpi-20261123-no-r3-v1

No current rules matched the text.

This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.

Permissions and checks before use

Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.

These common operations were not identified in the main document. This does not mean no permissions or risks exist.

These notices grant no permissions. Your host tool must still confirm file changes, secrets, external transfers or costs as needed.

Security rating and access scope

safe · Static evidence review; not a runtime safety guarantee.

Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.