1 <?php
2 /**
3 * @package Joomla.Platform
4 * @subpackage Form
5 * @copyright Copyright (C) 2005 - 2017 Open Source Matters, Inc. All rights reserved.
6 * @license GNU General Public License version 2 or later; see LICENSE.txt
7 */
8
9 defined('JPATH_PLATFORM') or die;
10
11 use Joomla\Registry\Registry;
12
13 /**
14 * Form Rule class for the Joomla Platform.
15 * Requires the value entered be one of the options in a field of type="list"
16 *
17 * @since 11.1
18 */
19 class JFormRuleOptions extends JFormRule
20 {
21 /**
22 * Method to test the value.
23 *
24 * @param SimpleXMLElement $element The SimpleXMLElement object representing the `<field>` tag for the form field object.
25 * @param mixed $value The form field value to validate.
26 * @param string $group The field name group control value. This acts as an array container for the field.
27 * For example if the field has name="foo" and the group value is set to "bar" then the
28 * full field name would end up being "bar[foo]".
29 * @param Registry $input An optional Registry object with the entire data set to validate against the entire form.
30 * @param JForm $form The form object for which the field is being tested.
31 *
32 * @return boolean True if the value is valid, false otherwise.
33 *
34 * @since 11.1
35 */
36 public function test(SimpleXMLElement $element, $value, $group = null, Registry $input = null, JForm $form = null)
37 {
38 // Check if the field is required.
39 $required = ((string) $element['required'] == 'true' || (string) $element['required'] == 'required');
40
41 if (!$required && empty($value))
42 {
43 return true;
44 }
45
46 // Make an array of all available option values.
47 $options = array();
48
49 // Create the field
50 $field = null;
51
52 if ($form)
53 {
54 $field = $form->getField((string) $element->attributes()->name, $group);
55 }
56
57 // When the field exists, the real options are fetched.
58 // This is needed for fields which do have dynamic options like from a database.
59 if ($field && is_array($field->options))
60 {
61 foreach ($field->options as $opt)
62 {
63 $options[] = $opt->value;
64 }
65 }
66 else
67 {
68 foreach ($element->option as $opt)
69 {
70 $options[] = $opt->attributes()->value;
71 }
72 }
73
74 // There may be multiple values in the form of an array (if the element is checkboxes, for example).
75 if (is_array($value))
76 {
77 // If all values are in the $options array, $diff will be empty and the options valid.
78 $diff = array_diff($value, $options);
79
80 return empty($diff);
81 }
82 else
83 {
84 // In this case value must be a string
85 return in_array((string) $value, $options);
86 }
87 }
88 }
89