1 <?php
 2 /**
 3  * @package     Joomla.Platform
 4  * @subpackage  Form
 5  *
 6  * @copyright   Copyright (C) 2005 - 2017 Open Source Matters, Inc. All rights reserved.
 7  * @license     GNU General Public License version 2 or later; see LICENSE
 8  */
 9 
10 defined('JPATH_PLATFORM') or die;
11 
12 use Joomla\Registry\Registry;
13 
14 // Detect if we have full UTF-8 and unicode PCRE support.
15 if (!defined('JCOMPAT_UNICODE_PROPERTIES'))
16 {
17     define('JCOMPAT_UNICODE_PROPERTIES', (bool) @preg_match('/\pL/u', 'a'));
18 }
19 
20 /**
21  * Form Rule class for the Joomla Platform.
22  *
23  * @since  11.1
24  */
25 class JFormRule
26 {
27     /**
28      * The regular expression to use in testing a form field value.
29      *
30      * @var    string
31      * @since  11.1
32      */
33     protected $regex;
34 
35     /**
36      * The regular expression modifiers to use when testing a form field value.
37      *
38      * @var    string
39      * @since  11.1
40      */
41     protected $modifiers;
42 
43     /**
44      * Method to test the value.
45      *
46      * @param   SimpleXMLElement  $element  The SimpleXMLElement object representing the `<field>` tag for the form field object.
47      * @param   mixed             $value    The form field value to validate.
48      * @param   string            $group    The field name group control value. This acts as an array container for the field.
49      *                                      For example if the field has name="foo" and the group value is set to "bar" then the
50      *                                      full field name would end up being "bar[foo]".
51      * @param   Registry          $input    An optional Registry object with the entire data set to validate against the entire form.
52      * @param   JForm             $form     The form object for which the field is being tested.
53      *
54      * @return  boolean  True if the value is valid, false otherwise.
55      *
56      * @since   11.1
57      * @throws  UnexpectedValueException if rule is invalid.
58      */
59     public function test(SimpleXMLElement $element, $value, $group = null, Registry $input = null, JForm $form = null)
60     {
61         // Check for a valid regex.
62         if (empty($this->regex))
63         {
64             throw new UnexpectedValueException(sprintf('%s has invalid regex.', get_class($this)));
65         }
66 
67         // Add unicode property support if available.
68         if (JCOMPAT_UNICODE_PROPERTIES)
69         {
70             $this->modifiers = (strpos($this->modifiers, 'u') !== false) ? $this->modifiers : $this->modifiers . 'u';
71         }
72 
73         // Test the value against the regular expression.
74         if (preg_match(chr(1) . $this->regex . chr(1) . $this->modifiers, $value))
75         {
76             return true;
77         }
78 
79         return false;
80     }
81 }
82