Completed
Push — master ( d4d654...40e20e )
by Vladimir
04:35
created

CheckGeneratorCommand::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 2
dl 0
loc 4
ccs 0
cts 4
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * This file is part of the `tvi/monitor-bundle` project.
4
 *
5
 * (c) https://github.com/turnaev/monitor-bundle/graphs/contributors
6
 *
7
 * For the full copyright and license information, please view the LICENSE.md
8
 * file that was distributed with this source code.
9
 */
0 ignored issues
show
Coding Style introduced by
PHP version not specified
Loading history...
Coding Style introduced by
Missing @category tag in file comment
Loading history...
Coding Style introduced by
Missing @package tag in file comment
Loading history...
Coding Style introduced by
Missing @author tag in file comment
Loading history...
Coding Style introduced by
Missing @license tag in file comment
Loading history...
Coding Style introduced by
Missing @link tag in file comment
Loading history...
10
11
namespace Tvi\MonitorBundle\Command;
12
13
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
14
use Symfony\Component\Console\Command\Command;
15
use Symfony\Component\Console\Input\InputInterface;
16
use Symfony\Component\Console\Input\InputOption;
17
use Symfony\Component\Console\Output\OutputInterface;
18
use Symfony\Component\Console\Input\InputArgument;
19
use Symfony\Component\Finder\Finder;
20
use Symfony\Component\Finder\SplFileInfo;
21
use Symfony\Component\HttpKernel\Bundle\Bundle;
22
use Twig\Error\LoaderError;
23
use Twig\Loader\FilesystemLoader;
24
25
/**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
26
 * @author Vladimir Turnaev <[email protected]>
27
 */
0 ignored issues
show
Coding Style introduced by
Missing @category tag in class comment
Loading history...
Coding Style introduced by
Missing @package tag in class comment
Loading history...
Coding Style introduced by
Missing @license tag in class comment
Loading history...
Coding Style introduced by
Missing @link tag in class comment
Loading history...
28
class CheckGeneratorCommand extends Command
29
{
30
    const TPL_DIR = __DIR__.'/../Resources/generator/Check';
31
32
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
33
     * @var \Twig\Environment
34
     */
35
    private $twig;
0 ignored issues
show
Coding Style introduced by
Private member variable "twig" must be prefixed with an underscore
Loading history...
36
37
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
38
     * @var SplFileInfo[]
39
     */
40
    private $tpls;
0 ignored issues
show
Coding Style introduced by
Private member variable "tpls" must be prefixed with an underscore
Loading history...
41
42
    public function __construct(\Twig\Environment $twig, string $name = null)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function __construct()
Loading history...
43
    {
44
        parent::__construct($name);
45
        $this->twig = $twig;
46
    }
47
48
    /**
0 ignored issues
show
Coding Style introduced by
Doc comment is empty
Loading history...
49
     *
50
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
51
    protected function configure()
52
    {
53
        $this
54
            ->setName('tvi:monitor:generator:check')
55
            ->setDescription('Generates check plugin from tvi monitor template')
56
            ->addArgument('checker', InputArgument::REQUIRED, 'Check name')
57
            ->addOption('group', 'g',InputOption::VALUE_OPTIONAL, 'Check group')
58
            ->addOption('integration-test-src', null,InputOption::VALUE_OPTIONAL, 'Path to integration tests src', null)
59
            ->addOption('no-backup', 'b', InputOption::VALUE_NONE, 'Do not backup existing check files.')
60
            ->setHelp(<<<EOT
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
61
The <info>%command.name%</info> command generates check classes
62
from tvi monitor template:
63
64
* Create a check:
65
66
By default, the unmodified version of check is backed up and saved
67
To prevent this task from creating the backup file,
68
pass the <comment>--no-backup</comment> option:
69
  
70
  <info>Php %command.full_name% "TviMonitorBundle:Check\Example" [--group=...] [--no-backup]</info>
71
  <info>Php %command.full_name% ":Check\Example"</info>
72
  <info>Php %command.full_name% "Check\Example"</info>
73
74
EOT
75
            );
76
        ;
77
    }
78
79
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
80
     * @param InputInterface  $input
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
81
     * @param OutputInterface $output
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
82
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
83
    protected function interact(InputInterface $input, OutputInterface $output)
84
    {
85
        $this->twig->setLoader(new FilesystemLoader([self::TPL_DIR]));
86
87
        $fn = Finder::create();
88
        $tpls = $fn->in(self::TPL_DIR)->files()->getIterator();
89
        $this->tpls = iterator_to_array($tpls);
90
    }
91
92
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
93
     * @param InputInterface  $input
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
94
     * @param OutputInterface $output
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
95
     *
96
     * @return void
97
     * @throws \Twig_Error_Loader
98
     * @throws \Twig_Error_Runtime
99
     * @throws \Twig_Error_Syntax
100
     */
101
    protected function execute(InputInterface $input, OutputInterface $output)
102
    {
103
        $checker = $input->getArgument('checker');
104
        $noBackup = !$input->getOption('no-backup');
105
106
        $r = explode(':', $checker);
107
        @list($bundleName, $checkPath) = (count($r) == 1) ? [null, current($r)] : $r;
108
109
        /* @var $bundle Bundle */
110
        if(!$bundleName) {
0 ignored issues
show
Coding Style introduced by
Expected "if (...) {\n"; found "if(...) {\n"
Loading history...
111
            $defaultBundle = 'TviMonitorBundle';
112
            $bundle = $this->getApplication()->getKernel()->getBundle($defaultBundle);
0 ignored issues
show
Bug introduced by
The method getKernel() does not exist on Symfony\Component\Console\Application. It seems like you code against a sub-type of Symfony\Component\Console\Application such as Symfony\Bundle\FrameworkBundle\Console\Application. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

112
            $bundle = $this->getApplication()->/** @scrutinizer ignore-call */ getKernel()->getBundle($defaultBundle);
Loading history...
113
            $output->writeln(sprintf('<info>Use default bundle <comment>%s</comment></info>', $bundle->getNamespace()));
114
        } else {
115
            try {
116
117
                $bundle = $this->getApplication()->getKernel()->getBundle($bundleName);
118
            } catch (\InvalidArgumentException $e) {
119
                $output->writeln(sprintf('<error>%s</error>', $e->getMessage()));
120
            }
121
        }
122
123
        preg_match('#^(.*?)(\w+)$#', $checkPath, $m);
124
        list($checkNamespace, $checkName) =  [$m[1], $m[2]];
125
126
        $checkNamespace = preg_replace('#\\\$#', '', $checkNamespace);
127
        $bundleNamespace = $bundle->getNamespace();
128
129
        //NAMESPACE
130
        $NAMESPACE = sprintf('%s\%s\%s', $bundleNamespace, $checkNamespace, $checkName);
131
        $NAMESPACE = preg_replace('#\\\$#', '', $NAMESPACE);
132
133
        //SERVICE_PREFIX
134
        $SERVICE_PREFIX = preg_replace('#\\\#', "_", $bundleNamespace);
135
        $SERVICE_PREFIX = preg_replace('#bundle$#i', '', $SERVICE_PREFIX);
136
        $SERVICE_PREFIX = strtolower($SERVICE_PREFIX);
137
138
        //CHECK_NAME
139
        $CHECK_NAME = $checkName;
140
141
        //CHECK_ALIAS
142
        $CHECK_ALIAS = preg_replace('#([A-Z])#', '_\1', $checkName);
143
        $CHECK_ALIAS = preg_replace('#^_*#', '', $CHECK_ALIAS);
144
        $CHECK_ALIAS = strtolower($CHECK_ALIAS);
145
146
        //CHECK_GROUP
147
        $group = $input->getOption('group');
148
        $CHECK_GROUP = $group ? $group: $CHECK_ALIAS;
149
150
        $checkPath = sprintf('%s%s%s', $bundle->getPath(), DIRECTORY_SEPARATOR, $checkPath);
151
        $checkPath = str_replace('\\', DIRECTORY_SEPARATOR, $checkPath);
152
153
        if(is_dir($checkPath)) {
0 ignored issues
show
Coding Style introduced by
Expected "if (...) {\n"; found "if(...) {\n"
Loading history...
154
155
            if($noBackup && is_dir($checkPath)) {
0 ignored issues
show
Coding Style introduced by
Expected "if (...) {\n"; found "if(...) {\n"
Loading history...
156
                $output->writeln(sprintf('<info><error>Check %s exist</error>. Use --no-backup flag to rewrite</info>', $NAMESPACE));
157
                exit(1);
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
158
            } else {
159
                $output->writeln(sprintf('<info>Check <comment>%s</comment> exist rewrite them</info>', $NAMESPACE));
160
            }
161
        } else {
162
            @mkdir($checkPath, 0775, true) && !is_dir($checkPath);
163
        }
164
165
        foreach ($this->tpls as $f) {
166
167
            if(in_array($f->getBasename(), ['config.example.yml.twig', 'README.mdpp.twig'])) {
0 ignored issues
show
Coding Style introduced by
Expected "if (...) {\n"; found "if(...) {\n"
Loading history...
168
                continue;
169
            }
170
171
            /* @var SplFileInfo $f */
172
            $fName = $f->getBasename('.twig');
173
174
            if($fName == 'Test.php.integration') {
0 ignored issues
show
Coding Style introduced by
Expected "if (...) {\n"; found "if(...) {\n"
Loading history...
175
176
                $testPath = $input->getOption('integration-test-src');
177
                if(!$testPath) {
0 ignored issues
show
Coding Style introduced by
Expected "if (...) {\n"; found "if(...) {\n"
Loading history...
178
                    continue;
179
                } else {
180
                    $fName = $f->getBasename('.integration.twig');
181
182
                    $testPath = preg_replace('#///*$#', '', $testPath);
183
184
                    $fPath = sprintf('%s%s%s%s%s%s%s%s%s',
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
185
                        $bundle->getPath(),
186
                       DIRECTORY_SEPARATOR,
0 ignored issues
show
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 24 spaces, but found 23.
Loading history...
187
                        $testPath,
188
                        DIRECTORY_SEPARATOR,
189
                        'Test',
190
                        DIRECTORY_SEPARATOR,
191
                        $checkNamespace,
192
                        DIRECTORY_SEPARATOR,
193
                        $checkName
194
                        );
0 ignored issues
show
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 20 spaces, but found 24.
Loading history...
195
                    $fPath = preg_replace('#\\\+#', '/', $fPath);
196
197
                    if(is_dir($fPath)) {
0 ignored issues
show
Coding Style introduced by
Expected "if (...) {\n"; found "if(...) {\n"
Loading history...
198
                        if($noBackup && is_dir($fPath)) {
0 ignored issues
show
Coding Style introduced by
Expected "if (...) {\n"; found "if(...) {\n"
Loading history...
199
                            $output->writeln(sprintf('<info>Tests for <error>check %s exist</error>. Use --no-backup flag to rewrite</info>', $NAMESPACE));
200
                            continue;
201
                        } else {
202
                            $output->writeln(sprintf('<info>Tests for check <comment>%s</comment> exist rewrite them.</info>', $NAMESPACE));
203
                        }
204
                    } else {
205
                        @mkdir($fPath, 0775, true) && !is_dir($fPath);
206
                    }
207
                }
208
                $TEST_NAMESPACE = sprintf('%s\%s\%s\%s', $bundleNamespace,'Test', $checkNamespace, $checkName);
209
210
                $tplData = [
211
                    'NAMESPACE'      => $TEST_NAMESPACE,
212
                    'SERVICE_REPFIX' => $SERVICE_PREFIX,
213
                    'CHECK_NAME'    =>  $CHECK_NAME,
214
                    'CHECK_ALIAS'    => $CHECK_ALIAS,
215
                    'CHECK_GROUP'    => $CHECK_GROUP,
216
                ];
217
                $res = $this->twig->render($f->getRelativePathname(), $tplData);
218
219
                $path = sprintf('%s%s%s', $fPath, DIRECTORY_SEPARATOR, $fName);
220
221
                file_put_contents($path, $res);
222
223
                $this->createFile($fPath,'config.example.yml.twig','config.yml', $tplData);
224
225
            } else {
226
                $path = sprintf('%s%s%s', $checkPath, DIRECTORY_SEPARATOR, $fName);
227
228
                $tplData = [
229
                    'NAMESPACE'      => $NAMESPACE,
230
                    'SERVICE_REPFIX' => $SERVICE_PREFIX,
231
                    'CHECK_NAME'    =>  $CHECK_NAME,
232
                    'CHECK_ALIAS'    => $CHECK_ALIAS,
233
                    'CHECK_GROUP'    => $CHECK_GROUP,
234
                ];
235
                $res = $this->twig->render($f->getRelativePathname(), $tplData);
236
237
                file_put_contents($path, $res);
238
239
                $this->createFile($checkPath,'config.example.yml.twig','config.example.yml', $tplData);
240
                $this->createFile($checkPath,'README.mdpp.twig','README.mdpp', $tplData);
241
            }
242
        }
243
    }
244
245
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
246
     * @param string $basePath
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
247
     * @param string $from
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
248
     * @param string $to
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
249
     * @param array  $tplData
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
250
     *
251
     * @throws \Twig_Error_Loader
252
     * @throws \Twig_Error_Runtime
253
     * @throws \Twig_Error_Syntax
254
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
255
    private function createFile(string $basePath, string $from, string $to, array $tplData)
0 ignored issues
show
Coding Style introduced by
Private method name "CheckGeneratorCommand::createFile" must be prefixed with an underscore
Loading history...
256
    {
257
        $r = array_filter($this->tpls, function (SplFileInfo $f) use($from) {
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
Coding Style introduced by
Expected 1 space after USE keyword; found 0
Loading history...
258
            return $f->getBasename() == $from;
259
        });
0 ignored issues
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
260
261
        /* @var  SplFileInfo $f */
262
        $f = current($r);
263
        if($f) {
0 ignored issues
show
introduced by
$f is of type Symfony\Component\Finder\SplFileInfo, thus it always evaluated to true. If $f can have other possible types, add them to src/Command/CheckGeneratorCommand.php:261
Loading history...
Coding Style introduced by
Expected "if (...) {\n"; found "if(...) {\n"
Loading history...
264
            $res = $this->twig->render($f->getRelativePathname(), $tplData);
265
            $savePath = sprintf('%s%s%s', $basePath, DIRECTORY_SEPARATOR, $to);
266
            file_put_contents($savePath, $res);
267
        }
268
    }
269
}
270