selective/validation 问题修复 & 功能扩展

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

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

selective/validation

Composer 安装命令:

composer require selective/validation

包简介

Validation error collector and transformer

README 文档

README

A validation library for PHP that uses the notification pattern.

Latest Version on Packagist Software License Build Status Total Downloads

Table of contents

Requirements

  • PHP 8.2 - 8.5

Installation

composer require selective/validation

Usage

A notification is a collection of errors

In order to use a notification, you have to create the ValidationResult object. A ValidationResult can be really simple:

<?php

use Selective\Validation\Exception\ValidationException;
use Selective\Validation\ValidationResult;

$validationResult = new ValidationResult();

if (empty($data['username'])) {
    $validationResult->addError('username', 'Input required');
}

You can now test the ValidationResult and throw an exception if it contains errors.

<?php
if ($validationResult->fails()) {
    throw new ValidationException('Please check your input', $validationResult);
}

Validating form data

Login example:

<?php

use Selective\Validation\Exception\ValidationException;
use Selective\Validation\ValidationResult;

// ...

// Get all POST values
$data = (array)$request->getParsedBody();

$validation = new ValidationResult();

// Validate username
if (empty($data['username'])) {
    $validation->addError('username', 'Input required');
}

// Validate password
if (empty($data['password'])) {
    $validation->addError('password', 'Input required');
}

// Check validation result
if ($validation->fails()) {
    // Trigger error response (see validation middleware)
    throw new ValidationException('Please check your input', $validation);
}

Validating JSON

Validating a JSON request works like validating form data, because in PHP it's just an array from the request object.

<?php
use Selective\Validation\ValidationResult;

// Fetch json data from request as array
$jsonData = (array)$request->getParsedBody();

$validation = new ValidationResult();

// ...

if ($validation->fails()) {
    throw new ValidationException('Please check your input', $validation);
}

In vanilla PHP you can fetch the JSON request as follows:

<?php

$jsonData = (array)json_decode(file_get_contents('php://input'), true);

// ...

Regex

The Selective\Validation\Regex\ValidationRegex class allows you to validate if a given string conforms a defined regular expression.

Example usage:

use Selective\Validation\Factory\CakeValidationFactory;
use Selective\Validation\Regex\ValidationRegex;
// ...

$data = [ /* ... */ ];

$validationFactory = new CakeValidationFactory();
$validator = $validationFactory->createValidator();

$validator
    ->regex('id', ValidationRegex::ID, 'Invalid')
    ->regex('country', ValidationRegex::COUNTRY_ISO_2, 'Invalid country')
    ->regex('date_of_birth', ValidationRegex::DATE_DMY, 'Invalid date format');

Middleware

The ValidationExceptionMiddleware catches the ValidationException and converts it into a nice JSON response.

Slim 4 integration

Insert a container definition for ValidationExceptionMiddleware::class:

<?php

use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseFactoryInterface;
use Selective\Validation\Encoder\JsonEncoder;
use Selective\Validation\Middleware\ValidationExceptionMiddleware;
use Selective\Validation\Transformer\ErrorDetailsResultTransformer;
use Slim\App;
use Slim\Factory\AppFactory;
// ...

return [
    ValidationExceptionMiddleware::class => function (ContainerInterface $container) {
        $factory = $container->get(ResponseFactoryInterface::class);

        return new ValidationExceptionMiddleware(
            $factory, 
            new ErrorDetailsResultTransformer(), 
            new JsonEncoder()
        );
    },

    ResponseFactoryInterface::class => function (ContainerInterface $container) {
        $app = $container->get(App::class);

        return $app->getResponseFactory();
    },

    App::class => function (ContainerInterface $container) {
        AppFactory::setContainer($container);

        return AppFactory::create();
    },

    // ...

];

Add the ValidationExceptionMiddleware into your middleware stack:

<?php

use Selective\Validation\Middleware\ValidationExceptionMiddleware;
use Slim\Factory\AppFactory;

require_once __DIR__ . '/../vendor/autoload.php';

$app = AppFactory::create();

// ...

$app->add(ValidationExceptionMiddleware::class);

// ...

$app->run();

Usage in Slim

<?php

use Selective\Validation\ValidationException;
use Selective\Validation\ValidationResult;

$validation = new ValidationResult();

// Validate username
if (empty($data->username)) {
    $validation->addError('username', 'Input required');
}

// Check validation result
if ($validation->fails()) {
    // Trigger the validation middleware
    throw new ValidationException('Please check your input', $validation);
}

Validators

You can combine this library with a validator that is doing the actual validation of your input data.

The converter pattern makes it easy to map instances of one class into instances of another class.

CakePHP Validator

The cakephp/validation library provides features to build validators that can validate arbitrary arrays of data with ease.

Installation

composer require cakephp/validation

Usage

The Cake\Validation\Validator::validate() method returns a non-empty array when there are validation failures. The list of errors then can be converted into a ValidationResult using the Selective\Validation\Factory\CakeValidationFactory or Selective\Validation\Converter\CakeValidationConverter.

For example, if you want to validate a login form you could do the following:

use Selective\Validation\Factory\CakeValidationFactory;
use Selective\Validation\Exception\ValidationException;
// ...

// Within the Action class: fetch the request data, e.g. from a JSON request
$data = (array)$request->getParsedBody();

// Within the Application Service class: Do the validation
$validationFactory = new CakeValidationFactory();
$validator = $validationFactory->createValidator();

$validator
    ->notEmptyString('username', 'Input required')
    ->notEmptyString('password', 'Input required');

$validationResult = $validationFactory->createValidationResult(
    $validator->validate($data)
);

if ($validationResult->fails()) {
    throw new ValidationException('Please check your input', $validationResult);
}

Please note: The CakeValidationFactory should be injected via constructor.

Read more: https://odan.github.io/2020/10/18/slim4-cakephp-validation.html

Transformer

If you want to implement a custom response data structure, you can implement a custom transformer against the \Selective\Validation\Transformer\ResultTransformerInterface interface.

Example

<?php

namespace App\Transformer;

use Selective\Validation\Exception\ValidationException;
use Selective\Validation\Transformer\ResultTransformerInterface;
use Selective\Validation\ValidationResult;

final class MyValidationTransformer implements ResultTransformerInterface
{
    public function transform(
        ValidationResult $validationResult, 
        ValidationException $exception = null
    ): array {
        // Implement your own data structure for the response
        // ...

        return [];
    }
}

License

The MIT License (MIT). Please see License File for more information.

selective/validation 适用场景与选型建议

selective/validation 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 112.38k 次下载、GitHub Stars 达 35, 最近一次更新时间为 2019 年 04 月 23 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「validation」 「middleware」 「slim」 「psr15」 「slim4」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 selective/validation 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 selective/validation 我们能提供哪些服务?
定制开发 / 二次开发

基于 selective/validation 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 112.38k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 35
  • 点击次数: 24
  • 依赖项目数: 2
  • 推荐数: 0

GitHub 信息

  • Stars: 35
  • Watchers: 4
  • Forks: 5
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2019-04-23