Passed
Push — master ( 77d283...4aaa18 )
by Bernardo
03:28
created

CompileCommand::compileToMock()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
/**
4
 * MIT License
5
 *
6
 * Copyright (c) 2017 ATRAPALO
7
 *
8
 * Permission is hereby granted, free of charge, to any person obtaining a copy
9
 * of this software and associated documentation files (the "Software"), to deal
10
 * in the Software without restriction, including without limitation the rights
11
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
 * copies of the Software, and to permit persons to whom the Software is
13
 * furnished to do so, subject to the following conditions:
14
 *
15
 * The above copyright notice and this permission notice shall be included in all
16
 * copies or substantial portions of the Software.
17
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
 * SOFTWARE.
24
 */
25
26
namespace BernardoSecades\SplitBlue\Command;
27
28
use BernardoSecades\SplitBlue\Exception\DocException;
29
use BernardoSecades\SplitBlue\Exception\MockException;
30
use Symfony\Component\Console\Command\Command;
31
use Symfony\Component\Console\Input\InputArgument;
32
use Symfony\Component\Console\Input\InputInterface;
33
use Symfony\Component\Console\Output\OutputInterface;
34
use Symfony\Component\Console\Helper\ProgressBar;
35
use Symfony\Component\Process\Process;
36
use Symfony\Component\Process\Exception\ProcessFailedException;
37
use Symfony\Component\Finder\Finder;
38
use Symfony\Component\Filesystem\Filesystem;
39
use Symfony\Component\Filesystem\Exception\IOExceptionInterface;
40
use SplFileInfo;
41
42
class CompileCommand extends Command
43
{
44
    /** @var array */
45
    protected $compiledFiles = [];
46
    /** @var array */
47
    protected $docCreatedFiles = [];
48
    /** @var OutputInterface */
49
    protected $output;
50
    /** @var string */
51
    protected $mdPath;
52
53
    protected function configure()
54
    {
55
        $this
56
            ->setName('atrapalo:mocks-compile')
57
            ->setAliases(['c'])
58
            ->setDescription('Compile .apib files to generate documentation and unique files to load in mock server')
59
            ->addArgument(
60
                'path',
61
                InputArgument::OPTIONAL,
62
                'Base folder to start to search files index.apib',
63
                dirname(__DIR__, 2) . DIRECTORY_SEPARATOR .'md'
64
            );
65
    }
66
    /**
67
     * @param InputInterface  $input
68
     * @param OutputInterface $output
69
     * @return int
70
     */
71
    protected function execute(InputInterface $input, OutputInterface $output)
72
    {
73
        if (function_exists('xdebug_disable')) {
74
            xdebug_disable();
75
        }
76
77
        $this->mdPath = $input->getArgument('path');
78
79
        $this->createMockFiles();
80
        $output->writeln('');
81
        $this->createDocFiles();
82
        $output->writeln('');
83
        $this->renderFilesInfo();
84
85
        if ($this->hasGeneratedFiles()) {
86
            return 0;
87
        }
88
89
        return 1;
90
    }
91
92
    /**
93
     * @param InputInterface  $input
94
     * @param OutputInterface $output
95
     */
96
    protected function initialize(InputInterface $input, OutputInterface $output)
97
    {
98
        $this->output = $output;
99
    }
100
101 View Code Duplication
    protected function createMockFiles()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
102
    {
103
        $files = $this->getFilesToMock();
104
        $this->output->writeln('<info>Compiling "apib" files to mock</info>');
105
        $progress = new ProgressBar($this->output, count($files));
106
        $progress->setBarCharacter('<fg=magenta>=</>');
107
        $progress->setProgressCharacter("\xF0\x9F\x8D\xBA");
108
109
        foreach ($files as $file) {
110
            $this->compileToMock($file->getRealPath());
111
            $progress->advance();
112
        }
113
114
        $progress->finish();
115
    }
116
117 View Code Duplication
    protected function createDocFiles()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
118
    {
119
        $files = $this->getFilesToDoc();
120
        $this->output->writeln('<info>Creating documentation from mock files compiled</info>');
121
        $progress = new ProgressBar($this->output, count($files));
122
        $progress->setBarCharacter('<fg=magenta>=</>');
123
        $progress->setProgressCharacter("\xF0\x9F\x8D\xBA");
124
125
        foreach ($files as $file) {
126
            $this->compileToDoc($file->getRealPath());
127
            $progress->advance();
128
        }
129
130
        $progress->finish();
131
    }
132
133
    /**
134
     * @param string $fileName
135
     */
136
    protected function compileToMock($fileName)
137
    {
138
        $this->executeMarkdownPP($fileName);
139
    }
140
141
    /**
142
     * @param string $fileName
143
     */
144
    protected function compileToDoc($fileName)
145
    {
146
        $this->executeAglio($fileName);
147
    }
148
149
    /**
150
     * @param string $fileName
151
     * @throws DocException
152
     */
153 View Code Duplication
    protected function executeAglio($fileName)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
154
    {
155
        $workingDirectory = dirname($fileName);
156
157
        if ('Build' != basename($workingDirectory)) {
158
            $pathBuild = $workingDirectory . DIRECTORY_SEPARATOR . 'Build';
159
            $fileSystem = new Filesystem();
160
            try {
161
                $fileSystem->mkdir($pathBuild);
162
            } catch (IOExceptionInterface $exception) {
163
                throw new DocException(
164
                    sprintf('Can not create folder %s', $pathBuild),
165
                    0,
166
                    $exception
167
                );
168
            }
169
        } else {
170
            $pathBuild = $workingDirectory;
171
        }
172
173
        $createdFile = sprintf('%s/out.html', $pathBuild);
174
        $commandLine = sprintf('aglio -i %s -o %s', $fileName, $createdFile);
175
        $process = new Process($commandLine);
176
        $process->setWorkingDirectory($workingDirectory);
177
178
        try {
179
            $process->mustRun();
180
            $this->docCreatedFiles[] = $createdFile;
181
        } catch (ProcessFailedException $e) {
182
            throw new DocException(
183
                sprintf(
184
                    'Error to generate mock file with markdown-pp: %s, maybe markdown-pp is not installed',
185
                    $e->getMessage()
186
                )
187
            );
188
        }
189
    }
190
191
    /**
192
     * @param string $fileName
193
     * @throws MockException
194
     */
195 View Code Duplication
    protected function executeMarkdownPP($fileName)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
196
    {
197
        $workingDirectory = dirname($fileName);
198
199
        if ('Build' != basename($workingDirectory)) {
200
            $pathBuild = $workingDirectory . DIRECTORY_SEPARATOR . 'Build';
201
            $fileSystem = new Filesystem();
202
            try {
203
                $fileSystem->mkdir($pathBuild);
204
            } catch (IOExceptionInterface $exception) {
205
                throw new MockException(
206
                    sprintf('Can not create folder %s', $pathBuild),
207
                    0,
208
                    $exception
209
                );
210
            }
211
        } else {
212
            $pathBuild = $workingDirectory;
213
        }
214
215
        $fileCreated = sprintf('%s/out.apib', $pathBuild);
216
        $commandLine = sprintf('markdown-pp %s -o %s', $fileName, $fileCreated);
217
        $process = new Process($commandLine);
218
        $process->setWorkingDirectory($workingDirectory);
219
220
        try {
221
            $process->mustRun();
222
            $this->compiledFiles[] = $fileCreated;
223
        } catch (ProcessFailedException $e) {
224
            throw new MockException(
225
                sprintf(
226
                    'Error to generate mock file with markdown-pp: %s, maybe markdown-pp is not installed',
227
                    $e->getMessage()
228
                )
229
            );
230
        }
231
    }
232
233
    /**
234
     * @return Finder
235
     */
236
    protected function getFilesToMock()
237
    {
238
        return $this->getFiles($this->mdPath, 'index.apib');
239
    }
240
241
    /**
242
     * @return Finder
243
     */
244
    protected function getFilesToDoc()
245
    {
246
        return $this->getFiles($this->mdPath, 'out.apib');
247
    }
248
249
    /**
250
     * @param string $path
251
     * @param string $filter
252
     * @return Finder
253
     */
254
    protected function getFiles($path, $filter)
255
    {
256
        $finder = new Finder();
257
        $files = $finder
258
            ->files()
259
            ->ignoreDotFiles(true)
260
            ->filter(function (SplFileInfo $file) use ($filter) {
261
                if ($file->getFilename() != $filter) {
262
                    return false;
263
                }
264
                return true;
265
            })
266
            ->in($path)->files();
267
268
        return $files;
269
    }
270
271
    protected function renderFilesInfo()
272
    {
273
        $this->output->writeln('<info>Files generated:</info>');
274
275
        $this->output->writeln('<fg=black;bg=cyan>Mock Files:</>');
276
        foreach ($this->compiledFiles as $nameFile) {
277
            $this->output->writeln($nameFile);
278
        }
279
280
        $this->output->writeln('<fg=black;bg=cyan>Doc Files:</>');
281
        foreach ($this->docCreatedFiles as $nameFile) {
282
            $this->output->writeln($nameFile);
283
        }
284
    }
285
286
    /**
287
     * @return bool
288
     */
289
    protected function hasGeneratedFiles()
290
    {
291
        return !empty($this->docCreatedFiles) && !empty($this->compiledFiles);
292
    }
293
}
294