1: <?php
2:
3: /**
4: * Jyxo PHP Library
5: *
6: * LICENSE
7: *
8: * This source file is subject to the new BSD license that is bundled
9: * with this package in the file license.txt.
10: * It is also available through the world-wide-web at this URL:
11: * https://github.com/jyxo/php/blob/master/license.txt
12: */
13:
14: namespace Jyxo\Input\Validator;
15:
16: /**
17: * Validates a value using a regular expression.
18: *
19: * @category Jyxo
20: * @package Jyxo\Input
21: * @subpackage Validator
22: * @copyright Copyright (c) 2005-2011 Jyxo, s.r.o.
23: * @license https://github.com/jyxo/php/blob/master/license.txt
24: * @author Jan Pěček
25: */
26: class Regex extends \Jyxo\Input\Validator\AbstractValidator
27: {
28:
29: /**
30: * Regular expression.
31: *
32: * @var string
33: */
34: protected $pattern;
35:
36:
37: /**
38: * Constructor.
39: *
40: * @param string $pattern Regular expression
41: */
42: public function __construct($pattern)
43: {
44: $this->setPattern($pattern);
45: }
46:
47: /**
48: * Sets the validation regular expression.
49: *
50: * @param string $pattern Regular expression
51: * @return \Jyxo\Input\Validator\Regex
52: * @throws \Jyxo\Input\Validator\Exception On empty regular expression
53: */
54: public function setPattern($pattern)
55: {
56: if (empty($pattern)) {
57: throw new Exception('Pattern could not be empty');
58: }
59: $this->pattern = (string) $pattern;
60:
61: return $this;
62: }
63:
64: /**
65: * Returns the validation regular expression.
66: *
67: * @return string
68: */
69: public function getPattern()
70: {
71: return $this->pattern;
72: }
73:
74: /**
75: * Validates a value.
76: *
77: * @param mixed $value Input value
78: * @return boolean
79: */
80: public function isValid($value)
81: {
82: if (!preg_match($this->getPattern(), (string) $value)) {
83: return false;
84: }
85:
86: return true;
87: }
88:
89: }
90: