check-pure-functions

分析 PHP 代码中的纯函数模式。检测无副作用的方法、确定性输出和不可变输入,帮助识别易于测试的纯函数。

仓库最近推送
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-pure-functions":https://skillpi.com/zh/skills/deepskill-2b5933cdd80c6e0c6c247ba184cf9b5d1280e974365c268498790da59e8a5fbd。安装前核对上游来源和版本:https://github.com/dykyi-roman/awesome-claude-code。来源不一致时停止并说明差异。核对通过后,用 Skill Finder 安装目标 Skill,并报告安装路径和来源版本。

来源与配置

github.com

配置方式待核实

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

安装实测待补充

分析 PHP 代码中的纯函数模式。检测无副作用的方法、确定性输出和不可变输入,帮助识别易于测试的纯函数。

0 下载

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

SkillPi 解读

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

文件浏览

在原站浏览文件 ↗

原始 SKILL.md

打开原文 ↗
Frontmatter
name: check-pure-functions
description: Analyzes PHP code for pure function patterns. Detects side-effect-free methods, deterministic output, immutable inputs. Pure functions are easily testable.

Pure Function Check

Analyze PHP code for pure function patterns that improve testability.

Pure Function Characteristics

A pure function:

  1. Returns the same output for the same input (deterministic)
  2. Has no side effects
  3. Doesn't depend on external state

Detection Patterns

1. Non-Deterministic Methods

// IMPURE: Depends on current time
public function isExpired(Token $token): bool
{
    return $token->getExpiresAt() < new DateTime(); // Non-deterministic
}

// PURE: Time is passed in
public function isExpired(Token $token, DateTimeInterface $now): bool
{
    return $token->getExpiresAt() < $now; // Deterministic
}

// IMPURE: Depends on random
public function generateCode(): string
{
    return bin2hex(random_bytes(16)); // Non-deterministic
}

// PURE: Random is injected
public function generateCode(RandomGeneratorInterface $random): string
{
    return bin2hex($random->bytes(16)); // Can be mocked
}

2. Methods with Side Effects

// IMPURE: Modifies external state
public function calculate(Order $order): Money
{
    $total = $this->computeTotal($order);
    $this->logger->info('Calculated total'); // Side effect
    $this->cache->set($order->getId(), $total); // Side effect
    return $total;
}

// PURE: Only calculates
public function calculate(Order $order): Money
{
    return $this->computeTotal($order);
}

// Separate side effects
public function calculateAndLog(Order $order): Money
{
    $total = $this->calculate($order);
    $this->logger->info('Calculated total');
    return $total;
}

3. Methods Modifying Input

// IMPURE: Modifies input object
public function process(Order $order): void
{
    $order->setStatus('processed'); // Modifies input
    $order->setProcessedAt(new DateTime());
}

// PURE: Returns new object
public function process(Order $order): Order
{
    return $order->withStatus('processed')
                 ->withProcessedAt(new DateTimeImmutable());
}

4. Methods Depending on Instance State

// IMPURE: Depends on mutable instance state
class PriceCalculator
{
    private float $taxRate;

    public function setTaxRate(float $rate): void
    {
        $this->taxRate = $rate;
    }

    public function calculate(Money $price): Money
    {
        return $price->multiply(1 + $this->taxRate); // Depends on state
    }
}

// PURE: All dependencies as parameters
class PriceCalculator
{
    public function calculate(Money $price, float $taxRate): Money
    {
        return $price->multiply(1 + $taxRate);
    }
}

5. Static State Dependency

// IMPURE: Depends on static state
class Config
{
    private static array $settings = [];

    public static function set(string $key, $value): void
    {
        self::$settings[$key] = $value;
    }
}

public function getDiscount(): float
{
    return Config::get('discount_rate'); // Global state
}

// PURE: Config injected
public function getDiscount(ConfigInterface $config): float
{
    return $config->get('discount_rate');
}

6. I/O in Business Logic

// IMPURE: File I/O
public function loadUserPreferences(int $userId): array
{
    $path = "/config/users/{$userId}.json";
    return json_decode(file_get_contents($path), true); // I/O
}

// PURE: Data passed in
public function parseUserPreferences(string $json): array
{
    return json_decode($json, true);
}

Pure Function Patterns

Extract Pure Core

// Before: Mixed logic and effects
public function processPayment(Order $order): PaymentResult
{
    $amount = $this->calculateTotal($order); // Pure
    $result = $this->gateway->charge($amount); // Impure
    $this->notifier->notify($order); // Impure
    return $result;
}

// After: Separated
// Pure function - easily testable
public function calculatePaymentAmount(Order $order): Money
{
    $subtotal = $this->calculateSubtotal($order);
    $tax = $this->calculateTax($subtotal);
    $discount = $this->calculateDiscount($order);
    return $subtotal->add($tax)->subtract($discount);
}

// Impure orchestration
public function processPayment(Order $order): PaymentResult
{
    $amount = $this->calculatePaymentAmount($order);
    return $this->gateway->charge($amount);
}

Functional Core, Imperative Shell

// Pure domain logic
final readonly class OrderCalculator
{
    public function calculateTotal(array $items, DiscountPolicy $policy): Money
    {
        $subtotal = array_reduce(
            $items,
            fn($sum, $item) => $sum->add($item->getLineTotal()),
            Money::zero()
        );
        return $policy->apply($subtotal);
    }
}

// Impure service (thin)
final class OrderService
{
    public function __construct(
        private OrderCalculator $calculator,
        private OrderRepository $repository,
    ) {}

    public function updateTotal(int $orderId): void
    {
        $order = $this->repository->find($orderId);
        $total = $this->calculator->calculateTotal(
            $order->getItems(),
            $order->getDiscountPolicy()
        );
        $order->setTotal($total);
        $this->repository->save($order);
    }
}

Grep Patterns

# Random in methods
Grep: "(random_bytes|rand|mt_rand|shuffle)\(" --glob "**/*.php"

# DateTime construction
Grep: "new\s+DateTime\(|DateTime::now" --glob "**/*.php"

# File I/O
Grep: "(file_get_contents|file_put_contents|fopen|fwrite)\(" --glob "**/*.php"

# Global state
Grep: "(self|static)::\\\$|global\s+\\\$" --glob "**/*.php"

Severity Classification

Pattern Severity
I/O in calculation 🟠 Major
Modifying input parameters 🟠 Major
Non-deterministic (time/random) 🟡 Minor
Depends on mutable state 🟡 Minor

Output Format

### Pure Function Issue: [Description]

**Severity:** 🟠/🟡
**Location:** `file.php:line`
**Type:** [Non-Deterministic|Side Effect|Mutable State|...]

**Issue:**
Method `calculate` depends on current time, making it non-deterministic.

**Current:**
```php
public function isExpired(Token $token): bool
{
    return $token->getExpiresAt() < new DateTime();
}

Suggested:

public function isExpired(Token $token, DateTimeInterface $now): bool
{
    return $token->getExpiresAt() < $now;
}

Testing Impact:

  • Before: Need to manipulate system time or accept flaky tests
  • After: Pass any DateTime, test edge cases easily

当前收录版本

0.0.1

核对来源版本 ↗

质量评测

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

场景价值75/100

亮点

  • 提供PHP纯函数检测的完整方法论
  • 包含多种典型场景的代码示例
  • 给出具体的grep搜索模式
触发精准85/100

亮点

  • 触发词覆盖PHP纯函数分析场景
  • description清晰准确
结构规范90/100

亮点

  • Phase划分清晰,有完整示例
  • 包含严重性分类和输出格式规范
  • frontmatter完整
执行可靠80/100

待提升项

  • 缺少可执行脚本 原报告严重程度:轻微

    提供了grep模式但缺少具体的执行脚本或自动化工具

    改进建议:建议补充一个可执行的bash脚本或PHP脚本,自动执行grep搜索并格式化输出

亮点

  • grep模式实用且覆盖主要问题类型
  • 输出格式规范清晰
证据可验 (前四项均值)83/100

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

正文静态检测

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

正文未命中当前规则。

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

权限与使用前检查

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

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

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

安全评级与访问范围

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

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