Completed
Pull Request — 3.x (#123)
by Sullivan
05:41 queued 02:36
created

GenerateCommand   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 114
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 10

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 10
dl 0
loc 114
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A configure() 0 6 1
B execute() 0 83 6
1
<?php
2
3
namespace SLLH\IsoCodesValidator\Dev\Console\Command;
4
5
use Gnugat\NomoSpaco\File\FileRepository;
6
use Gnugat\NomoSpaco\FqcnRepository;
7
use Gnugat\NomoSpaco\Token\ParserFactory;
8
use Symfony\Component\Console\Command\Command;
9
use Symfony\Component\Console\Input\InputInterface;
10
use Symfony\Component\Console\Output\OutputInterface;
11
use Symfony\Component\Finder\Finder;
12
use Symfony\Component\Translation\Dumper\XliffFileDumper;
13
use Symfony\Component\Translation\Loader\XliffFileLoader;
14
use Symfony\Component\Translation\MessageCatalogue;
15
use Symfony\Component\Translation\MessageCatalogueInterface;
16
17
/**
18
 * @author Sullivan Senechal <[email protected]>
19
 */
20
final class GenerateCommand extends Command
21
{
22
    /**
23
     * IsoCodes classes to not generate as validator.
24
     *
25
     * Generally abstract classes, interfaces or deprecations.
26
     *
27
     * @var string[]
28
     */
29
    private $excludedClasses = [
30
        'Luhn',
31
        'Gtin',
32
        'Dun14',
33
        'Itf14',
34
        'Upca',
35
    ];
36
37
    /**
38
     * {@inheritdoc}
39
     */
40
    protected function configure()
41
    {
42
        $this
43
            ->setName('generate')
44
        ;
45
    }
46
47
    /**
48
     * {@inheritdoc}
49
     */
50
    protected function execute(InputInterface $input, OutputInterface $output)
51
    {
52
        $isoCodePath = __DIR__.'/../../../vendor/ronanguilloux/isocodes';
53
        if (!file_exists($isoCodePath.'/.git')) {
54
            $output->writeln(
55
                '<error>No .git directory found on ronanguilloux/isocodes package. Please run rm -r vendor/ronanguilloux/isocodes && composer update ronanguilloux/isocodes --prefer-source command.</error>'
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 205 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
56
            );
57
58
            return 1;
59
        }
60
61
        $fqcnRepository = new FqcnRepository(new FileRepository(), new ParserFactory());
62
63
        $isoCodesClasses = array_diff(
64
            array_map(function ($fqcn) {
65
                return str_replace('IsoCodes\\', '', $fqcn);
66
            }, $fqcnRepository->findIn(__DIR__.'/../../../vendor/ronanguilloux/isocodes/src/IsoCodes')),
67
            $this->excludedClasses
68
        );
69
70
        $constraintClasses = array_filter(array_map(function ($fqcn) {
71
            return str_replace('SLLH\\IsoCodesValidator\\Constraints\\', '', $fqcn);
72
        }, $fqcnRepository->findIn(__DIR__.'/../../../src/Constraints')), function ($className) {
73
            return !empty(trim($className));
74
        });
75
76
        $twig = new \Twig_Environment(new \Twig_Loader_Filesystem(__DIR__.'/../..'));
77
78
        $xliffLoader = new XliffFileLoader();
79
        $xliffDumper = new XliffFileDumper();
80
81
        /** @var MessageCatalogue[] $catalogues */
82
        $catalogues = [];
83
        foreach (Finder::create()->in(__DIR__.'/../../../src/translations') as $fileInfo) {
84
            $locale = explode('.', $fileInfo->getBasename())[1];
85
            $catalogues[$locale] = $xliffLoader->load($fileInfo->getRealPath(), $locale, 'validators');
86
        }
87
88
        var_dump($catalogues);
0 ignored issues
show
Security Debugging Code introduced by
var_dump($catalogues); looks like debug code. Are you sure you do not want to remove it? This might expose sensitive data.
Loading history...
89
90
        foreach (array_udiff($isoCodesClasses, $constraintClasses, 'strcasecmp') as $className) {
91
            $classVersion = str_replace(
92
                'v',
93
                '',
94
                exec("git -C ${isoCodePath} tag --list --contains $(git -C ${isoCodePath} log --pretty=format:\"%h\" --diff-filter=A src/IsoCodes/${className}.php) | head -n 1")
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 177 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
95
            );
96
            $classMessage = 'This value is not a valid '.strtoupper($className).'.';
97
98
            $output->writeln("Generate <comment>${className}</comment> constraint (<info>v${classVersion}</info>).");
99
100
            file_put_contents(
101
                __DIR__."/../../../src/Constraints/${className}.php",
102
                $twig->render('templates/Constraint.php.twig', [
103
                    'class_name'    => $className,
104
                    'class_message' => $classMessage,
105
                    'class_version' => $classVersion,
106
                ])
107
            );
108
109
            file_put_contents(
110
                __DIR__."/../../../tests/Constraints/${className}ValidatorTest.php",
111
                $twig->render('templates/ConstraintValidatorTest.php.twig', [
112
                    'class_name' => $className,
113
                ])
114
            );
115
116
            foreach ($catalogues as $locale => $catalogue) {
117
                $catalogue->set($className, $classMessage, 'validators');
118
            }
119
        }
120
121
        foreach ($catalogues as $locale => $catalogue) {
122
            $fileContents = $xliffDumper->formatCatalogue($catalogue, 'validators', [
123
                'default_locale' => 'en'
124
            ]);
125
            file_put_contents(
126
                __DIR__."/../../../src/translations/validators.${locale}.xlf",
127
                str_replace('  ', '    ', $fileContents)
128
            );
129
        }
130
131
        return 0;
132
    }
133
}
134