本文整理汇总了PHP中lithium\util\Validator类的典型用法代码示例。如果您正苦于以下问题:PHP Validator类的具体用法?PHP Validator怎么用?PHP Validator使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Validator类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: __init
public static function __init(array $options = array())
{
parent::__init($options);
$self = static::_instance();
$self->_finders['count'] = function ($self, $params, $chain) use(&$query, &$classes) {
$db = Connections::get($self::meta('connection'));
$records = $db->read('SELECT count(*) as count FROM posts', array('return' => 'array'));
return $records[0]['count'];
};
Post::applyFilter('save', function ($self, $params, $chain) {
$post = $params['record'];
if (!$post->id) {
$post->created = date('Y-m-d H:i:s');
} else {
$post->modified = date('Y-m-d H:i:s');
}
$params['record'] = $post;
return $chain->next($self, $params, $chain);
});
Validator::add('isUniqueTitle', function ($value, $format, $options) {
$conditions = array('title' => $value);
// If editing the post, skip the current psot
if (isset($options['values']['id'])) {
$conditions[] = 'id != ' . $options['values']['id'];
}
// Lookup for posts with same title
return !Post::find('first', array('conditions' => $conditions));
});
}
示例2: init
public static function init()
{
$class = __CLASS__;
Validator::add('modelIsSet', function ($value, $format, $options) use($class) {
if (isset($options['model']) && ($options['model'] = $class)) {
return true;
}
return false;
});
}
示例3: testMultipleLocales
public function testMultipleLocales()
{
$data = '/phone en_US/';
Catalog::write('runtime', 'validation.phone', 'en_US', $data);
$data = '/phone en_GB/';
Catalog::write('runtime', 'validation.phone', 'en_GB', $data);
Validator::add('phone', array('en_US' => Catalog::read('runtime', 'validation.phone', 'en_US'), 'en_GB' => Catalog::read('runtime', 'validation.phone', 'en_GB')));
$result = Validator::isPhone('phone en_US', 'en_US');
$this->assertTrue($result);
$result = Validator::isPhone('phone en_GB', 'en_GB');
$this->assertTrue($result);
}
示例4: testEmail
/**
* Options variations:
* 1. +pattern -mx (default)
* 2. +pattern +mx
* 3. -pattern -mx
* 4. -pattern +mx
*
* `$emails[0]` with any `$options` or without options should be `true`
* `$emails[1]` with any `$options` or without options should be `false`
* `$emails[2]` with `$options[1]` should be `true`
* `$emails[2]` with `$options[1]` should be `true`
*
* `$options[1]` works same as Lithium's default email validator implementation
*/
public function testEmail()
{
$emails = array('li3test@djordjekovacevic.com', 'invalid.djordjekovacevic.com', 'looks.valid@djordjekovacevic.c');
$options = array(array('mx' => true), array('pattern' => false), array('pattern' => false, 'mx' => true));
$this->assertTrue(Validator::rule('email', $emails[0]));
$this->assertTrue(Validator::rule('email', $emails[0], 'any', $options[0]));
$this->assertTrue(Validator::rule('email', $emails[0], 'any', $options[1]));
$this->assertTrue(Validator::rule('email', $emails[0], 'any', $options[2]));
$this->assertFalse(Validator::rule('email', $emails[1]));
$this->assertFalse(Validator::rule('email', $emails[1], 'any', $options[0]));
$this->assertFalse(Validator::rule('email', $emails[1], 'any', $options[1]));
$this->assertFalse(Validator::rule('email', $emails[1], 'any', $options[2]));
$this->assertFalse(Validator::rule('email', $emails[2], 'any'));
$this->assertTrue(Validator::rule('email', $emails[2], 'any', $options[1]));
}
示例5: testConditionalInRange
public function testConditionalInRange()
{
$values = array('height' => 195, 'gender' => 'M');
$rules = array('height' => array(array('conditionalInRange', 'message' => 'Incorrect value for given condition!', 'upper' => 201, 'lower' => 184, 'conditions' => array(array('gender', '===', 'M'))), array('conditionalInRange', 'message' => 'Incorrect value for given condition!', 'upper' => 186, 'lower' => 167, 'conditions' => array(array('gender', '===', 'W')))));
$validate = Validator::check($values, $rules);
$this->assertTrue(empty($validate));
$values['gender'] = 'W';
$validate = Validator::check($values, $rules);
$this->assertTrue(!empty($validate));
$values['height'] = 171;
$validate = Validator::check($values, $rules);
$this->assertTrue(empty($validate));
$values['height'] = 165;
$validate = Validator::check($values, $rules);
$this->assertTrue(!empty($validate));
}
示例6: __init
public static function __init(array $options = array())
{
parent::__init($options);
$self = static::_instance();
Comment::applyFilter('save', function ($self, $params, $chain) {
$comment = $params['record'];
if (!$comment->id) {
$comment->created = date('Y-m-d h:i:s');
} else {
$comment->modified = date('Y-m-d h:i:s');
}
$params['record'] = $comment;
return $chain->next($self, $params, $chain);
});
Validator::add('validName', '/^[A-Za-z0-9\'\\s]+$/');
}
示例7: validate
public static function validate($object, $object_hash = array())
{
$errors = null;
if (!in_array(spl_object_hash($object), $object_hash)) {
$object_hash[] = spl_object_hash($object);
}
$reflection = new \ReflectionClass($object);
$classname = $reflection->getName();
$validations = $object->validations;
if (!empty($validations)) {
$unique = $equalWith = array();
foreach ($validations as $field => $rules) {
foreach ($rules as $key => $value) {
if ($value[0] == "unique") {
$unique[] = array($field, "message" => $value['message']);
if (count($validations[$field]) == 1) {
unset($validations[$field]);
} else {
unset($validations[$field][$key]);
}
} else {
if ($value[0] == "equalWith") {
$equalWith[] = array($field, "message" => $value['message'], "with" => $value['with']);
if (count($validations[$field]) == 1) {
unset($validations[$field]);
} else {
unset($validations[$field][$key]);
}
}
}
}
}
$errors = Validator::check(static::convertToArray($object), $validations);
/** Unique checking */
foreach ($unique as $key => $value) {
$result = $classname::getRepository()->findOneBy(array($value[0] => $object->{$value}[0]));
if (!empty($result)) {
$errors[$value[0]][] = $value["message"];
}
}
/** EqualWith checking */
foreach ($equalWith as $key => $value) {
if ($object->{$value}[0] != $object->{$value}['with']) {
$errors[$value[0]][] = $value["message"];
}
}
$reflection = new \ReflectionClass($object);
$properties = $reflection->getProperties(\ReflectionProperty::IS_PROTECTED);
try {
foreach ($properties as $property) {
$property->setAccessible(true);
if (ModelAnnotation::match($property, array('ManyToMany', 'OneToMany'))) {
$relation = $property->getValue($object);
foreach ($relation as $item) {
if (!in_array(spl_object_hash($item), $object_hash)) {
if (!ModelValidator::isValid($item, $object_hash)) {
$errors[$property->getName()][] = $item->getErrors();
}
}
}
} elseif (ModelAnnotation::match($property, array('ManyToOne', 'OneToOne'))) {
if ($item = $property->getValue($object)) {
if (!in_array(spl_object_hash($item), $object_hash)) {
if (!ModelValidator::isValid($item, $object_hash)) {
$errors[$property->getName()][] = $item->getErrors();
}
}
}
}
}
} catch (\ReflectionException $e) {
die($e->getTrace() . "-" . $e->getMessage());
continue;
}
}
ModelValidator::$_errors[spl_object_hash($object)] = $errors;
return $errors;
}
示例8: function
Validator::add(array('sha1' => '/^[A-Fa-f0-9]{40}$/', 'slug' => '/^[a-z0-9\\_\\-\\.]*$/', 'loose_slug' => '/^[a-zA-Z0-9\\_\\-\\.]*$/', 'strict_slug' => '/^[a-z][a-z0-9\\_\\-]*$/', 'isUnique' => function ($value, $format, $options) {
$conditions = array($options['field'] => $value);
foreach ((array) $options['model']::meta('key') as $field) {
if (!empty($options['values'][$field])) {
$conditions[$field] = array('!=' => $options['values'][$field]);
}
}
$fields = $options['field'];
$result = $options['model']::find('first', compact('fields', 'conditions'));
return (bool) empty($result);
}, 'status' => function ($value, $format, $options) {
return (bool) $options['model']::status($value);
}, 'type' => function ($value, $format, $options) {
return (bool) $options['model']::types($value);
}, 'md5' => function ($value, $format, $options) {
return (bool) (strlen($value) === 32 && ctype_xdigit($value));
}, 'attachmentType' => function ($value, $type, $data) {
if (!isset($data['attachment'])) {
return true;
}
$mime = $data['attachment']['type'];
$mimeTypes = Mime::types();
foreach ($data['types'] as $each) {
if (isset($mimeTypes[$each]) && in_array($mime, $mimeTypes[$each])) {
return true;
}
}
return false;
}, 'attachmentSize' => function ($value, $type, $data) {
if (!isset($data['attachment'])) {
return true;
}
$size = $data['attachment']['size'];
if (is_string($data['size'])) {
if (preg_match('/([0-9\\.]+) ?([a-z]*)/i', $data['size'], $matches)) {
$number = $matches[1];
$suffix = $matches[2];
$suffixes = array("" => 0, "Bytes" => 0, "KB" => 1, "MB" => 2, "GB" => 3, "TB" => 4, "PB" => 5);
if (isset($suffixes[$suffix])) {
$data['size'] = round($number * pow(1024, $suffixes[$suffix]));
}
}
}
return $data['size'] >= $size;
}));
示例9: _normalizeResource
protected static function _normalizeResource($resource)
{
if (is_callable($resource)) {
return $resource;
}
if (is_array($resource)) {
if ($resource === array('*')) {
return true;
}
return $resource;
}
if (!is_string($resource)) {
throw new Exception('Unsupported resource definition: ' . var_export($resource, true));
}
if (preg_match('/^([a-z0-9_\\*\\\\]+)::([a-z0-9_\\*]+)$/i', $resource, $matches)) {
return array('controller' => $matches[1], 'action' => $matches[2]);
}
if (Validator::isRegex($resource)) {
return function ($params) use($resource) {
return (bool) preg_match($resource, $params['request']->url);
};
}
if ($resource === '*') {
return true;
}
return function ($params) use($resource) {
return $resource === $params['request']->url;
};
}
示例10: function
* 'width' => 45,
* 'height' => 45,
* 'message' => 'The image dimensions must be 45 x 45'
* ]
* ]
* ];
* }}}
*
* If the field is set to `null`, this means the user intends to delete it so it would return `true`.
*/
Validator::add('dimensions', function ($value, $rule, $options) {
$status = [];
$field = $options['field'];
if ($options['required'] && empty($_FILES[$field]['tmp_name'])) {
return false;
}
if ($options['skipEmpty'] && empty($_FILES[$field]['tmp_name'])) {
return true;
}
if (!isset($_FILES[$options['field']]['error']) && null === $_FILES[$options['field']]) {
return true;
}
list($width, $height, $type, $attr) = getimagesize($_FILES[$field]['tmp_name']);
if (isset($options['width']) && $width !== $options['width']) {
$status[] = false;
}
if (isset($options['height']) && $height !== $options['height']) {
$status[] = false;
}
return !in_array(false, $status, true);
});
示例11: is
/**
* Detects properties of the request and returns a boolean response.
*
* @see lithium\action\Request::detect()
* @todo Remove $content and refer to Media class instead
* @param string $flag
* @return boolean
*/
public function is($flag)
{
$flag = strtolower($flag);
if (!empty($this->_detectors[$flag])) {
$detector = $this->_detectors[$flag];
if (is_array($detector)) {
list($key, $check) = $detector + array('', '');
if (is_array($check)) {
$check = '/' . join('|', $check) . '/i';
}
if (Validator::isRegex($check)) {
return (bool) preg_match($check, $this->env($key));
}
return $this->env($key) == $check;
}
if (is_callable($detector)) {
return $detector($this);
}
return (bool) $this->env($detector);
}
return false;
}
示例12: function
/**
* Integration with `View`. Embeds message translation aliases into the `View`
* class (or other content handler, if specified) when content is rendered. This
* enables translation functions, i.e. `<?=$t("Translated content"); ?>`.
*/
Media::applyFilter('_handle', function ($self, $params, $chain) {
$params['handler'] += array('outputFilters' => array());
$params['handler']['outputFilters'] += Message::aliases();
return $chain->next($self, $params, $chain);
});
/**
* Integration with `Validator`. You can load locale dependent rules into the `Validator`
* by specifying them manually or retrieving them with the `Catalog` class.
*/
foreach (array('phone', 'postalCode', 'ssn') as $name) {
Validator::add($name, Catalog::read(true, "validation.{$name}", 'en_US'));
}
/**
* Intercepts dispatching processes in order to set the effective locale by using
* the locale of the request or if that is not available retrieving a locale preferred
* by the client.
*/
ActionDispatcher::applyFilter('_callable', function ($self, $params, $chain) {
$request = $params['request'];
$controller = $chain->next($self, $params, $chain);
if (!$request->locale) {
$request->params['locale'] = Locale::preferred($request);
}
Environment::set(Environment::get(), array('locale' => $request->locale));
return $controller;
});
示例13: _reportException
/**
* Convert an exception object to an exception result array for test reporting.
*
* @param array $exception The exception data to report on. Statistics are gathered and
* added to the reporting stack contained in `Unit::$_results`.
* @param string $lineFlag
* @return void
* @todo Refactor so that reporters handle trace formatting.
*/
protected function _reportException($exception, $lineFlag = null)
{
$message = $exception['message'];
$isExpected = ($exp = end($this->_expected)) && ($exp === true || $exp === $message || Validator::isRegex($exp) && preg_match($exp, $message));
if ($isExpected) {
return array_pop($this->_expected);
}
$initFrame = current($exception['trace']) + array('class' => '-', 'function' => '-');
foreach ($exception['trace'] as $frame) {
if (isset($scopedFrame)) {
break;
}
if (!class_exists('lithium\\analysis\\Inspector')) {
continue;
}
if (isset($frame['class']) && in_array($frame['class'], Inspector::parents($this))) {
$scopedFrame = $frame;
}
}
if (class_exists('lithium\\analysis\\Debugger')) {
$exception['trace'] = Debugger::trace(array('trace' => $exception['trace'], 'format' => '{:functionRef}, line {:line}', 'includeScope' => false, 'scope' => array_filter(array('functionRef' => __NAMESPACE__ . '\\{closure}', 'line' => $lineFlag))));
}
$this->_result('exception', $exception + array('class' => $initFrame['class'], 'method' => $initFrame['function']));
}
示例14: testValidationWithContextData
public function testValidationWithContextData()
{
Validator::add('someModelRule', function ($value, $format, $options) {
return $value == 'Title' && $options['values']['body'] == 'Body';
});
$result = Validator::check(array('title' => 'Title', 'body' => 'Body'), array('title' => array('someModelRule')));
$this->assertIdentical(array(), $result);
$result = Validator::check(array('title' => 'Title', 'body' => 'Not Body'), array('title' => array('someModelRule')));
$this->assertIdentical(array('title' => array(0)), $result);
}
示例15: function
Validator::add('unique', function ($value, $format, $options) {
$options += array('conditions' => array(), 'getEntityManager' => 'getEntityManager', 'connection' => isset($options['model']::$connectionName) ? $options['model']::$connectionName : 'default', 'checkPrimaryKey' => true);
$entityManager = null;
if (!empty($options['getEntityManager']) && method_exists($options['model'], $options['getEntityManager']) && is_callable($options['model'] . '::' . $options['getEntityManager'])) {
$entityManager = call_user_func($options['model'] . '::' . $options['getEntityManager']);
} elseif (!empty($options['connection'])) {
$entityManager = lithium\data\Connections::get($options['connection'])->getEntityManager();
}
if (!$entityManager) {
throw new \lithium\core\ConfigException('Could not get the entity manager');
}
$conditions = array($options['field'] => $value) + $options['conditions'];
$query = $entityManager->createQueryBuilder();
$expressions = array();
$p = 1;
foreach ($conditions as $field => $value) {
$expressions[] = $query->expr()->eq('m.' . $field, '?' . $p);
$query->setParameter($p, $value);
$p++;
}
if ($options['checkPrimaryKey'] && !empty($options['values'])) {
$metaData = $entityManager->getClassMetadata($options['model']);
foreach ($metaData->identifier as $field) {
if (isset($options['values'][$field])) {
$expressions[] = $query->expr()->neq('m.' . $field, '?' . $p);
$query->setParameter($p, $options['values'][$field]);
$p++;
}
}
}
$query->add('select', 'count(m.' . $options['field'] . ') total')->add('from', $options['model'] . ' m')->add('where', call_user_func_array(array($query->expr(), 'andx'), $expressions));
$result = $query->getQuery()->getSingleResult();
return empty($result['total']);
});