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

namespace Icinga\Module\Director\Web\Form;

use Icinga\Module\Director\Data\Exporter;
use ipl\Html\Form;
use ipl\Html\FormDecorator\DdDtDecorator;
use gipfl\Translation\TranslationHelper;
use gipfl\IcingaWeb2\Url;
use Icinga\Module\Director\Objects\SyncRule;

class CloneSyncRuleForm extends Form
{
    use TranslationHelper;

    /** @var SyncRule */
    protected $rule;

    /** @var SyncRule|null */
    protected $newRule;

    public function __construct(SyncRule $rule)
    {
        $this->setDefaultElementDecorator(new DdDtDecorator());
        $this->rule = $rule;
    }

    protected function assemble()
    {
        $this->addElement('text', 'rule_name', [
            'label' => $this->translate('New name'),
            'value' => $this->rule->get('rule_name'),
        ]);
        $this->addElement('submit', 'submit', [
            'label' => $this->translate('Clone')
        ]);
    }

    /**
     * @return \Icinga\Module\Director\Db
     */
    protected function getTargetDb()
    {
        return $this->rule->getConnection();
    }

    /**
     * @throws \Icinga\Exception\NotFoundError
     * @throws \Icinga\Module\Director\Exception\DuplicateKeyException
     */
    public function onSuccess()
    {
        $db = $this->getTargetDb();
        $exporter = new Exporter($db);

        $export = $exporter->export($this->rule);
        $newName = $this->getValue('rule_name');
        $export->rule_name = $newName;
        unset($export->originalId);

        if (SyncRule::existsWithName($newName, $db)) {
            $this->getElement('rule_name')->addMessage('Name already exists');
        }
        $this->newRule = SyncRule::import($export, $db);
        $this->newRule->store();
    }

    public function getSuccessUrl()
    {
        if ($this->newRule === null) {
            return parent::getSuccessUrl();
        } else {
            return Url::fromPath('director/syncrule', ['id' => $this->newRule->get('id')]);
        }
    }
}