本文整理汇总了PHP中lithium\util\Validator::add方法的典型用法代码示例。如果您正苦于以下问题:PHP Validator::add方法的具体用法?PHP Validator::add怎么用?PHP Validator::add使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类lithium\util\Validator
的用法示例。
在下文中一共展示了Validator::add方法的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: __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]+$/');
}
示例5: 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']);
});
示例6: 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;
}));
示例7: 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);
});
示例8: function
* locale dependent rules into the by specifying them manually or retrieving
* them with the `Catalog` class.
*
* Enables support for multibyte strings through the `Multibyte` class by
* overwriting rules (currently just `lengthBetween`).
*
* @see lithium\g11n\Catalog
* @see lithium\g11n\Multibyte
* @see lithium\util\Validator
*/
foreach (array('phone', 'postalCode', 'ssn') as $name) {
Validator::add($name, Catalog::read(true, "validation.{$name}", 'en_US'));
}
Validator::add('lengthBetween', function ($value, $format, $options) {
$length = Multibyte::strlen($value);
$options += array('min' => 1, 'max' => 255);
return $length >= $options['min'] && $length <= $options['max'];
});
/**
* In-View Translation
*
* 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"); ?>`.
*
* @see lithium\g11n\Message::aliases()
* @see lithium\net\http\Media
*/
Media::applyFilter('_handle', function ($self, $params, $chain) {
$params['handler'] += array('outputFilters' => array());
$params['handler']['outputFilters'] += Message::aliases();
示例9: function
/**
* Works same as Lithium's `inRange` validator but require conditions `true` to continue
* @see \li3_validators\extensions\util\EvalComparation::build()
*/
$customValidators['conditionalInRange'] = function ($value, $format, $options) {
$options += array('upper' => null, 'lower' => null, 'conditions' => array());
$conditions = true;
if (!is_numeric($value)) {
return false;
}
if (!empty($options['conditions'])) {
$conditions = eval(EvalComparation::build($options));
if (!$conditions) {
return true;
}
}
switch (true) {
case !is_null($options['upper']) && !is_null($options['lower']):
return $value > $options['lower'] && $value < $options['upper'];
case !is_null($options['upper']):
return $value < $options['upper'];
case !is_null($options['lower']):
return $value > $options['lower'];
}
return is_finite($value);
};
/**
* Initialize custom validators
*/
Validator::add($customValidators);
示例10: 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.
*/
Validator::add('phone', Catalog::read('validation.phone', 'en_US'));
Validator::add('postalCode', Catalog::read('validation.postalCode', 'en_US'));
Validator::add('ssn', Catalog::read('validation.ssn', '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;
});
ConsoleDispatcher::applyFilter('_callable', function ($self, $params, $chain) {
示例11: testNlNl
public function testNlNl()
{
Validator::add(Catalog::read('validation', 'nl_NL'));
$this->assertTrue(Validator::isSsn('123456789'));
$this->assertFalse(Validator::isSsn('12345678'));
}
示例12: function
<?php
use lithium\util\Validator;
Validator::add('uniqueName', function ($value, $format, $options) {
$model = "\\" . $options['model'];
//return !(boolean) $model::first(array('conditions' => array('name' => $options['values']['name'])));
return true;
});
示例13: function
* `'mx'` boolean that enable validator to check if MX DNS record exists and
* `'pattern'` mixed `false` to use `filter_var()` function (default in lithium)
* or regex to check against. By default this filter check against custom regex
* that doesn't match all [RFC 5322](http://tools.ietf.org/html/rfc5322) valid
* emails, but will match against most correct emails, and doesn't check domain
* against MX DNS record. With combinations of this options you can achieve
* enough validations, including lithium's default (`'mx' => false, 'pattern' => false`).
*/
$overriddenValidators['email'] = function ($value, $format, $options) {
$defaults = array('mx' => false, 'pattern' => '/^[a-z0-9][a-z0-9_.-]*@[a-z0-9.-]{3,}\\.[a-z]{2,4}$/i');
$options += $defaults;
$valid = true;
switch ($options['pattern']) {
case false:
$valid = filter_var($value, FILTER_VALIDATE_EMAIL);
break;
default:
$valid = preg_match($options['pattern'], $value);
break;
}
if ($valid && $options['mx'] && function_exists('checkdnsrr')) {
$emailParts = explode('@', $value);
$valid = checkdnsrr(end($emailParts), 'MX');
}
return $valid;
};
/**
* Initialize overridden validators
*/
Validator::add($overriddenValidators);
示例14: getBaseUrl
});
Uploads::applyFilter('save', function ($self, $params, $chain) {
if ($params['data']) {
$params['entity']->set($params['data']);
$params['data'] = array();
}
if (!$params['entity']->id) {
$params['entity']->created = date('Y-m-d H:i:s');
}
return $chain->next($self, $params, $chain);
});
use lithium\util\Validator;
Validator::add('usernameTaken', function ($value) {
$success = false;
if (strlen($value) != 0) {
$success = count(Users::findByUsername($value)) == 0 ? false : true;
}
return !$success;
});
use lithium\core\Libraries;
Libraries::add('upload', array('path' => LITHIUM_APP_PATH . '/libraries/_source/upload/'));
Libraries::add('captcha', array('path' => LITHIUM_APP_PATH . '/libraries/_source/captcha/', 'webroot' => LITHIUM_APP_PATH . '/libraries/_source/captcha/', "bootstrap" => "securimage.php"));
define('_INSTALL', file_exists($_SERVER['DOCUMENT_ROOT'] . "/install") ? '1' : '0');
function getBaseUrl()
{
$protocol = isset($_SERVER["HTTPS"]) && $_SERVER['HTTPS'] != "off" ? "https" : "http";
return $protocol . "://" . $_SERVER['HTTP_HOST'];
}
use lithium\core\Environment;
Environment::is(function ($request) {
return in_array($request->env('SERVER_ADDR'), array('::1', '127.0.0.1')) ? 'development' : 'production';
示例15: testRegexContainment
/**
* Tests that setting the `'contain'` rule option to false correctly requires a string to be
* an exact match of the regex, with no additional characters outside.
*
* @return void
*/
public function testRegexContainment()
{
$this->assertTrue(Validator::isIp('127.0.0.1', null, array('contains' => false)));
$this->expectException('/Unknown modifier/');
$this->assertFalse(Validator::isIp('127.0.0.1', null, array('contains' => true)));
Validator::add('foo', '/foo/', array('contains' => true));
$this->assertTrue(Validator::isFoo('foobar'));
Validator::add('foo', 'foo', array('contains' => false));
$this->assertFalse(Validator::isFoo('foobar'));
$this->assertTrue(Validator::isFoo('foo'));
}