summaryrefslogtreecommitdiffstats
path: root/library/Director/Web/Form/DbSelectorForm.php
blob: 8b4f4323c86b8e4f9670ffa1c36303e276aa2694 (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
<?php

namespace Icinga\Module\Director\Web\Form;

use gipfl\IcingaWeb2\Url;
use Icinga\Web\Response;
use ipl\Html\Form;
use Icinga\Web\Window;

class DbSelectorForm extends Form
{
    protected $defaultAttributes = [
        'class' => 'db-selector'
    ];

    protected $allowedNames;

    /** @var Window */
    protected $window;

    protected $response;

    public function __construct(Response $response, Window $window, $allowedNames)
    {
        $this->response = $response;
        $this->window = $window;
        $this->allowedNames = $allowedNames;
    }

    protected function assemble()
    {
        $this->addElement('hidden', 'DbSelector', [
            'value' => 'sent'
        ]);
        $this->addElement('select', 'db_resource', [
            'options' => $this->allowedNames,
            'class'   => 'autosubmit',
            'value'   => $this->getSession()->get('db_resource')
        ]);
    }

    /**
     * A base class should handle this, based on hidden fields
     *
     * @return bool
     */
    public function hasBeenSubmitted()
    {
        return $this->hasBeenSent() && $this->getRequestParam('DbSelector') === 'sent';
    }

    public function onSuccess()
    {
        $this->getSession()->set('db_resource', $this->getElement('db_resource')->getValue());
        $this->response->redirectAndExit(Url::fromRequest($this->getRequest()));
    }

    protected function getRequestParam($name, $default = null)
    {
        $request = $this->getRequest();
        if ($request === null) {
            return $default;
        }
        if ($request->getMethod() === 'POST') {
            $params = $request->getParsedBody();
        } elseif ($this->getMethod() === 'GET') {
            parse_str($request->getUri()->getQuery(), $params);
        } else {
            $params = [];
        }

        if (is_array($params) && array_key_exists($name, $params)) {
            return $params[$name];
        }

        return $default;
    }
    /**
     * @return \Icinga\Web\Session\SessionNamespace
     */
    protected function getSession()
    {
        return $this->window->getSessionNamespace('director');
    }
}