定制 weew/validator 二次开发

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

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

weew/validator

Composer 安装命令:

composer require weew/validator

包简介

Simple validation library.

README 文档

README

Build Status Code Quality Test Coverage Version Licence

Table of contents

Installation

composer require weew/validator

Available constraints

Additional constraint packs

There are additional constraints that you may load trough composer.

Constraints

Constraints are small pieces of validation logic. A constraint can be used on its own, without the validator.

$constraint = new EmailConstraint();
// or
$constraint = new EmailConstraint('Custom error message.');
$check = $constraint->check('foo@bar.baz');

if ($check) {
    // valdiation passed
} else {
    echo $constraint->getMessage();
}

Constraint groups

Constraint groups allows you to configure multiple constraints for a single value.

$group = new ConstraintGroup('email', [
    new EmailConstraint(),
]);
// or
$group = new ConstraintGroup('email');
$group->addConstraint(new EmailConstraint());

Constraint groups can be used to validate data without the validator. The check method returns a ValidationResult object.

$result = $group->check('foo@bar.baz');

Validator

The easiest way to use the validator is by creating a new instance and adding constraints inline. Validator will return a ValidationResult object.

$validator = new Validator();
$data = ['username' => 'foo', 'email' => 'foo@bar.baz'];

$result = $validator->check($data, [
    new ConstraintGroup('email', [
        new EmailConstraint(),
    ]),
]);

Validation result and validation errors

Validation result is used to group occurring validation errors. Validation errors hold information about the validated properties, their values and the applied constraints.

if ($result->isFailed()) {
    foreach ($result->getErrors() as $error) {
        // $error->getSubject()
        // $error->getValue()
        // $error->getMessage()
        // $error->getConstraint()
    }
}

Composing a custom validator

You can compose a validator with predefined constraints that will be applied on each validation.

$data = ['username' => 'foo', 'email' => 'foo@bar.baz'];
$validator->addConstraint('email', new EmailConstraint());
$validator->addConstraints('username', [
    new AlphaConstraint(),
    new MinMaxLengthConstraint(3, 20),
]);

$result = $validator->check($data);

Creating a custom validator class

Configuring validators inline is not always the best solution. Sometimes you might want to create dedicated validator classes. With this library this is very easy to achieve.

class UserProfileValidator extends Validator {
    protected function configure() {
        $this->addConstraint('email', new EmailConstraint());
        $this->addConstraints('username', [
            new AlphaConstraint(),
            new MinMaxLengthConstraint(3, 20),
        ]);
    }
}

$data = ['username' => 'foo', 'email' => 'foo@bar.baz'];
$validator = new UserProfileValidator();
$result = $validator->check($data);

Custom constraints

Creating a new constraint is a fairly easy task. All you have to do is to implement the IConstraint interface. This is an example on how to create a simple constraint that makes sure that a number is within the given range.

class MinMaxConstraint implements IConstraint {
    protected $min;
    protected $max;
    protected $message;

    public function __construct($min, $max, $message = null) {
        $this->min = $min;
        $this->max = $max;
        $this->message = $message;
    }

    public function check($value, IValidationData $data = null) {
        if (is_numeric($value)) {
            return $value >= $this->min && $value <= $this->max;
        }

        return false;
    }

    public function getMessage() {
        if ($this->message !== null) {
            return $this->message;
        }

        return 'Some default error message.';
    }

    public function getOptions() {
        return [
            'min' => $this->min,
            'max' => $this->max,
        ];
    }
}

Wildcard validation

Imagine you have a similar structure that you want to validate.

$input = [
    'items' => [
        ['name' => 'name1'],
        ['name' => null],
        ['name' => 'name3'],
    ],
];

In order to validate the name property of every single element inside the items array, you would have to iterate over the items manually. You could also use a wildcard to target all the values. To wildcard array values, you can use this special character *.

$result = $validator->addConstraint('items.*.name', new NotNullConstraint());

In the example above, result will hold an error with subject items.1.name.

Array keys can also be validated using wildcards. You'll have to use a different wildcard character #. Be aware that the # wildcard character should always be the last path segment. This is wrong foo.#.bar, this is ok foo.bar.#.

$input = [
    'items' => [
        'name1' => 'value1',
        '2' => 'value2',
        'name3' => 'value3',
    ],
];

$result = $validator->addConstraint('items.#', new MinMaxLengthConstraint(3, 5));

Result will contain an error with subject #items.1. As you see, there is a # prefix in front of subjects for wildcard keys. This way you can differentiate between subjects for values and subjects for keys.

Property accessors

Validator comes with support for multiple data types.

Array accessor

This accessor adds support for array based data sets.

$data = ['email' => 'foo@bar.baz'];
$validator->check($data);

Object accessor

This accessor adds support for object based data sets.

$data = new stdClass();
$data->email = 'foo@bar.baz';
$validator->check($data);

Getter accessor

This accessor adds support for objects that only allow to access data over getter methods.

class User {
    protected $username;
    public function __construct($username) {
        $this->username = $username;
    }
    public function getUsername() {
        return $this->username;
    }
}

$validator->check(new User('foo'));

weew/validator 适用场景与选型建议

weew/validator 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 222 次下载、GitHub Stars 达 0, 最近一次更新时间为 2016 年 07 月 16 日, 在 PHP 生态内属于活跃度较高的组件。

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

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

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2016-07-16