check-pure-functions

Analyze pure-function patterns in PHP code. Detect side-effect-free methods, deterministic outputs, and immutable inputs to identify functions that are easy to test.

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-pure-functions" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-2b5933cdd80c6e0c6c247ba184cf9b5d1280e974365c268498790da59e8a5fbd. 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 pure-function patterns in PHP code. Detect side-effect-free methods, deterministic outputs, and immutable inputs to identify functions that are easy to test.

0 Downloads

Introduction source: third_party · dykyi-roman · 0.0.1 Reference

SkillPi interpretation

Tasks
Analyzes PHP code for pure function patterns. Detects side-effect-free methods, deterministic output, immutable inputs. Pure functions are easily testable.
Testing
Not tested

Browse files

Browse files at the source ↗

Original SKILL.md

Open original ↗
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

Current listing version

0.0.1

Verify the source revision ↗

Quality assessment

Out of 100 · Assessment report from SkillPi LAB.

Scenario Value75/100

Highlights

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

Highlights

  • 触发词覆盖PHP纯函数分析场景
  • description清晰准确
Structure and Standards90/100

Highlights

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

Areas to improve

  • 缺少可执行脚本 Reported severity: Minor

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

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

Highlights

  • grep模式实用且覆盖主要问题类型
  • 输出格式规范清晰
Evidence Verifiability (mean of the first four)83/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.