grithin/phpinput

用于处理输入的PHP工具。

3.0.0 2016-07-05 14:02 UTC

This package is not auto-updated.

Last update: 2024-09-17 04:02:46 UTC


README

目的

提供一种简洁的方式,用于常见的输入过滤和验证

查看Input类的内联文档

概述

规则是一个规则数组,其键映射输入的键

规则按照提供的顺序解析

一个规则由步骤组成

每个规则可以是步骤数组或用逗号分隔的步骤字符串

每个步骤最多由三部分组成

  • 前缀
  • 处理器
  • 参数

规则看起来像以下之一

  • handler|param1;param2;param3, handler, handler
  • ['handler|param1;param2;param3', handler, handler]
  • [[handler, param1, param2, param2], handler, handler]
  • [[[prefix, callback], param1, param2, param2], handler, handler] 注意,作为字符串,参数用分号分隔

前缀可以是以下组合之一

  • "!" 在错误时中断,不再对该字段有更多规则
  • "!!" 在错误时中断,不再对任何字段有更多规则
  • "?" 表示验证是可选的,不会抛出错误(与'!'一起使用时很有用,例如'?!v.filled,email')
  • "~" 表示如果没有错误,则存在错误
  • "&" 表示如果该字段之前有任何错误,则应中断代码。这改变了在错误结束时承担责任的方式,这在前缀验证中有时是可取的:prefixed_validation.concat ['&validation2',...]
  • "&&" 表示如果在验证运行中的任何字段上有任何之前的错误,则应中断代码

处理器可以是以下之一

  • "f.name" 或 "filter.name" 其中 'name' 是 \Grithin\Filter 的方法
  • "v.name" 或 "validate.name" 其中 'name' 是 \Grithin\Validate 的方法
  • "g.name" 或 "global.name" 其中 name 是全局用户函数
  • "l.instance.name" 或 "local.instance.name" 其中 "instance" 是 $this->localInstances 的实例名称,"name" 是方法
  • "class.method" 其中 "class" 是类的名称,"method" 是该类上的静态方法的名称
  • 实际的回调值。例如 ['\Grithin\Filter','trim']

示例

use \Grithin\Input;


$in = ['bob'=>'sucks'];
$input = new Input(['in'=>$in]);

#validate that the bob value is a float
$rules = ['bob'=>'v.isFloat'];

if($input->handle($rules)){
	die("Yay!");
}else{
	echo 'uh oh...';
	\Grithin\Debug::quit($input->errors);
}
/*
uh oh...

[base:index.php:19] 1: [
	0 : [
		'type' : 'isFloat'
		'fields' : [
			0 : 'bob'
		]
	]
]
*/
use \Grithin\Input;

$passingInput = [];

$passingInput[1] = [
		'phone'=>'my phone number is (555)   555-5555.',
		'appointment_time' => 'August 8, 2020',
		'comment' => '    bob is a crazy    '
	];
$passingInput[2] = [
		'phone'=>'my phone number is (555)   555-5555.',
		'comment' => '    bob is a crazy    '
	];

#validate that the bob value is a float
$rules = [
		'phone'=>'v.phone',
		'appointment_time'=>'?!v.filled,v.date,f.datetime', #< '?' means optional, '!' means stop of not validated
		'comment' => 'f.trim'
	];

$input = new Input(['in'=>$passingInput[1]]);
$input->handle($rules);
\Grithin\Debug::out($input->in);
/*
[base:index.php:34] 1: [
	'phone' : '5555555555'
	'appointment_time' : '2020-08-08 00:00:00'
	'comment' : 'bob is a crazy'
]*/

$input = new Input(['in'=>$passingInput[2]]);
$input->handle($rules);
\Grithin\Debug::out($input->in);
/*
[base:index.php:45] 2: [
	'phone' : '5555555555'
	'comment' : 'bob is a crazy'
]
*/