check-class-length

分析 PHP 代码中的类长度问题。检测超过 300 行的类、识别可能的上帝类,评估内聚性问题并检查是否违反单一职责原则(SRP)。

仓库最近推送
GitHub Stars
109
Forks
26
Issues / PRs
1

安装方式

先用 Prompt 核对来源与依赖。也可下载安装包。

用 AI 助手安装

复制提示词,让助手先核对固定版本和依赖。

查看 Prompt收起 Prompt
先检查当前 Agent 是否已安装 SkillPI Skill Finder。如果尚未安装,请按官方仓库的说明安装并启用:https://github.com/Findskills/skillpi。然后使用 Skill Finder 打开此 SkillPI 详情页并定位 "check-class-length":https://skillpi.com/zh/skills/deepskill-88609b89c101cae8a4317631d4b50d72ac830ea64fdedc60839159ef47b02786。安装前核对上游来源和版本:https://github.com/dykyi-roman/awesome-claude-code。来源不一致时停止并说明差异。核对通过后,用 Skill Finder 安装目标 Skill,并报告安装路径和来源版本。

来源与配置

github.com

配置方式待核实

请查看原始来源中的适用工具、依赖和权限要求。

安装实测待补充

分析 PHP 代码中的类长度问题。检测超过 300 行的类、识别可能的上帝类,评估内聚性问题并检查是否违反单一职责原则(SRP)。

0 下载

介绍来源: third_party · dykyi-roman · 0.0.1 参考来源

SkillPi 解读

能完成的任务
翻译待完成,请参阅来源文档。
输入和输出
减记
实测状态
未测试

文件浏览

在原站浏览文件 ↗

原始 SKILL.md

打开原文 ↗
Frontmatter
name: check-class-length
description: Analyzes PHP code for class length issues. Detects classes exceeding 300 lines, God class indicators, cohesion issues, SRP violations.

Class Length Check

Analyze PHP code for class size and cohesion issues.

Detection Thresholds

Lines Classification
1-100 ✅ Ideal
101-200 ⚠️ Acceptable
201-300 🟡 Large - review needed
301-500 🟠 Too large - split
501+ 🔴 God class - urgent refactoring

Detection Patterns

1. God Class Indicators

// GOD CLASS: Does everything
class OrderManager
{
    // Handles orders
    public function createOrder() {}
    public function updateOrder() {}
    public function cancelOrder() {}

    // Handles payments
    public function processPayment() {}
    public function refundPayment() {}

    // Handles shipping
    public function createShipment() {}
    public function trackShipment() {}

    // Handles inventory
    public function reserveStock() {}
    public function releaseStock() {}

    // Handles notifications
    public function sendOrderConfirmation() {}
    public function sendShippingNotification() {}

    // Handles reporting
    public function generateOrderReport() {}
    public function exportToExcel() {}

    // 50+ more methods...
}

// GOOD: Split by responsibility
class OrderService {}
class PaymentService {}
class ShippingService {}
class InventoryService {}
class NotificationService {}
class ReportingService {}

2. Low Cohesion Signs

// LOW COHESION: Methods don't use same properties
class UserService
{
    private $userRepository;
    private $emailService;
    private $paymentGateway;
    private $logService;
    private $cacheService;

    // User methods use $userRepository
    public function findUser() {}
    public function updateUser() {}

    // Email methods use $emailService (unrelated)
    public function sendEmail() {}
    public function validateEmail() {}

    // Payment methods use $paymentGateway (unrelated)
    public function processPayment() {}
    public function checkBalance() {}
}

// HIGH COHESION: All methods use same core dependencies
class UserService
{
    public function __construct(
        private UserRepository $userRepository,
        private PasswordHasher $hasher,
    ) {}

    public function findUser(int $id): User {}
    public function createUser(UserData $data): User {}
    public function updateUser(User $user, UserData $data): void {}
    public function changePassword(User $user, string $password): void {}
}

3. Too Many Dependencies

// TOO MANY DEPENDENCIES: Indicates SRP violation
class OrderProcessor
{
    public function __construct(
        private OrderRepository $orderRepository,
        private ProductRepository $productRepository,
        private UserRepository $userRepository,
        private PaymentGateway $paymentGateway,
        private ShippingService $shippingService,
        private InventoryService $inventoryService,
        private EmailService $emailService,
        private SmsService $smsService,
        private PushNotificationService $pushService,
        private LoggerInterface $logger,
        private CacheInterface $cache,
        private EventDispatcher $eventDispatcher,
        // 10+ more...
    ) {}
}

// GUIDELINE: Max 5-7 dependencies
class OrderProcessor
{
    public function __construct(
        private OrderRepository $orderRepository,
        private PaymentProcessor $paymentProcessor,
        private NotificationService $notificationService,
        private EventDispatcher $eventDispatcher,
    ) {}
}

4. Feature Envy

// FEATURE ENVY: Class manipulates other class's data extensively
class OrderPrinter
{
    public function print(Order $order): string
    {
        $output = "Order: " . $order->getId() . "\n";
        $output .= "Customer: " . $order->getCustomer()->getName() . "\n";
        $output .= "Address: " . $order->getCustomer()->getAddress()->getStreet() . "\n";
        $output .= "City: " . $order->getCustomer()->getAddress()->getCity() . "\n";

        $total = 0;
        foreach ($order->getItems() as $item) {
            $output .= $item->getProduct()->getName() . ": ";
            $output .= $item->getQuantity() . " x " . $item->getPrice() . "\n";
            $total += $item->getQuantity() * $item->getPrice();
        }
        // Many more lines accessing Order internals...
    }
}

// BETTER: Move logic to Order class
class Order
{
    public function format(): string
    {
        // Order knows how to format itself
    }
}

5. Too Many Public Methods

// TOO MANY PUBLIC METHODS: API surface too large
class UserService
{
    public function findById() {}
    public function findByEmail() {}
    public function findByPhone() {}
    public function findByUsername() {}
    public function findActive() {}
    public function findInactive() {}
    public function create() {}
    public function update() {}
    public function delete() {}
    public function activate() {}
    public function deactivate() {}
    public function ban() {}
    public function unban() {}
    public function verify() {}
    // 20+ more public methods
}

// BETTER: Split into focused classes
class UserFinder {}
class UserModifier {}
class UserStatusManager {}

Metrics

LCOM (Lack of Cohesion of Methods)

  • LCOM = 0: Perfect cohesion
  • LCOM < 0.5: Good cohesion
  • LCOM > 0.8: Poor cohesion

Class Complexity Indicators

  • Lines of code > 300
  • Methods > 20
  • Properties > 10
  • Dependencies > 7
  • Cyclomatic complexity > 50

Refactoring Strategies

Extract Class

// Before: One large class
class Order
{
    // Order data and methods (30 methods)
    // Pricing logic (10 methods)
    // Shipping logic (8 methods)
    // Notification logic (5 methods)
}

// After: Multiple focused classes
class Order {} // Core order data
class OrderPricing {} // Price calculation
class OrderShipping {} // Shipping logic
class OrderNotifier {} // Notifications

Introduce Domain Events

// Before: Class does everything
class OrderService
{
    public function complete(Order $order): void
    {
        $order->complete();
        $this->updateInventory($order);
        $this->sendEmail($order);
        $this->createInvoice($order);
        $this->notifyWarehouse($order);
    }
}

// After: Event-driven
class OrderService
{
    public function complete(Order $order): void
    {
        $order->complete();
        $this->eventDispatcher->dispatch(new OrderCompletedEvent($order));
    }
}

// Separate listeners handle each concern
class UpdateInventoryListener {}
class SendConfirmationEmailListener {}
class CreateInvoiceListener {}

Severity Classification

Lines Severity
201-300 🟡 Minor
301-500 🟠 Major
501+ 🔴 Critical

Output Format

### Class Length: [ClassName] is too large

**Severity:** 🟠/🔴
**Location:** `file.php`
**Lines:** 450
**Methods:** 35
**Dependencies:** 12

**Issue:**
Class `OrderManager` is 450 lines with 35 methods, indicating multiple responsibilities.

**Responsibilities Detected:**
1. Order CRUD operations
2. Payment processing
3. Shipping management
4. Email notifications
5. Reporting

**Suggested Split:**

OrderService (100 lines) ├── OrderRepository PaymentProcessor (80 lines) ShippingManager (70 lines) OrderNotifier (50 lines) OrderReporter (60 lines)

When This Is Acceptable

  • Aggregate Roots — DDD aggregates may legitimately contain many methods to protect invariants
  • Event Sourcing aggregates — Aggregates with many apply* event handlers grow naturally
  • Test classes — Test classes with many test methods for thorough coverage

False Positive Indicators

  • Class extends AggregateRoot or similar base
  • Class is in tests/ directory
  • Class has many small, focused methods (high method count ≠ God class)

当前收录版本

0.0.1

核对来源版本 ↗

质量评测

满分100 · 来自 SkillPi LAB 实验室的评测报告。

场景价值75/100

亮点

  • 提供 PHP 代码类长度分析功能,具有明确的实用价值
  • 针对开发者常见痛点,提供具体的检测标准和重构建议
触发精准95/100

亮点

  • description 清晰明确,覆盖多种检测场景
  • 触发词精准完整,边界清晰
结构规范95/100

亮点

  • 结构完整,章节划分清晰
  • 提供详细的代码示例和分类标准
  • frontmatter 完整规范
执行可靠85/100

亮点

  • 提供详细的检测模式和重构策略
  • 逻辑完整,指导原则可靠实用
证据可验 (前四项均值)88/100

取前四项原始分值的算术平均,四舍五入取整。可通过收录报告核对各项评分与说明,运行记录需单独查证。

正文静态检测

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

正文未命中当前规则。

分数仅反映正文中的规则命中,供使用前参考。附件与运行行为不在此评分范围内。

权限与使用前检查

根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。

未从主文档识别到上述常见操作,不能据此判断无需权限或没有风险。

本站展示提示不会授予权限。涉及文件改动、密钥、外部发送或费用时,仍由你使用的工具按需确认。

安全评级与访问范围

safe · 静态证据核验,不代表运行安全保证。

使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。