kekke88/phpdantic

使用PHP类型提示进行数据验证。

v1.0.0 2023-11-19 19:18 UTC

This package is not auto-updated.

Last update: 2024-09-23 21:34:26 UTC


README

使用PHP类型提示进行数据验证。

安装

Composer

在项目中输入以下内容;

composer require kekke88/phpdantic

简介

你是否见过这样的代码;

...
$json = $client->request('GET', '/user/1');
$user = json_decode($json);

if(!isset($user->name) || !is_string($user->name)) {
    die("Name does not exist");
}
...

需要不断地参考API文档,猜测用户对象包含的内容?这个库旨在通过使用数据模型进行验证并分配值来解决这个问题,以便你可以使用你的IDE功能来处理对象。

示例

<?php

declare(strict_types=1);

namespace Kekke\Catfact;

require_once('vendor/autoload.php');

use Kekke88\Phpdantic\BaseModel;
use GuzzleHttp\Client;
use Kekke88\Phpdantic\Exceptions\PhpdanticException;

class Catfact extends BaseModel
{
    public string $fact;
    public int $length;
}

$client = new Client([
    'base_uri' => 'https://catfact.ninja/',
    'timeout'  => 2.0,
]);

$response = $client->request('GET', 'fact');

try {
    $fact = new Catfact(json_decode((string) $response->getBody(), true));
} catch (PhpdanticException $e) {
    echo $e->getMessage();
}

var_dump($fact);

验证器示例

<?php

declare(strict_types=1);

namespace Kekke\Catfact;

require_once('vendor/autoload.php');

use Kekke88\Phpdantic\BaseModel;
use GuzzleHttp\Client;
use Kekke88\Phpdantic\Exceptions\PhpdanticException;

class Catfact extends BaseModel
{
    public string $fact;
    public int $length;

    public array $phpdanticValidators = [
        'length' => 'validateLength',
    ];

    public function validateLength(int $length): bool
    {
        if($length < 60) {
            return false;
        }

        return true;
    }
}

$client = new Client([
    'base_uri' => 'https://catfact.ninja/',
    'timeout'  => 2.0,
]);

$response = $client->request('GET', 'fact');

try {
    $fact = new Catfact(json_decode((string) $response->getBody(), true));
} catch (PhpdanticException $e) {
    echo $e->getMessage(); // Validation method validateLength failed at property length
}

进行中

  • 集合
  • 用于直接验证对象和/或JSON的函数

贡献

欢迎贡献,如果你想贡献,请发起一个PR。

问题

如果你发现某些东西不符合预期,请打开一个问题