定制 zfcampus/zf-content-validation 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

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

zfcampus/zf-content-validation

最新稳定版本:1.8.0

Composer 安装命令:

composer require zfcampus/zf-content-validation

包简介

Zend Framework module providing incoming content validation

README 文档

README

Repository abandoned 2019-12-31

This repository has moved to laminas-api-tools/api-tools-content-validation.

Build Status Coverage Status

Introduction

Zend Framework module for automating validation of incoming input.

Allows the following:

  • Defining named input filters.
  • Mapping named input filters to named controller services.
  • Returning an ApiProblemResponse with validation error messages on invalid input.

Requirements

Please see the composer.json file.

Installation

Run the following composer command:

$ composer require zfcampus/zf-content-validation

Alternately, manually add the following to your composer.json, in the require section:

"require": {
    "zfcampus/zf-content-validation": "^1.4"
}

And then run composer update to ensure the module is installed.

Finally, add the module name to your project's config/application.config.php under the modules key:

return [
    /* ... */
    'modules' => [
        /* ... */
        'ZF\ContentValidation',
    ],
    /* ... */
];

Configuration

User Configuration

This module utilizes two user level configuration keys zf-content-validation and also input_filter_specs (named such that this functionality can be moved into ZF2 in the future).

Service Name key

The zf-content-validation key is a mapping between controller service names as the key, and the value being an array of mappings that determine which HTTP method to respond to and what input filter to map to for the given request. The keys for the mapping can either be an HTTP method that accepts a request body (i.e., POST, PUT, PATCH, or DELETE), or it can be the word input_filter. The value assigned for the input_filter key will be used in the case that no input filter is configured for the current HTTP request method.

Example where there is a default as well as a POST filter:

'zf-content-validation' => [
    'Application\Controller\HelloWorld' => [
        'input_filter' => 'Application\Controller\HelloWorld\Validator',
        'POST' => 'Application\Controller\HelloWorld\CreationValidator',
    ],
],

In the above example, the Application\Controller\HelloWorld\Validator service will be selected for PATCH, PUT, or DELETE requests, while the Application\Controller\HelloWorld\CreationValidatorwill be selected for POST requests.

Starting in version 1.1.0, two additional keys can be defined to affect application validation behavior:

  • use_raw_data: if NOT present, raw data is ALWAYS injected into the "BodyParams" container (defined by zf-content-negotiation). If this key is present and a boolean false, then the validated, filtered data from the input filter will be used instead.

  • allows_only_fields_in_filter: if present, and use_raw_data is boolean false, the value of this flag will define whether or not additional fields present in the payload will be merged with the filtered data.

  • remove_empty_data: Should we remove empty data from received data?

    • If no remove_empty_data flag is present, do nothing - use data as is
    • If remove_empty_data flag is present AND is boolean true, then remove empty data from current data array
    • Does not remove empty data if keys matched received data

Validating GET requests

  • Since 1.3.0.

Starting in 1.3.0, you may also specify GET as an HTTP method, mapping it to an input filter in order to validate your query parameters. Configuration is exactly as described in the above section.

This feature is only available when manually configuring your API; it is not exposed in the Admin UI.

Validating collection requests

  • Since 1.5.0

Starting in 1.5.0, you may specify any of:

  • POST_COLLECTION
  • PUT_COLLECTION
  • PATCH_COLLECTION

as keys. These will then be used specifically with the given HTTP method, but only on requests matching the collection endpoint.

Validating DELETE requests

  • Since 1.6.0

Starting in 1.6.0, you may specify each of the following keys for input filters:

  • DELETE
  • DELETE_COLLECTION

The input filter associated with the key will be used to validate data sent in the request body.

input_filter_spec

input_filter_spec is for configuration-driven creation of input filters. The keys for this array will be a unique name, but more often based off the service name it is mapped to under the zf-content-validation key. The values will be an input filter configuration array, as is described in the ZF2 manual section on input filters.

Example:

'input_filter_specs' => [
    'Application\Controller\HelloWorldGet' => [
        0 => [
            'name' => 'name',
            'required' => true,
            'filters' => [
                0 => [
                    'name' => 'Zend\Filter\StringTrim',
                    'options' => [],
                ],
            ],
            'validators' => [],
            'description' => 'Hello to name',
            'allow_empty' => false,
            'continue_if_empty' => false,
        ],
    ],

System Configuration

The following configuration is defined by the module in order to function within a ZF2 application.

namespace ZF\ContentValidation;

use Zend\InputFiler\InputFilterAbstractServiceFactory;
use Zend\ServiceManager\Factory\InvokableFactory;

return [
    'controller_plugins' => [
        'aliases' => [
            'getinputfilter' => InputFilter\InputFilterPlugin::class,
            'getInputfilter' => InputFilter\InputFilterPlugin::class,
            'getInputFilter' => InputFilter\InputFilterPlugin::class,
        ],
        'factories' => [
            InputFilter\InputFilterPlugin::class => InvokableFactory::class,
        ],
    ],
    'input_filters' => [
        'abstract_factories' => [
            InputFilterAbstractServiceFactory::class,
        ],
    ],
    'service_manager' => [
        'factories' => [
            ContentValidationListener::class => ContentValidationListenerFactory::class,
        ],
    ],
    'validators' => [
        'factories' => [
            'ZF\ContentValidation\Validator\DbRecordExists' => Validator\Db\RecordExistsFactory::class,
            'ZF\ContentValidation\Validator\DbNoRecordExists' => Validator\Db\NoRecordExistsFactory::class,
        ],
    ],
];

ZF Events

Listeners

ZF\ContentValidation\ContentValidationListener

This listener is attached to the MvcEvent::EVENT_ROUTE event at priority -650. Its purpose is to utilize the zf-content-validation configuration in order to determine if the current request's selected controller service name has a configured input filter. If it does, it will traverse the mappings from the configuration file to create the appropriate input filter (from configuration or the Zend Framework 2 input filter plugin manager) in order to validate the incoming data. This particular listener utilizes the data from the zf-content-negotiation data container in order to get the deserialized content body parameters.

Events

ZF\ContentValidation\ContentValidationListener::EVENT_BEFORE_VALIDATE

This event is emitted by ZF\ContentValidation\ContentValidationListener::onRoute() (described above) in between aggregating data to validate and determining the input filter, and the actual validation of data. Its purpose is to allow users:

  • the ability to manipulate input filters.
  • to modify the data set to validate (available since 1.4.0).

As an example, you might want to validate an identifier provided via the URI, and matched during routing. You may do this as follows:

$events->listen(ContentValidationListener::EVENT_BEFORE_VALIDATE, function ($e) {
    if ($e->getController() !== MyRestController::class) {
        return;
    }

    $matches = $e->getRouteMatch();
    $data = $e->getParam('ZF\ContentValidation\ParameterData') ?: [];
    $data['id'] = $matches->getParam('id');
    $e->setParam('ZF\ContentValidation\ParameterData', $data);
});

ZF Services

Controller Plugins

ZF\ContentValidation\InputFilter\InputFilterPlugin (aka getInputFilter)

This plugin is available to Zend Framework 2 controllers. When invoked ($this->getInputFilter() or $this->plugin('getinputfilter')->__invoke()), it returns whatever is in the MVC event parameter ZF\ContentValidation\InputFilter, returning null for any value that is not an implementation of Zend\InputFilter\InputFilter.

Service

Zend\InputFilter\InputFilterAbstractServiceFactory

This abstract factory is responsible for creating and returning an appropriate input filter given a name and the configuration from the top-level key input_filter_specs. It is registered with Zend\InputFilter\InputFilterPluginManager.

zfcampus/zf-content-validation 适用场景与选型建议

zfcampus/zf-content-validation 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 1.91M 次下载、GitHub Stars 达 20, 在 PHP 生态内属于活跃度较高的组件。

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

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

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

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

  • 总下载量: 1.91M
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 20
  • 点击次数: 19
  • 依赖项目数: 21
  • 推荐数: 0

GitHub 信息

  • Stars: 20
  • Watchers: 11
  • Forks: 32
  • 开发语言: PHP

其他信息

  • 授权协议: BSD-3-Clause
  • 更新时间: 未知