mfn/argument-validation

根据参数列表验证参数

0.2 2015-11-28 12:28 UTC

This package is auto-updated.

Last update: 2024-09-16 17:34:39 UTC


README

主页: https://github.com/mfn/php-argument-validation

简介

这个库可以用来验证参数定义与一系列参数的匹配。

以下PHP类型支持直接使用

  • array
  • any 用于任何类型的类型(别名:mixed
  • bool|boolean
  • callable 支持 ['class', 'method'] 语法。对于闭包,请使用 \Closure 类型提示
  • float|double|real
  • int|integer
  • numberfloatinteger
  • numericintstring,如果它表示一个数字)
  • object
  • resource 支持使用 resource 请求特定类型的资源,例如,对于文件,可以使用 resource
  • string
  • 您提供的任何类名

特性

  • 支持可选类型,通过在前面加问号:?@var。这个语法被选择以不破坏IDE支持,例如PhpStorm等。
  • 也会进行类的 instanceof 验证,只需写出完整的类名,即 ClassNamespace\Class。参见后面的关于完全限定符号名称的说明。
  • 支持类型数组,例如 arraystring[] 以及键和值的类型,即 array
  • 支持替代类型,例如 int|string

类型检查器的哲学是严格检查参数,不执行类型强制转换的魔法。

关于类和前导反斜杠的说明

这个库期望docblock已经被“标准化”,也就是说,所有符号名称都是完全合格的,没有前导反斜杠。 “完全合格”也意味着它们已经与命名空间解析,并且可能使用别名。请参阅https://github.com/mfn/php-docblock-normalize 以获取可以做到这一点的库。

要求

PHP 5.6

安装

使用composer: composer.phar require mfn/argument-validation 0.1

示例

<?php
use Mfn\ArgumentValidation\ExtractFromDocblock;
use Mfn\ArgumentValidation\ArgumentValidation;

$docblock = <<<'DOCBLOCK'
/**
 * @var array $someArray
 * @var bool $isCool
 */
DOCBLOCK;

$parameters = (new ExtractFromDocblock)->extract($docblock);

$arguments = [
    'someArray' => [],
    'isCool' => 'foobar',
];

$errors = (new ArgumentValidation)->validate($parameters, $arguments);

var_dump($errors);

此脚本将输出

array(1) {
  [0]=>
  string(86) "Argument $isCool does not match type 'bool': Expected instance of bool but received string"
}

创建自己的类型

  • 实现 \Mfn\ArgumentValidation\Interfaces\TypeInterface

    • getName()getAliases() 返回字符串(字符串数组),这是您的类型将注册的名称。这是必须在类型声明中存在的字面名称/类型。
  • 创建 \Mfn\ArgumentValidation\ArgumentValidation 的一个实例,并通过 registerType()registerTypeAs() 注册类型。

将三个参数传递给您的 validate() 方法

  • \Mfn\ArgumentValidation\Interfaces\TypeValidatorInterface 因此,如果需要,您可以从您的类型调用额外的验证
  • \Mfn\ArgumentValidation\Interfaces\TypeDescriptionParserInterface 内部类型的描述(可能为空,见 isEmpty() 方法)
  • 要检查的实际 $value

如果您的验证认为存在错误,则抛出 \Mfn\ArgumentValidation\Exceptions\TypeError

限制

  • 嵌套数组不支持键/值类型,即 array> 不会正确解析

贡献

将其分支,在功能分支上 hacking,创建一个 pull request,变得很棒!

没有开发者是孤岛,因此请遵循这些标准

© 马库斯·费舍尔 markus@fischer.name