CompileCommand::getFiles()   A
last analyzed

Complexity

Conditions 2
Paths 1

Size

Total Lines 16
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 11
nc 1
nop 2
1
<?php
2
3
/**
4
 * MIT License
5
 *
6
 * Copyright (c) 2017 Bernardo Secades
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::REQUIRED,
62
                'Base folder to start to search files index.apib'
63
            );
64
    }
65
    /**
66
     * @param InputInterface  $input
67
     * @param OutputInterface $output
68
     * @return int
69
     */
70
    protected function execute(InputInterface $input, OutputInterface $output)
71
    {
72
        if (function_exists('xdebug_disable')) {
73
            xdebug_disable();
74
        }
75
76
        $this->mdPath = $input->getArgument('path');
77
78
        $this->createMockFiles();
79
        $output->writeln('');
80
        $this->createDocFiles();
81
        $output->writeln('');
82
83
        return $this->renderFilesInfo();
84
    }
85
86
    /**
87
     * @param InputInterface  $input
88
     * @param OutputInterface $output
89
     */
90
    protected function initialize(InputInterface $input, OutputInterface $output)
91
    {
92
        $this->output = $output;
93
    }
94
95 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...
96
    {
97
        $files = $this->getFilesToMock();
98
99
        if ($files->count()) {
100
            $this->output->writeln('<info>Compiling "apib" files to mock</info>');
101
            $progress = new ProgressBar($this->output, count($files));
102
            $progress->setBarCharacter('<fg=magenta>=</>');
103
            $progress->setProgressCharacter("\xF0\x9F\x8D\xBA");
104
105
            foreach ($files as $file) {
106
                $this->compileToMock($file->getRealPath());
107
                $progress->advance();
108
            }
109
110
            $progress->finish();
111
        }
112
    }
113
114 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...
115
    {
116
        $files = $this->getFilesToDoc();
117
118
        if ($files->count()) {
119
            $this->output->writeln('<info>Creating documentation from mock files compiled</info>');
120
            $progress = new ProgressBar($this->output, count($files));
121
            $progress->setBarCharacter('<fg=magenta>=</>');
122
            $progress->setProgressCharacter("\xF0\x9F\x8D\xBA");
123
124
            foreach ($files as $file) {
125
                $this->compileToDoc($file->getRealPath());
126
                $progress->advance();
127
            }
128
129
            $progress->finish();
130
        }
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
    /**
272
     * @return int
273
     */
274
    protected function renderFilesInfo()
275
    {
276
        if ($this->hasGeneratedFiles()) {
277
278
            $this->output->writeln('<info>Files generated:</info>');
279
280
            $this->output->writeln('<fg=black;bg=cyan>Mock Files:</>');
281
            foreach ($this->compiledFiles as $nameFile) {
282
                $this->output->writeln($nameFile);
283
            }
284
285
            $this->output->writeln('<fg=black;bg=cyan>Doc Files:</>');
286
            foreach ($this->docCreatedFiles as $nameFile) {
287
                $this->output->writeln($nameFile);
288
            }
289
290
            return 0;
291
        }
292
293
        $this->output->writeln('<fg=black;bg=red>There are not index files to generate mock or doc files</>');
294
295
        return 1;
296
    }
297
298
    /**
299
     * @return bool
300
     */
301
    protected function hasGeneratedFiles()
302
    {
303
        return !empty($this->docCreatedFiles) && !empty($this->compiledFiles);
304
    }
305
}
306