1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* @package Fuel\Validation |
4
|
|
|
* @version 2.0 |
5
|
|
|
* @author Fuel Development Team |
6
|
|
|
* @license MIT License |
7
|
|
|
* @copyright 2010 - 2013 Fuel Development Team |
8
|
|
|
* @link http://fuelphp.com |
9
|
|
|
*/ |
10
|
|
|
|
11
|
|
|
namespace Fuel\Validation\Rule; |
12
|
|
|
|
13
|
|
|
use Fuel\Validation\AbstractRule; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* Checks that the given value matches the regex passed to setParameter() |
17
|
|
|
* |
18
|
|
|
* @package Fuel\Validation\Rule |
19
|
|
|
* @author Fuel Devleopment Team |
20
|
|
|
* |
21
|
|
|
* @since 2.0 |
22
|
|
|
*/ |
23
|
|
View Code Duplication |
class Regex extends AbstractRule |
|
|
|
|
24
|
|
|
{ |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* Contains the rule failure message |
28
|
|
|
* |
29
|
|
|
* @var string |
30
|
|
|
*/ |
31
|
|
|
protected $message = 'The field does not match the given pattern.'; |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* @param mixed $value Value to validate |
35
|
|
|
* @param string $field Unused by this rule |
36
|
|
|
* @param array $allFields Unused by this rule |
37
|
|
|
* |
38
|
|
|
* @return bool |
39
|
|
|
* |
40
|
|
|
* @since 2.0 |
41
|
|
|
*/ |
42
|
8 |
|
public function validate($value, $field = null, $allFields = null) |
43
|
|
|
{ |
44
|
8 |
|
$regex = $this->getParameter(); |
45
|
|
|
|
46
|
8 |
|
if ( ! is_string($value) or $regex === null) |
47
|
|
|
{ |
48
|
4 |
|
return false; |
49
|
|
|
} |
50
|
|
|
|
51
|
4 |
|
return preg_match($regex, $value) == true; |
|
|
|
|
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* Sets the value to check against |
56
|
|
|
* |
57
|
|
|
* @param string $params If an array the first value will be used |
58
|
|
|
* |
59
|
|
|
* @return $this |
60
|
|
|
* |
61
|
|
|
* @since 2.0 |
62
|
|
|
*/ |
63
|
11 |
|
public function setParameter($params) |
64
|
|
|
{ |
65
|
|
|
// Ensure we have only a single thing to match against |
66
|
11 |
|
if (is_array($params)) |
67
|
|
|
{ |
68
|
1 |
|
$params = array_shift($params); |
69
|
|
|
} |
70
|
|
|
|
71
|
11 |
|
return parent::setParameter($params); |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
/** |
75
|
|
|
* Returns |
76
|
|
|
* |
77
|
|
|
* array( |
78
|
|
|
* 'pattern' => <Regex used for matching> |
79
|
|
|
* ); |
80
|
|
|
* |
81
|
|
|
* @return string[] |
82
|
|
|
*/ |
83
|
1 |
|
public function getMessageParameters() |
84
|
|
|
{ |
85
|
|
|
return array( |
86
|
1 |
|
'pattern' => $this->getParameter(), |
87
|
|
|
); |
88
|
|
|
} |
89
|
|
|
|
90
|
|
|
} |
91
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.