itarato / var-check
在不检查所有属性、键和实例方法的情况下访问它们。
v2.x-dev
2016-02-23 04:59 UTC
This package is not auto-updated.
Last update: 2024-09-14 15:58:07 UTC
README
变更日志
## 版本 2
- 使用PSR-4自动加载
require_once __DIR__ . '/vendor/autoload.php'; use itarato\VarCheck\VC;
- 实例创建
VC::make($variable);
- VarCheck方法使用下划线(避免实际对象属性、函数或数组键)
VC::make($variable)->_value(); VC::make($variable)->_empty();
__call
魔术方法现在调用当前对象的实例函数
class User { function getParent() { return $this->parent; } } $child = new User(); VC::make($child)->getParent()->_value();
安装
- 通过composer:
"require": "itarato/var-check": "2.*@dev"
$ echo '{"require": {"itarato/var-check": "2.*@dev"}}' > composer.json ; composer install
VarCheck是一个类,用于验证嵌套复杂变量,而无需使用大量的isset()和exist()。
为了避免多层isset/exist等,这个类提供了一个简单的方法来验证变量中的嵌套值。典型用例是当你有一个大变量,你不确定它是否有正确的索引,并且内部有一个对象,以及一个属性...
复杂变量
$myComplexVar = array(1 => new stdClass()); $myComplexVar[1]->name = 'John Doe';
要解决的问题
// Get the value: $output = isset($myComplexVar[1]) && isset($myComplexVar[1]->name) ? $myComplexVar[1]->name : $otherwise;
解决方案
$output = VC::make($myComplexVar)->_key(1)->_attr('name')->_value($otherwise); // or even simpler: $output = VC::make($myComplexVar)->{'1'}->name->_value($otherwise);
检查嵌套值是否存在
VC::make($myComplexVar)->_key(1)->_attr('name')->_exist(); // TRUE; // or: VC::make($myComplexVar)->{'1'}->name->_exist(); // TRUE;
获取嵌套值
VC::make($myComplexVar)->_key(1)->_attr('name')->_value(); // John Doe;
如果存在,在值上调用函数
// Instead of this: $value = isset($variable['key']['foo']->element) ? my_function($variable['key']['foo']->element) : NULL; // Do this: $value = VC::make($variable)->key->foo->element->my_function(); // Or: $myClassInstance; $value = arCheck::make($variable)->key->foo->element->call(array($myClassInstance, 'instanceFunction'));
如果不存在,进行安全检查
VC::make($myComplexVar)->_key(1)->_attr('job')->_exist(); // FALSE; VC::make($myComplexVar)->_key(1)->_attr('job')->_attr('title')->_exist(); // FALSE;
同时检查和值
if ($value = VC::make($form_status)->_key('values')->_key('#node')->_attr('field_image')->_key(LANGUAGE_NONE)->_key(0)->_key('item')->_key('fid')->_value()) { // Use $value; } // or: if ($value = VC::make($form_status)->values->{'#node'}->field_image->{LANGUAGE_NONE}->{'0'}->item->fid->_value()) { // Use $value; }
自定义验证
VC::make($myVar)->_key(3)->_attr('title')->_call(function ($v) { return $v > 10; });