summaryrefslogtreecommitdiffstats
path: root/library/Director/Web/Form/Element/ExtensibleSet.php
blob: f3c968fc478b629c098e8da4d7fa516b10072b17 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
<?php

namespace Icinga\Module\Director\Web\Form\Element;

use InvalidArgumentException;

/**
 * Input control for extensible sets
 */
class ExtensibleSet extends FormElement
{
    /**
     * Default form view helper to use for rendering
     * @var string
     */
    public $helper = 'formIplExtensibleSet';

   // private $multiOptions;

    public function getValue()
    {
        $value = parent::getValue();
        if (is_string($value) || is_numeric($value)) {
            $value = [$value];
        } elseif ($value === null) {
            return $value;
        }
        if (! is_array($value)) {
            throw new InvalidArgumentException(sprintf(
                'ExtensibleSet expects to work with Arrays, got %s',
                var_export($value, 1)
            ));
        }
        $value = array_filter($value, 'strlen');

        if (empty($value)) {
            return null;
        }

        return $value;
    }

    /**
     * We do not want one message per entry
     *
     * @codingStandardsIgnoreStart
     */
    protected function _getErrorMessages()
    {
        return $this->_errorMessages;
        // @codingStandardsIgnoreEnd
    }

    /**
     * @codingStandardsIgnoreStart
     */
    protected function _filterValue(&$value, &$key)
    {
        // @codingStandardsIgnoreEnd
        if (is_array($value)) {
            $value = array_filter($value, 'strlen');
        } elseif (is_string($value) && !strlen($value)) {
            $value = null;
        }

        parent::_filterValue($value, $key);
    }

    public function isValid($value, $context = null)
    {
        if ($value === null) {
            $value = [];
        }

        $value = array_filter($value, 'strlen');
        $this->setValue($value);
        if ($this->isRequired() && empty($value)) {
            // TODO: translate
            $this->addError('You are required to choose at least one element');
            return false;
        }

        if ($this->hasErrors()) {
            return false;
        }

        return parent::isValid($value, $context);
    }
}