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

namespace Icinga\Module\Director\Web\Form;

use gipfl\Web\Form;
use Icinga\Module\Director\Data\Exporter;
use Icinga\Module\Director\Data\ObjectImporter;
use Icinga\Module\Director\Db;
use ipl\Html\FormDecorator\DdDtDecorator;
use gipfl\Translation\TranslationHelper;
use gipfl\IcingaWeb2\Url;
use Icinga\Module\Director\Objects\ImportSource;

class CloneImportSourceForm extends Form
{
    use TranslationHelper;

    /** @var ImportSource */
    protected $source;

    /** @var ImportSource|null */
    protected $newSource;

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

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

    public function onSuccess()
    {
        $db = $this->source->getConnection();
        assert($db instanceof Db);
        $export = (new Exporter($db))->export($this->source);
        $newName = $this->getElement('source_name')->getValue();
        $export->source_name = $newName;
        unset($export->uuid);

        if (ImportSource::existsWithName($newName, $db)) {
            $this->getElement('source_name')->addMessage('Name already exists');
        }
        $importer = new ObjectImporter($db);
        $this->newSource = $importer->import(ImportSource::class, $export);
        $this->newSource->store();
    }

    public function getSuccessUrl()
    {
        return Url::fromPath('director/importsource', ['id' => $this->newSource->get('id')]);
    }
}