Namespaces

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

Classes

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

Interfaces

  • IHtmlString

Exceptions

  • AssertionException
  • ImageException
  • JsonException
  • RegexpException
  • TokenizerException
  • UnknownImageFileException
  • Overview
  • Namespace
  • Class
  • Tree
  • Deprecated
  • Other releases
  • Nette homepage
  1: <?php
  2: 
  3: /**
  4:  * This file is part of the Nette Framework (https://nette.org)
  5:  * Copyright (c) 2004 David Grudl (https://davidgrudl.com)
  6:  */
  7: 
  8: namespace Nette\Utils;
  9: 
 10: use Nette;
 11: 
 12: 
 13: /**
 14:  * Validation utilities.
 15:  */
 16: class Validators extends Nette\Object
 17: {
 18:     protected static $validators = array(
 19:         'bool' => 'is_bool',
 20:         'boolean' => 'is_bool',
 21:         'int' => 'is_int',
 22:         'integer' => 'is_int',
 23:         'float' => 'is_float',
 24:         'number' => NULL, // is_int || is_float,
 25:         'numeric' => array(__CLASS__, 'isNumeric'),
 26:         'numericint' => array(__CLASS__, 'isNumericInt'),
 27:         'string' => 'is_string',
 28:         'unicode' => array(__CLASS__, 'isUnicode'),
 29:         'array' => 'is_array',
 30:         'list' => array('Nette\Utils\Arrays', 'isList'),
 31:         'object' => 'is_object',
 32:         'resource' => 'is_resource',
 33:         'scalar' => 'is_scalar',
 34:         'callable' => array(__CLASS__, 'isCallable'),
 35:         'null' => 'is_null',
 36:         'email' => array(__CLASS__, 'isEmail'),
 37:         'url' => array(__CLASS__, 'isUrl'),
 38:         'uri' => array(__CLASS__, 'isUri'),
 39:         'none' => array(__CLASS__, 'isNone'),
 40:         'type' => array(__CLASS__, 'isType'),
 41:         'identifier' => array(__CLASS__, 'isPhpIdentifier'),
 42:         'pattern' => NULL,
 43:         'alnum' => 'ctype_alnum',
 44:         'alpha' => 'ctype_alpha',
 45:         'digit' => 'ctype_digit',
 46:         'lower' => 'ctype_lower',
 47:         'upper' => 'ctype_upper',
 48:         'space' => 'ctype_space',
 49:         'xdigit' => 'ctype_xdigit',
 50:     );
 51: 
 52:     protected static $counters = array(
 53:         'string' => 'strlen',
 54:         'unicode' => array('Nette\Utils\Strings', 'length'),
 55:         'array' => 'count',
 56:         'list' => 'count',
 57:         'alnum' => 'strlen',
 58:         'alpha' => 'strlen',
 59:         'digit' => 'strlen',
 60:         'lower' => 'strlen',
 61:         'space' => 'strlen',
 62:         'upper' => 'strlen',
 63:         'xdigit' => 'strlen',
 64:     );
 65: 
 66: 
 67:     /**
 68:      * Throws exception if a variable is of unexpected type.
 69:      * @param  mixed
 70:      * @param  string  expected types separated by pipe
 71:      * @param  string  label
 72:      * @return void
 73:      */
 74:     public static function assert($value, $expected, $label = 'variable')
 75:     {
 76:         if (!static::is($value, $expected)) {
 77:             $expected = str_replace(array('|', ':'), array(' or ', ' in range '), $expected);
 78:             if (is_array($value)) {
 79:                 $type = 'array(' . count($value) . ')';
 80:             } elseif (is_object($value)) {
 81:                 $type = 'object ' . get_class($value);
 82:             } elseif (is_string($value) && strlen($value) < 40) {
 83:                 $type = "string '$value'";
 84:             } else {
 85:                 $type = gettype($value);
 86:             }
 87:             throw new AssertionException("The $label expects to be $expected, $type given.");
 88:         }
 89:     }
 90: 
 91: 
 92:     /**
 93:      * Throws exception if an array field is missing or of unexpected type.
 94:      * @param  array
 95:      * @param  string  item
 96:      * @param  string  expected types separated by pipe
 97:      * @param  string
 98:      * @return void
 99:      */
100:     public static function assertField($arr, $field, $expected = NULL, $label = "item '%' in array")
101:     {
102:         self::assert($arr, 'array', 'first argument');
103:         if (!array_key_exists($field, $arr)) {
104:             throw new AssertionException('Missing ' . str_replace('%', $field, $label) . '.');
105: 
106:         } elseif ($expected) {
107:             static::assert($arr[$field], $expected, str_replace('%', $field, $label));
108:         }
109:     }
110: 
111: 
112:     /**
113:      * Finds whether a variable is of expected type.
114:      * @param  mixed
115:      * @param  string  expected types separated by pipe with optional ranges
116:      * @return bool
117:      */
118:     public static function is($value, $expected)
119:     {
120:         foreach (explode('|', $expected) as $item) {
121:             list($type) = $item = explode(':', $item, 2);
122:             if (isset(static::$validators[$type])) {
123:                 if (!call_user_func(static::$validators[$type], $value)) {
124:                     continue;
125:                 }
126:             } elseif ($type === 'number') {
127:                 if (!is_int($value) && !is_float($value)) {
128:                     continue;
129:                 }
130:             } elseif ($type === 'pattern') {
131:                 if (preg_match('|^' . (isset($item[1]) ? $item[1] : '') . '\z|', $value)) {
132:                     return TRUE;
133:                 }
134:                 continue;
135:             } elseif (!$value instanceof $type) {
136:                 continue;
137:             }
138: 
139:             if (isset($item[1])) {
140:                 $length = $value;
141:                 if (isset(static::$counters[$type])) {
142:                     $length = 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] !== '' && $length < $range[0]) || ($range[1] !== '' && $length > $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:         $alpha = "a-z\x80-\xFF"; // superset of IDN
242:         return (bool) preg_match("(^
243:             (\"([ !#-[\\]-~]*|\\\\[ -~])+\"|$atom+(\\.$atom+)*)  # quoted or unquoted
244:             @
245:             ([0-9$alpha]([-0-9$alpha]{0,61}[0-9$alpha])?\\.)+    # domain - RFC 1034
246:             [$alpha]([-0-9$alpha]{0,17}[$alpha])?                # top domain
247:         \\z)ix", $value);
248:     }
249: 
250: 
251:     /**
252:      * Finds whether a string is a valid http(s) URL.
253:      * @param  string
254:      * @return bool
255:      */
256:     public static function isUrl($value)
257:     {
258:         $alpha = "a-z\x80-\xFF";
259:         return (bool) preg_match("(^
260:             https?://(
261:                 (([-_0-9$alpha]+\\.)*                       # subdomain
262:                     [0-9$alpha]([-0-9$alpha]{0,61}[0-9$alpha])?\\.)?  # domain
263:                     [$alpha]([-0-9$alpha]{0,17}[$alpha])?   # top domain
264:                 |\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}  # IPv4
265:                 |\[[0-9a-f:]{3,39}\]                        # IPv6
266:             )(:\\d{1,5})?                                   # port
267:             (/\\S*)?                                        # path
268:         \\z)ix", $value);
269:     }
270: 
271: 
272:     /**
273:      * Finds whether a string is a valid URI according to RFC 1738.
274:      * @param  string
275:      * @return bool
276:      */
277:     public static function isUri($value)
278:     {
279:         return (bool) preg_match('#^[a-z\d+\.-]+:\S+\z#i', $value);
280:     }
281: 
282: 
283:     /**
284:      * Checks whether the input is a class, interface or trait.
285:      * @param  string
286:      * @return bool
287:      */
288:     public static function isType($type)
289:     {
290:         return class_exists($type) || interface_exists($type) || (PHP_VERSION_ID >= 50400 && trait_exists($type));
291:     }
292: 
293: 
294:     /**
295:      * Checks whether the input is a valid PHP identifier.
296:      * @return bool
297:      */
298:     public static function isPhpIdentifier($value)
299:     {
300:         return is_string($value) && preg_match('#^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*\z#', $value);
301:     }
302: 
303: }
304: 
Nette 2.3-20161221 API API documentation generated by ApiGen 2.8.0