跳至正文
OpenAgentSkill
浏览已开放 · 目录记录日期 2026-11-21 · 自动更新和账户服务暂时关闭。
数据与分析

bd-validation-rule

Add a new validation rule to better-data — implement

Lonsdale201 · 已有静态检查记录

安装与使用

运行命令前先阅读来源与依赖说明。复制命令不会自动安装或执行。

npx skills add Lonsdale201/wp-agent-skills --skill bd-validation-rule

技能说明


name: bd-validation-rule description: Add a new validation rule to better-data — implement the Rule interface (NOT "RuleInterface"; the actual interface in src/Validation/Rule.php is named Rule), live in src/Validation/Rule/, and follow the canonical contract — check(mixed, string, DataObject) returns null on pass or a short error string on fail; rules other than Required treat null as skip so nullable fields don't false- positive. Each rule is also a PHP attribute (TARGET_PARAMETER | TARGET_PROPERTY | IS_REPEATABLE), is final readonly, holds zero business logic outside check(), and surfaces in JSON Schema via RestSchemaBuilder::applyRuleAttribute when relevant. Use when introducing a rule that isn't in src/Validation/Rule/ (Email, Url, Uuid, Min, Max, MinLength, MaxLength, Regex, OneOf, Required, Callback). Triggers on creating a class implementing Rule, adding a new #[Rule\Foo] attribute, or extending applyRuleAttribute. metadata: wp-skills-author: "Soczó Kristóf" wp-skills-contact: "mailto:lonsdale201@hotmail.com" wp-skills-plugin: "better-data" wp-skills-plugin-version-tested: "phase-9" wp-skills-php-min: "8.3" wp-skills-last-updated: "2026-04-29"

better-data: Adding a validation rule

For library maintainers introducing a new built-in validation rule (Rule\CreditCard, Rule\PhoneE164, Rule\StrongPassword, etc.). Rules are tiny, pure, attribute-decorated classes that the validator iterates per field. The contract is small but precise — getting it wrong (throwing instead of returning, applying to nulls, embedding side effects) breaks compositional rules and surfaces messy errors to consumers.

Misconception this skill corrects

"I'll throw an exception with the validation error message inside check() — easier than a return-string protocol."

The contract at src/Validation/Rule.php:25-28 is:

interface Rule
{
    public function check(mixed $value, string $fieldName, DataObject $subject): ?string;
}

null = pass, short error string = fail. Throwing is the engine's prerogative, not an individual rule's. The BuiltInValidator (src/Validation/BuiltInValidator.php) iterates rules across many fields and accumulates errors; an exception would short-circuit the entire validation pass and return a single error instead of the complete failure list — which is what ValidationResult is for.

Other AI-prone misconceptions:

  • "Rule\Foo extends Rule\Email." Wrong — rules don't compose via inheritance; PHP's attribute reflection looks up exact class names. Add a new rule.
  • "The interface is RuleInterface." Wrong — it's literally Rule. The AGENTS.md docs in older drafts referred to it as RuleInterface, but the actual file is src/Validation/Rule.php and the interface is Rule. Use that name.
  • "Rules apply to null values too — I want to validate that ?Email $email = null is non-null." Wrong — convention is null means "skip"; if you want non-null, add #[Rule\Required] also. Single responsibility.

When to use this skill

Trigger when ANY of the following is true:

  • Creating a new file under src/Validation/Rule/.
  • The diff adds implements Rule (or implements the deprecated RuleInterface).
  • Adding a new #[Rule\Foo] attribute to a DTO and you can't find Foo in src/Validation/Rule/.
  • Reviewing a PR that throws inside a check() method — flag and convert to return-string.

Workflow

1. File layout

src/Validation/Rule/CreditCard.php
tests/Unit/Validation/Rule/CreditCardTest.php  ← optional, or co-located
tests/Unit/ValidationTest.php                   ← shared rule tests

2. Class shape (use Required.php as the template)

<?php

declare(strict_types=1);

namespace BetterData\Validation\Rule;

use Attribute;
use BetterData\DataObject;
use BetterData\Validation\Rule;

#[Attribute(Attribute::TARGET_PARAMETER | Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)]
final readonly class CreditCard implements Rule
{
    public function __construct(
        public bool $allowTestNumbers = false,
    ) {}

    public function check(mixed $value, string $fieldName, DataObject $subject): ?string
    {
        if ($value === null) {
            return null; // null = skip; pair with #[Required] if presence matters
        }

        if (!\is_string($value)) {
            return 'must be a string of digits';
        }

        $digits = \preg_replace('/\s+/', '', $value);

        if ($digits === null || !\preg_match('/^\d{12,19}$/', $digits)) {
            return 'must be a valid card number';
        }

        if (!self::luhnPasses($digits)) {
            return 'failed checksum';
        }

        if (!$this->allowTestNumbers && self::isTestCard($digits)) {
            return 'test card numbers are not accepted';
        }

        return null;
    }

    private static function luhnPasses(string $digits): bool { /* ... */ }
    private static function isTestCard(string $digits): bool { /* ... */ }
}

Five structural rules:

  1. final readonly class — same immutability the rest of the lib enforces.
  2. implements Rule — the interface from BetterData\Validation. Not RuleInterface, not your own.
  3. #[Attribute(...)] | IS_REPEATABLE — repeatable so a single field can carry both #[Rule\Required] and #[Rule\Email].
  4. Constructor-promoted public properties for parameters (allowTestNumbers here). Same data-carrier shape as other attributes.
  5. check() returns ?string — null on pass, short message on fail. Messages are short, lowercase-by-convention, framework-agnostic; consumers wrap them in localized strings if needed.

3. Null handling (the convention)

Look at the difference between Required.php:14-20 and Email.php:14-20:

// Required: null is the failure case
if ($value === null) {
    return 'is required';
}

// Email (and every other rule): null is "skip"
if ($v
阅读完整来源 ↗