Completed
Pull Request — 3.x (#123)
by Sullivan
04:54
created

GenerateCommand   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 114
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 11

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 11
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 Doctrine\Common\Inflector\Inflector;
6
use Gnugat\NomoSpaco\File\FileRepository;
7
use Gnugat\NomoSpaco\FqcnRepository;
8
use Gnugat\NomoSpaco\Token\ParserFactory;
9
use Symfony\Component\Console\Command\Command;
10
use Symfony\Component\Console\Input\InputInterface;
11
use Symfony\Component\Console\Output\OutputInterface;
12
use Symfony\Component\Finder\Finder;
13
use Symfony\Component\Translation\Dumper\XliffFileDumper;
14
use Symfony\Component\Translation\Loader\XliffFileLoader;
15
use Symfony\Component\Translation\MessageCatalogue;
16
use Symfony\Component\Translation\MessageCatalogueInterface;
17
18
/**
19
 * @author Sullivan Senechal <[email protected]>
20
 */
21
final class GenerateCommand extends Command
22
{
23
    /**
24
     * IsoCodes classes to not generate as validator.
25
     *
26
     * Generally abstract classes, interfaces or deprecations.
27
     *
28
     * @var string[]
29
     */
30
    private $excludedClasses = [
31
        'Luhn',
32
        'Gtin',
33
        'Dun14',
34
        'Itf14',
35
        'Upca',
36
    ];
37
38
    /**
39
     * {@inheritdoc}
40
     */
41
    protected function configure()
42
    {
43
        $this
44
            ->setName('generate')
45
        ;
46
    }
47
48
    /**
49
     * {@inheritdoc}
50
     */
51
    protected function execute(InputInterface $input, OutputInterface $output)
52
    {
53
        $isoCodePath = __DIR__.'/../../../vendor/ronanguilloux/isocodes';
54
        if (!file_exists($isoCodePath.'/.git')) {
55
            $output->writeln(
56
                '<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...
57
            );
58
59
            return 1;
60
        }
61
62
        $fqcnRepository = new FqcnRepository(new FileRepository(), new ParserFactory());
63
64
        $isoCodesClasses = array_diff(
65
            array_map(function ($fqcn) {
66
                return str_replace('IsoCodes\\', '', $fqcn);
67
            }, $fqcnRepository->findIn(__DIR__.'/../../../vendor/ronanguilloux/isocodes/src/IsoCodes')),
68
            $this->excludedClasses
69
        );
70
71
        $constraintClasses = array_filter(array_map(function ($fqcn) {
72
            return str_replace('SLLH\\IsoCodesValidator\\Constraints\\', '', $fqcn);
73
        }, $fqcnRepository->findIn(__DIR__.'/../../../src/Constraints')), function ($className) {
74
            return !empty(trim($className));
75
        });
76
77
        $twig = new \Twig_Environment(new \Twig_Loader_Filesystem(__DIR__.'/../..'));
78
79
        $xliffLoader = new XliffFileLoader();
80
        $xliffDumper = new XliffFileDumper();
81
82
        /** @var MessageCatalogue[] $catalogues */
83
        $catalogues = [];
84
        foreach (Finder::create()->in(__DIR__.'/../../../src/translations') as $fileInfo) {
85
            $locale = explode('.', $fileInfo->getBasename())[1];
86
            $catalogues[$locale] = $xliffLoader->load($fileInfo->getRealPath(), $locale, 'validators');
87
        }
88
89
        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...
90
91
        foreach (array_udiff($isoCodesClasses, $constraintClasses, 'strcasecmp') as $className) {
92
            $classVersion = str_replace(
93
                'v',
94
                '',
95
                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...
96
            );
97
            $classMessage = 'This value is not a valid '.strtoupper($className).'.';
98
99
            $output->writeln("Generate <comment>${className}</comment> constraint (<info>v${classVersion}</info>).");
100
101
            file_put_contents(
102
                __DIR__."/../../../src/Constraints/${className}.php",
103
                $twig->render('templates/Constraint.php.twig', [
104
                    'class_name'    => $className,
105
                    'class_message' => $classMessage,
106
                    'class_version' => $classVersion,
107
                ])
108
            );
109
110
            file_put_contents(
111
                __DIR__."/../../../tests/Constraints/${className}ValidatorTest.php",
112
                $twig->render('templates/ConstraintValidatorTest.php.twig', [
113
                    'class_name' => $className,
114
                ])
115
            );
116
117
            foreach ($catalogues as $locale => $catalogue) {
118
                $catalogue->set($classMessage, Inflector::tableize($className), 'validators');
119
            }
120
        }
121
122
        foreach ($catalogues as $locale => $catalogue) {
123
            $fileContents = $xliffDumper->formatCatalogue($catalogue, 'validators', [
124
                'default_locale' => 'en'
125
            ]);
126
            file_put_contents(
127
                __DIR__."/../../../src/translations/validators.${locale}.xlf",
128
                str_replace('  ', '    ', $fileContents)
129
            );
130
        }
131
132
        return 0;
133
    }
134
}
135