1: <?php
2: /*
3: You may not change or alter any portion of this comment or credits
4: of supporting developers from this source code or any supporting source code
5: which is considered copyrighted (c) material of the original comment or credit authors.
6:
7: This program is distributed in the hope that it will be useful,
8: but WITHOUT ANY WARRANTY; without even the implied warranty of
9: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10: */
11:
12: namespace Xoops\Form;
13:
14: use Xoops\Core\Text\Sanitizer;
15:
16: /**
17: * OptionElement - Abstract base class for form elements with options (i.e. Select)
18: *
19: * @category Xoops\Form\OptionElement
20: * @package Xoops\Form
21: * @author trabis <lusopoemas@gmail.com>
22: * @author Richard Griffith <richard@geekwright.com>
23: * @copyright 2011-2015 XOOPS Project (http://xoops.org)
24: * @license GNU GPL 2 or later (http://www.gnu.org/licenses/gpl-2.0.html)
25: * @link http://xoops.org
26: */
27: abstract class OptionElement extends Element
28: {
29: /**
30: * Add an option
31: *
32: * @param string $value value attribute
33: * @param string $name name attribute
34: *
35: * @return void
36: */
37: public function addOption($value, $name = null)
38: {
39: if ($name === null || $name === '') {
40: $this->setArrayItem('option', $value, $value);
41: } else {
42: $this->setArrayItem('option', $value, $name);
43: }
44: }
45:
46: /**
47: * Add multiple options
48: *
49: * @param array $options Associative array of value->name pairs
50: *
51: * @return void
52: */
53: public function addOptionArray($options)
54: {
55: if (is_array($options)) {
56: foreach ($options as $k => $v) {
57: $this->addOption($k, $v);
58: }
59: }
60: }
61:
62: /**
63: * Get an array with all the options
64: *
65: * @param integer $encode encode special characters, potential values:
66: * 0 - skip
67: * 1 - only for value
68: * 2 - for both value and name
69: *
70: * @return array Associative array of value->name pairs
71: */
72: public function getOptions($encode = 0)
73: {
74: $options = $this->get('option', []);
75: if (!$encode) {
76: return $options;
77: }
78: $myts = Sanitizer::getInstance();
79: $value = array();
80: foreach ($options as $val => $name) {
81: $value[(bool) $encode ? $myts->htmlSpecialChars($val) : $val] = ($encode > 1)
82: ? $myts->htmlSpecialChars($name) : $name;
83: }
84: return $value;
85: }
86: }
87: