gabrielberthier/pieck 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

gabrielberthier/pieck

最新稳定版本:v1.0.0

Composer 安装命令:

composer require gabrielberthier/pieck

包简介

The PHP validation library that converts data to Plain Old PHP Objects

README 文档

README

Pieck is a validation library that parses incoming payloads into POPOs (Plain Old PHP Objects). Similar to Pydantic, Zod, Class Validator and other libraries, its objective is to convert raw input to idiomatic user-land objects, providing runtime data validation, parsing, and serialization using PHP types, ensuring data conforms to defined schemas for robust applications, especially in APIs, by catching errors early, simplifying complex data handling (like nested JSON and arrays). Also, it provides features like automatic conversion, custom validation, and JSON Schema generation, making PHP code more reliable and developer-friendly.

Requirements

PHP 8.3+

Features

✅ Validates data via types

✅ Converts raw arrays/objects into plain objects

✅ Support for custom validation rules

✅ Method validation

✅ Collection/Array conversion

✅ To/From JSON

✅ Out of the box converts DateTime interfaces, array types, scalar types.

Installation

composer require gabrielberthier/pieck

How it works

It uses reflection to map entries to object properties.

<?php

use Pieck\Validator;
use Pieck\Attributes\Field;

class Other
{
    public function __construct(public readonly string $key) {}
}

class Example
{
    public string $defaultSignIn = 'Google';

    public function __construct(
        public readonly string $name,
        public string $occupation,
        #[Field(collectionOf: Other::class)]
        public array $otherStuff = [],
    ) {}
}

$result = Validator::validate(Example::class, [
    'name' => 'Pieck',
    'occupation' => 'Warrior',
    'otherStuff' => [['key' => null]],
]);

if ($result->isError()) {
    var_dump(($result->getError()->describe()));
} else {
    var_dump($result->getSucess());
}

Also, it is possible to extend DataClass (in a pydantic-link fashion) to use methods as modelValidate, modelValidateJson, toJson and modelDump.

use Pieck\DataClass;

class PieckRequest extends DataClass
{
    public function __construct(
        public readonly string $name,
        public string $occupation,
    ) {
    }
}


try {
    $pieckRequest = PieckRequest::modelValidate([
        'name' => 'Pieck',
        'occupation' => 'Warrior',
    ]);
    dump($pieckRequest->modelDump());
    dump($pieckRequest->toJson());
} catch (\Throwable $th) {
    dump($th);
}

Attributes

Take advantage of attributes to extend properties and validations. Pieck comes with two main Attributes: Field and Validate. Field declares how a property should be treated and Validate declares how to validate a class based on methods.

Field

Target: properties.

Properties:

  • coerce:
    • default: true
    • if set to true, will attempt to coerce a value into the declared field type
  • defaultFactory:
    • default: null
    • declares a factory of type ObjectFactoryInterface, that receives a value and converts it to its declarative property type.
  • rules:
    • default: []
    • Receives a set of rules that must be satisfied in order to pass field validation.
  • collectionOf:
    • default: null
    • If set, will try to convert the value to a collection of the given type.
    • Ex:
      • #[Field(collectionOf: 'int')] or #[Field(collectionOf: Pieces::class)]
  • serializationAlias:
    • default: null
    • If set, it will be used when serializing the object via modelDump and toJson.

Validate

Target: methods.

Properties:

  • field: The field you want to receive as param. Leaving this empty will set the args to receive the entire input passed.
  • message: The message to set case it fails.

Use this to validate the object's own properties, income values and to set behaviours while in validation.

Example:

<?php

use Pieck\Validator;
use Pieck\Attributes\Validate;

class Validatable
{
    public int $score = 100;

    #[Validate]
    public function validate(): bool
    {
        return $this->score > 0;
    }
}

Validate specific field:

<?php

use Pieck\Validator;
use Pieck\Attributes\Validate;

class Validatable
{
    public int $score = 100;

    #[Validate('score')]
    public function validate(int $score): bool
    {
        return $score > 0;
    }
}

$validated = Validator::validate(Validatable::class, ['score'=> 100])

If you raise an AssertionError, it will be converted in an error message:

<?php

use Pieck\Attributes\Validate;

class PieckRequest
{
    public function __construct(
        public readonly string $name,
    ) {}

    #[Validate(field: 'name')]
    public function validateName(string $name): void
    {
        echo $name.PHP_EOL;

        throw new \AssertionError('I wish a different name');
    }
}

$result = Validator::validate(PieckRequest::class, [
    'name' => 'Pieck',
]);

Custom Rules

Declare custom rules and pass them to Field attribute, just like:

use Pieck\Rules\RuleInterface;
use Pieck\Attributes\Field;

class NotEmpty implements RuleInterface
{
    public function passes($attribute, $value): bool
    {
        return !empty($value);
    }

    public function message(): string
    {
        return 'Message case this fails';
    }
}

class PieckRequest
{
    #[Field(
        rules: [NotEmpty::class] 
        // OR rules: [new NotEmpty()] 
    )]
    public readonly string $name;
}

统计信息

  • 总下载量: 1
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 2
  • 点击次数: 3
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 2
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-01-16

承接程序开发

PHP开发

VUE

Vue开发

前端开发

小程序开发

公众号开发

系统定制

数据库设计

云部署

网站建设

安全加固