Completed
Push — master ( 3d4598...ee29b8 )
by Jeff
03:15
created

DomainAddCommand   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 5
dl 0
loc 45
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A configure() 0 6 1
A execute() 0 20 3
A __construct() 0 9 1
1
<?php
2
3
declare(strict_types=1);
4
/**
5
 * This file is part of the mailserver-admin package.
6
 * (c) Jeffrey Boehm <https://github.com/jeboehm/mailserver-admin>
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace App\Command;
12
13
use App\Entity\Domain;
14
use Doctrine\ORM\EntityManagerInterface;
15
use Symfony\Component\Console\Command\Command;
16
use Symfony\Component\Console\Input\InputArgument;
17
use Symfony\Component\Console\Input\InputInterface;
18
use Symfony\Component\Console\Output\OutputInterface;
19
use Symfony\Component\Validator\ConstraintViolation;
20
use Symfony\Component\Validator\Validator\ValidatorInterface;
21
22
class DomainAddCommand extends Command
23
{
24
    private $manager;
25
26
    private $validator;
27
28
    public function __construct(
29
        string $name = null,
30
        EntityManagerInterface $manager,
31
        ValidatorInterface $validator
32
    ) {
33
        parent::__construct($name);
34
35
        $this->manager = $manager;
36
        $this->validator = $validator;
37
    }
38
39
    protected function configure(): void
40
    {
41
        $this
42
            ->setName('domain:add')
43
            ->setDescription('Add domains.')
44
            ->addArgument('domain', InputArgument::REQUIRED, 'Domain-part (after @)');
45
    }
46
47
    protected function execute(InputInterface $input, OutputInterface $output): int
48
    {
49
        $domain = new Domain();
50
        $domain->setName(\mb_strtolower($input->getArgument('domain')));
51
52
        $validationResult = $this->validator->validate($domain);
53
54
        if ($validationResult->count() > 0) {
55
            foreach ($validationResult as $item) {
56
                /* @var $item ConstraintViolation */
57
                $output->writeln(sprintf('<error>%s: %s</error>', $item->getPropertyPath(), $item->getMessage()));
58
            }
59
60
            return 1;
61
        }
62
63
        $this->manager->persist($domain);
64
        $this->manager->flush();
65
66
        return 0;
67
    }
68
}
69