lucatume/args

一个兼容PHP 5.2的参数处理库。

1.0.1.1 2018-02-11 12:20 UTC

This package is auto-updated.

Last update: 2024-09-07 19:50:22 UTC


README

一个使参数检查变得不那么繁琐的库。

缺少类型提示

PHP不允许在函数和方法参数中使用类型提示标量值,这迫使每个函数体中都要添加循环

if (!is_string($s)){
    throw ...
}
if(strlen($s) > 20 || strlen($s) < 10){
    throw ...
}
if(preg_match($this->name_pattern, $s) === false){
    throw ...
}

这个库仍在开发中,旨在通过引入流畅的接口使参数检查更加细粒化、经过测试和DRYer
上面的检查可以变为

Arg::_($s)->is_string()->length(10, 20)->match($this->name_pattern);

还有一些与数组相关的函数

Arg::_($a)->count(6, 10)->contains('value1', 'value2')->has_key('key_one');

每个方法在条件不满足时都会抛出一个异常。在数组示例中,如果数组是 ['some', 23],则将抛出一个包含以下消息的异常

Array must contain at least 6 elements!

安装

下载类并将其添加到您的项目中,或使用Composer如下

require: {
    "lucatume/args": "~0.1"
}

方法

调用类时,应首先使用静态方法_(),并将要检查的值传递给它,可选地,还可以传递该值在异常中将被引用的名称

Arg::_($value, 'amount');

要实际检查参数是否符合条件,请使用assert()方法

Arg::_($value)->assert($value > 13);

虽然这是基础,但这种语法最好用于类未涵盖的特殊情况,应使用类提供的便捷方法。
每个方法都定义为正逻辑:如果参数符合预期,则不会发生任何事情,否则将抛出一个异常。

  • is_bool() - 检查值是否为布尔值,与is_bool()方法相同
  • is_scalar() - 检查值是否为标量,与is_scalar()方法相同
  • is_string() - 检查值是否为字符串,与is_string()方法相同
  • is_numeric() - 检查值是否为数字,与is_numeric()方法相同
  • is_int() - 检查值是否为整型,与is_int()方法相同
  • is_double() - 检查值是否为双精度浮点数,与is_double()方法相同
  • is_float() - 检查值是否为浮点数,与is_float()方法相同
  • is_null() - 检查值是否为空,与is_null()方法相同
  • is_resource() - 检查值是否为资源,与is_resource()方法相同
  • is_array() - 检查值是否为数组,与is_array()方法相同
  • is_associative_array() - 检查值是否为关联数组
  • is_object() - 检查值是否为对象,与is_object()方法相同
  • else_throw($exception) - 如果检查失败,则抛出指定的异常;$exception可以是对象实例或类名。如果类名以Exception结尾,则可以省略该部分(例如,“NotGoodException”到“NotGood”)

标量方法

如果参数是标量,则可使用额外的检查方法

  • at_least($value) - 检查参数是否大于等于该值
  • at_most($value) - 检查参数是否小于等于该值
  • greater_than($value) - 检查参数是否大于该值
  • less_than($value) - 检查参数是否小于该值

字符串方法

如果参数是字符串,则可使用额外的方法

  • length($min, [$max]) - 检查参数长度是否至少为 $min,可选地,不超过 $max 个字符。
  • match($pattern) - 检查参数是否与给定的正则表达式模式匹配

数组方法

如果参数是数组,则可用额外的方法

  • count($min, [$max]) - 检查参数是否包含至少 $min 个元素,可选地,最多包含 $max 个元素。

  • has_structure($structure) - 检查数组是否具有提供的结构,例如:

    $structure = array( 'key1' => null, 'key2' => null, 'key3' => array( 'subKey1' => null, 'subKey1' => null ) );

    $structure = array( 'key1' => 'some', 'key2' => 'foo', 'key3' => array( 'subKey1' => 12, 'subKey1' => 23 ) );

    Arg::_($arr)->has_structure($structure);

  • extends_structure($structure) - 检查数组是否扩展了提供结构

  • defaults($defaults) - 不执行检查,而是将参数数组与默认集合并集

  • contains($value [,$value] [,$value2]) - 检查参数是否包含指定的值(可选多个值)

  • has_key($value [,$value] [,$value2]) - 检查参数是否包含指定的键(可选多个键)

对象方法

  • is_set($property [, $property][, $property] ) - 检查一个或多个指定的属性是否已设置