CreateFieldCommand   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 7
eloc 24
c 1
b 0
f 0
dl 0
loc 44
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A configure() 0 6 1
A __construct() 0 6 1
A execute() 0 22 5
1
<?php
2
3
/*
4
 * This file is part of the SexyField package.
5
 *
6
 * (c) Dion Snoeijen <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare (strict_types = 1);
13
14
namespace Tardigrades\Command;
15
16
use Mockery\Exception;
17
use Symfony\Component\Console\Input\InputArgument;
18
use Symfony\Component\Console\Input\InputInterface;
19
use Symfony\Component\Console\Output\OutputInterface;
20
use Symfony\Component\Yaml\Yaml;
21
use Tardigrades\SectionField\Service\FieldManagerInterface;
22
use Tardigrades\SectionField\Service\FieldNotFoundException;
23
use Tardigrades\SectionField\ValueObject\FieldConfig;
24
25
class CreateFieldCommand extends FieldCommand
26
{
27
    /** @var FieldManagerInterface */
28
    private $fieldManager;
29
30
    public function __construct(
31
        FieldManagerInterface $fieldManager
32
    ) {
33
        $this->fieldManager = $fieldManager;
34
35
        parent::__construct('sf:create-field');
36
    }
37
38
    protected function configure()
39
    {
40
        $this
41
            ->setDescription('Creates a field.')
42
            ->setHelp('Create field based on a config file.')
43
            ->addArgument('config', InputArgument::REQUIRED, 'The field configuration yml')
44
        ;
45
    }
46
47
    protected function execute(InputInterface $input, OutputInterface $output)
48
    {
49
        $config = $input->getArgument('config');
50
51
        try {
52
            if (file_exists($config)) {
53
                $parsed = Yaml::parse(file_get_contents($config));
54
                if (is_array($parsed)) {
55
                    $fieldConfig = FieldConfig::fromArray($parsed);
56
                    try {
57
                        $this->fieldManager->readByHandle($fieldConfig->getHandle());
58
                        $output->writeln('<info>This field already exists</info>');
59
                    } catch (FieldNotFoundException $exception) {
60
                        $this->fieldManager->createByConfig($fieldConfig);
61
                        $output->writeln('<info>Field created!</info>');
62
                    }
63
                    return;
64
                }
65
            }
66
            throw new Exception('No valid config found.');
67
        } catch (\Exception $exception) {
68
            $output->writeln("<error>Invalid field config. {$exception->getMessage()}</error>");
69
        }
70
    }
71
}
72