Namespaces

  • Latte
    • Loaders
    • Macros
    • Runtime
  • Nette
    • Application
      • Responses
      • Routers
      • UI
    • Bridges
      • ApplicationLatte
      • ApplicationTracy
      • CacheLatte
      • DatabaseDI
      • DatabaseTracy
      • DITracy
      • FormsLatte
      • Framework
      • HttpTracy
      • SecurityTracy
    • Caching
      • Storages
    • ComponentModel
    • Database
      • Drivers
      • Reflection
      • Table
    • DI
      • Config
        • Adapters
      • Extensions
    • Diagnostics
    • Forms
      • Controls
      • Rendering
    • Http
    • Iterators
    • Latte
    • Loaders
    • Localization
    • Mail
    • Neon
    • PhpGenerator
    • Reflection
    • Security
    • Templating
    • Utils
  • NetteModule
  • none
  • Tracy

Classes

  • ArrayHash
  • ArrayList
  • Arrays
  • Callback
  • CallbackFilterIterator
  • DateTime
  • FileSystem
  • Finder
  • Html
  • Image
  • Json
  • LimitedScope
  • MimeTypeDetector
  • ObjectMixin
  • Paginator
  • Random
  • RecursiveCallbackFilterIterator
  • Strings
  • TokenIterator
  • Tokenizer
  • Validators

Interfaces

  • IHtmlString

Exceptions

  • AssertionException
  • JsonException
  • RegexpException
  • TokenizerException
  • UnknownImageFileException
  • Overview
  • Namespace
  • Class
  • Tree
  • Deprecated
  1: <?php
  2: 
  3: /**
  4:  * This file is part of the Nette Framework (http://nette.org)
  5:  * Copyright (c) 2004 David Grudl (http://davidgrudl.com)
  6:  */
  7: 
  8: namespace Nette\Utils;
  9: 
 10: use Nette;
 11: 
 12: 
 13: /**
 14:  * Validation utilites.
 15:  *
 16:  * @author     David Grudl
 17:  */
 18: class Validators extends Nette\Object
 19: {
 20:     protected static $validators = array(
 21:         'bool' => 'is_bool',
 22:         'boolean' => 'is_bool',
 23:         'int' => 'is_int',
 24:         'integer' => 'is_int',
 25:         'float' => 'is_float',
 26:         'number' => NULL, // is_int || is_float,
 27:         'numeric' => array(__CLASS__, 'isNumeric'),
 28:         'numericint' => array(__CLASS__, 'isNumericInt'),
 29:         'string' =>  'is_string',
 30:         'unicode' => array(__CLASS__, 'isUnicode'),
 31:         'array' => 'is_array',
 32:         'list' => array('Nette\Utils\Arrays', 'isList'),
 33:         'object' => 'is_object',
 34:         'resource' => 'is_resource',
 35:         'scalar' => 'is_scalar',
 36:         'callable' => array(__CLASS__, 'isCallable'),
 37:         'null' => 'is_null',
 38:         'email' => array(__CLASS__, 'isEmail'),
 39:         'url' => array(__CLASS__, 'isUrl'),
 40:         'uri' => array(__CLASS__, 'isUri'),
 41:         'none' => array(__CLASS__, 'isNone'),
 42:         'type' => array(__CLASS__, 'isType'),
 43:         'identifier' => array(__CLASS__, 'isPhpIdentifier'),
 44:         'pattern' => NULL,
 45:         'alnum' => 'ctype_alnum',
 46:         'alpha' => 'ctype_alpha',
 47:         'digit' => 'ctype_digit',
 48:         'lower' => 'ctype_lower',
 49:         'upper' => 'ctype_upper',
 50:         'space' => 'ctype_space',
 51:         'xdigit' => 'ctype_xdigit',
 52:     );
 53: 
 54:     protected static $counters = array(
 55:         'string' =>  'strlen',
 56:         'unicode' => array('Nette\Utils\Strings', 'length'),
 57:         'array' => 'count',
 58:         'list' => 'count',
 59:         'alnum' => 'strlen',
 60:         'alpha' => 'strlen',
 61:         'digit' => 'strlen',
 62:         'lower' => 'strlen',
 63:         'space' => 'strlen',
 64:         'upper' => 'strlen',
 65:         'xdigit' => 'strlen',
 66:     );
 67: 
 68: 
 69:     /**
 70:      * Throws exception if a variable is of unexpected type.
 71:      * @param  mixed
 72:      * @param  string  expected types separated by pipe
 73:      * @param  string  label
 74:      * @return void
 75:      */
 76:     public static function assert($value, $expected, $label = 'variable')
 77:     {
 78:         if (!static::is($value, $expected)) {
 79:             $expected = str_replace(array('|', ':'), array(' or ', ' in range '), $expected);
 80:             if (is_array($value)) {
 81:                 $type = 'array(' . count($value) . ')';
 82:             } elseif (is_object($value)) {
 83:                 $type = 'object ' . get_class($value);
 84:             } elseif (is_string($value) && strlen($value) < 40) {
 85:                 $type = "string '$value'";
 86:             } else {
 87:                 $type = gettype($value);
 88:             }
 89:             throw new AssertionException("The $label expects to be $expected, $type given.");
 90:         }
 91:     }
 92: 
 93: 
 94:     /**
 95:      * Throws exception if an array field is missing or of unexpected type.
 96:      * @param  array
 97:      * @param  string  item
 98:      * @param  string  expected types separated by pipe
 99:      * @return void
100:      */
101:     public static function assertField($arr, $field, $expected = NULL, $label = "item '%' in array")
102:     {
103:         self::assert($arr, 'array', 'first argument');
104:         if (!array_key_exists($field, $arr)) {
105:             throw new AssertionException('Missing ' . str_replace('%', $field, $label) . '.');
106: 
107:         } elseif ($expected) {
108:             static::assert($arr[$field], $expected, str_replace('%', $field, $label));
109:         }
110:     }
111: 
112: 
113:     /**
114:      * Finds whether a variable is of expected type.
115:      * @param  mixed
116:      * @param  string  expected types separated by pipe with optional ranges
117:      * @return bool
118:      */
119:     public static function is($value, $expected)
120:     {
121:         foreach (explode('|', $expected) as $item) {
122:             list($type) = $item = explode(':', $item, 2);
123:             if (isset(static::$validators[$type])) {
124:                 if (!call_user_func(static::$validators[$type], $value)) {
125:                     continue;
126:                 }
127:             } elseif ($type === 'number') {
128:                 if (!is_int($value) && !is_float($value)) {
129:                     continue;
130:                 }
131:             } elseif ($type === 'pattern') {
132:                 if (preg_match('|^' . (isset($item[1]) ? $item[1] : '') . '\z|', $value)) {
133:                     return TRUE;
134:                 }
135:                 continue;
136:             } elseif (!$value instanceof $type) {
137:                 continue;
138:             }
139: 
140:             if (isset($item[1])) {
141:                 if (isset(static::$counters[$type])) {
142:                     $value = call_user_func(static::$counters[$type], $value);
143:                 }
144:                 $range = explode('..', $item[1]);
145:                 if (!isset($range[1])) {
146:                     $range[1] = $range[0];
147:                 }
148:                 if (($range[0] !== '' && $value < $range[0]) || ($range[1] !== '' && $value > $range[1])) {
149:                     continue;
150:                 }
151:             }
152:             return TRUE;
153:         }
154:         return FALSE;
155:     }
156: 
157: 
158:     /**
159:      * Finds whether a value is an integer.
160:      * @return bool
161:      */
162:     public static function isNumericInt($value)
163:     {
164:         return is_int($value) || is_string($value) && preg_match('#^-?[0-9]+\z#', $value);
165:     }
166: 
167: 
168:     /**
169:      * Finds whether a string is a floating point number in decimal base.
170:      * @return bool
171:      */
172:     public static function isNumeric($value)
173:     {
174:         return is_float($value) || is_int($value) || is_string($value) && preg_match('#^-?[0-9]*[.]?[0-9]+\z#', $value);
175:     }
176: 
177: 
178:     /**
179:      * Finds whether a value is a syntactically correct callback.
180:      * @return bool
181:      */
182:     public static function isCallable($value)
183:     {
184:         return $value && is_callable($value, TRUE);
185:     }
186: 
187: 
188:     /**
189:      * Finds whether a value is an UTF-8 encoded string.
190:      * @param  string
191:      * @return bool
192:      */
193:     public static function isUnicode($value)
194:     {
195:         return is_string($value) && preg_match('##u', $value);
196:     }
197: 
198: 
199:     /**
200:      * Finds whether a value is "falsy".
201:      * @return bool
202:      */
203:     public static function isNone($value)
204:     {
205:         return $value == NULL; // intentionally ==
206:     }
207: 
208: 
209:     /**
210:      * Finds whether a variable is a zero-based integer indexed array.
211:      * @param  array
212:      * @return bool
213:      */
214:     public static function isList($value)
215:     {
216:         return Arrays::isList($value);
217:     }
218: 
219: 
220:     /**
221:      * Is a value in specified range?
222:      * @param  mixed
223:      * @param  array  min and max value pair
224:      * @return bool
225:      */
226:     public static function isInRange($value, $range)
227:     {
228:         return (!isset($range[0]) || $range[0] === '' || $value >= $range[0])
229:             && (!isset($range[1]) || $range[1] === '' || $value <= $range[1]);
230:     }
231: 
232: 
233:     /**
234:      * Finds whether a string is a valid email address.
235:      * @param  string
236:      * @return bool
237:      */
238:     public static function isEmail($value)
239:     {
240:         $atom = "[-a-z0-9!#$%&'*+/=?^_`{|}~]"; // RFC 5322 unquoted characters in local-part
241:         $localPart = "(?:\"(?:[ !\\x23-\\x5B\\x5D-\\x7E]*|\\\\[ -~])+\"|$atom+(?:\\.$atom+)*)"; // quoted or unquoted
242:         $alpha = "a-z\x80-\xFF"; // superset of IDN
243:         $domain = "[0-9$alpha](?:[-0-9$alpha]{0,61}[0-9$alpha])?"; // RFC 1034 one domain component
244:         $topDomain = "[$alpha](?:[-0-9$alpha]{0,17}[$alpha])?";
245:         return (bool) preg_match("(^$localPart@(?:$domain\\.)+$topDomain\\z)i", $value);
246:     }
247: 
248: 
249:     /**
250:      * Finds whether a string is a valid http(s) URL.
251:      * @param  string
252:      * @return bool
253:      */
254:     public static function isUrl($value)
255:     {
256:         $alpha = "a-z\x80-\xFF";
257:         $domain = "[0-9$alpha](?:[-0-9$alpha]{0,61}[0-9$alpha])?";
258:         $topDomain = "[$alpha](?:[-0-9$alpha]{0,17}[$alpha])?";
259:         return (bool) preg_match("(^https?://(?:(?:$domain\\.)*$topDomain|\\d{1,3}\.\\d{1,3}\.\\d{1,3}\.\\d{1,3}|\[[0-9a-f:]{3,39}\])(:\\d{1,5})?(/\\S*)?\\z)i", $value);
260:     }
261: 
262: 
263:     /**
264:      * Finds whether a string is a valid URI according to RFC 1738.
265:      * @param  string
266:      * @return bool
267:      */
268:     public static function isUri($value)
269:     {
270:         return (bool) preg_match('#^[a-z\d+\.-]+:\S+\z#i', $value);
271:     }
272: 
273: 
274:     /**
275:      * Checks whether the input is a class, interface or trait.
276:      * @param  string
277:      * @return bool
278:      */
279:     public static function isType($type)
280:     {
281:         return class_exists($type) || interface_exists($type) || (PHP_VERSION_ID >= 50400 && trait_exists($type));
282:     }
283: 
284: 
285:     /**
286:      * Checks whether the input is a valid PHP identifier.
287:      * @return bool
288:      */
289:     public static function isPhpIdentifier($value)
290:     {
291:         return is_string($value) && preg_match('#^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*\z#', $value);
292:     }
293: 
294: }
295: 
296: 
297: /**
298:  * The exception that indicates assertion error.
299:  */
300: class AssertionException extends \Exception
301: {
302: }
303: 
Nette 2.2.6 API API documentation generated by ApiGen 2.8.0