Completed
Push — master ( 181da6...1dd547 )
by Vladimir
04:19
created

CheckGeneratorCommand::interact()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 5
dl 0
loc 8
ccs 0
cts 7
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
crap 2
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
23
/**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
24
 * @author Vladimir Turnaev <[email protected]>
25
 */
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...
26
class CheckGeneratorCommand extends ContainerAwareCommand
27
{
28
    const TPL_DIR = __DIR__.'/../Resources/generator/Check';
29
30
    protected function configure()
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function configure()
Loading history...
31
    {
32
        $this
33
            ->setName('tvi:monitor:generator:check')
34
            ->setDescription('Generates check plugin from tvi monitor template')
35
            ->addArgument('name', InputArgument::REQUIRED, 'Check name')
36
            ->addOption('group', 'g',InputOption::VALUE_OPTIONAL, 'Check group')
37
            ->addOption('integration-test-src', null,InputOption::VALUE_OPTIONAL, 'Path to integration tests src', null)
38
            ->addOption('no-backup', 'b', InputOption::VALUE_NONE, 'Do not backup existing check files.')
39
            ->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...
40
The <info>%command.name%</info> command generates check classes
41
from tvi monitor template:
42
43
* Create a check:
44
45
By default, the unmodified version of check is backed up and saved
46
To prevent this task from creating the backup file,
47
pass the <comment>--no-backup</comment> option:
48
  
49
  <info>php %command.full_name% "TviMonitorBundle:Check\Example" [--group=...] [--no-backup]</info>
50
  <info>php %command.full_name% ":Check\Example"</info>
51
  <info>php %command.full_name% "Check\Example"</info>
52
53
EOT
54
            );
55
        ;
56
    }
57
58
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
59
     * @var \Twig\Environment
60
     */
61
    private $twig;
0 ignored issues
show
Coding Style introduced by
Private member variable "twig" must be prefixed with an underscore
Loading history...
62
63
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
64
     * @var SplFileInfo[]
65
     */
66
    private $tpls;
0 ignored issues
show
Coding Style introduced by
Private member variable "tpls" must be prefixed with an underscore
Loading history...
67
68
    protected function interact(InputInterface $input, OutputInterface $output)
0 ignored issues
show
Coding Style introduced by
Missing doc comment for function interact()
Loading history...
69
    {
70
        $this->twig = $this->getContainer()->get('twig');
71
        $this->twig->setLoader(new \Twig_Loader_Filesystem([__DIR__.'/../Resources/generator/Check/']));
72
73
        $fn = Finder::create();
74
        $tpls = $fn->in(self::TPL_DIR)->files()->getIterator();
75
        $this->tpls = iterator_to_array($tpls);
76
    }
77
78
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
79
     * @param InputInterface  $input
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
80
     * @param OutputInterface $output
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
81
     *
82
     * @return void
83
     * @throws \Twig_Error_Loader
84
     * @throws \Twig_Error_Runtime
85
     * @throws \Twig_Error_Syntax
86
     */
87
    protected function execute(InputInterface $input, OutputInterface $output)
88
    {
89
        $name = $input->getArgument('name');
90
91
        $r = explode(':', $name);
92
        @list($bundle, $checkPath) = (count($r) == 1) ? [null, current($r)] : $r;
93
94
        /* @var $bundle Bundle */
95
        if(!$bundle) {
0 ignored issues
show
introduced by
$bundle is of type Symfony\Component\HttpKernel\Bundle\Bundle, thus it always evaluated to true. If $bundle can have other possible types, add them to src/Command/CheckGeneratorCommand.php:94
Loading history...
Coding Style introduced by
Expected "if (...) {\n"; found "if(...) {\n"
Loading history...
96
            $defaultBundle = 'TviMonitorBundle';
0 ignored issues
show
Unused Code introduced by
The assignment to $defaultBundle is dead and can be removed.
Loading history...
97
            $bundle = $this->getApplication()->getKernel()->getBundle('TviMonitorBundle');
98
            $output->writeln(sprintf('<info>Use default bundle <comment>%s</comment></info>', $bundle->getNamespace()));
99
        } else {
100
            try {
101
                $bundle = $this->getApplication()->getKernel()->getBundle($bundle);
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

101
                $bundle = $this->getApplication()->/** @scrutinizer ignore-call */ getKernel()->getBundle($bundle);
Loading history...
102
            } catch (\InvalidArgumentException $e) {
103
                $output->writeln(sprintf('<error>%s</error>', $e->getMessage()));
104
            }
105
        }
106
107
        preg_match('#^(.*?)(\w+)$#', $checkPath, $m);
108
        list($checkNamespace, $checkName) =  [$m[1], $m[2]];
109
110
        $checkNamespace = preg_replace('#\\\$#', '', $checkNamespace);
111
        $bundleNamespace = $bundle->getNamespace();
112
113
        $NAMESPACE = sprintf('%s\%s\%s', $bundleNamespace, $checkNamespace, $checkName);
114
        $NAMESPACE = preg_replace('#\\\$#', '', $NAMESPACE);
115
116
        $SERVICE_PREFIX = preg_replace('#\\\#', "_", $bundleNamespace);
117
        $SERVICE_PREFIX = preg_replace('#bundle$#i', '', $SERVICE_PREFIX);
118
        $SERVICE_PREFIX = strtolower($SERVICE_PREFIX);
119
120
        $CHECK_NAME = $checkName;
121
122
        $CHECK_ALIAS = preg_replace('#([A-Z])#', '_\1', $checkName);
123
        $CHECK_ALIAS = preg_replace('#^_*#', '', $CHECK_ALIAS);
124
        $CHECK_ALIAS = strtolower($CHECK_ALIAS);
125
126
        $group = $input->getOption('group');
127
        $CHECK_GROUP = $group ? $group: $CHECK_ALIAS;
128
129
        //v($NAMESPACE, $SERVICE_PREFIX, $CHECK_ALIAS, $checkName); exit;
130
131
        $checkPath = sprintf('%s%s%s', $bundle->getPath(), DIRECTORY_SEPARATOR, $checkPath);
132
        $checkPath = str_replace('\\', DIRECTORY_SEPARATOR, $checkPath);
133
134
        $noBackup = !$input->getOption('no-backup');
135
136
        if(is_dir($checkPath)) {
0 ignored issues
show
Coding Style introduced by
Expected "if (...) {\n"; found "if(...) {\n"
Loading history...
137
138
            if($noBackup && is_dir($checkPath)) {
0 ignored issues
show
Coding Style introduced by
Expected "if (...) {\n"; found "if(...) {\n"
Loading history...
139
                $output->writeln(sprintf('<info><error>Check %s exist</error>. Use --no-backup flag to rewrite</info>', $NAMESPACE));
140
                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...
141
            } else {
142
                $output->writeln(sprintf('<info>Check <comment>%s</comment> exist rewrite them</info>', $NAMESPACE));
143
            }
144
        } else {
145
            @mkdir($checkPath, 0775, true) && !is_dir($checkPath);
146
        }
147
148
149
150
151
        foreach ($this->tpls as $f) {
152
153
            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...
154
                continue;
155
            }
156
157
            /* @var SplFileInfo $f */
158
            $fName = $f->getBasename('.twig');
159
160
            if($fName == 'Test.php.integration') {
0 ignored issues
show
Coding Style introduced by
Expected "if (...) {\n"; found "if(...) {\n"
Loading history...
161
162
                $testPath = $input->getOption('integration-test-src');
163
                if(!$testPath) {
0 ignored issues
show
Coding Style introduced by
Expected "if (...) {\n"; found "if(...) {\n"
Loading history...
164
                    continue;
165
                } else {
166
                    $fName = $f->getBasename('.integration.twig');
167
168
                    $testPath = preg_replace('#///*$#', '', $testPath);
169
170
                    $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...
171
                        $bundle->getPath(),
172
                       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...
173
                        $testPath,
174
                        DIRECTORY_SEPARATOR,
175
                        'Test',
176
                        DIRECTORY_SEPARATOR,
177
                        $checkNamespace,
178
                        DIRECTORY_SEPARATOR,
179
                        $checkName
180
                        );
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...
181
182
                    if(is_dir($fPath)) {
0 ignored issues
show
Coding Style introduced by
Expected "if (...) {\n"; found "if(...) {\n"
Loading history...
183
                        if($noBackup && is_dir($fPath)) {
0 ignored issues
show
Coding Style introduced by
Expected "if (...) {\n"; found "if(...) {\n"
Loading history...
184
                            $output->writeln(sprintf('<info>Tests for <error>check %s exist</error>. Use --no-backup flag to rewrite</info>', $NAMESPACE));
185
                            continue;
186
                        } else {
187
                            $output->writeln(sprintf('<info>Tests for check <comment>%s</comment> exist rewrite them.</info>', $NAMESPACE));
188
                        }
189
                    } else {
190
                        @mkdir($fPath, 0775, true) && !is_dir($fPath);
191
                    }
192
                }
193
                $TEST_NAMESPACE = sprintf('%s\%s\%s\%s', $bundleNamespace,'Test', $checkNamespace, $checkName);
194
195
                $tplData = [
196
                    'NAMESPACE'      => $TEST_NAMESPACE,
197
                    'SERVICE_REPFIX' => $SERVICE_PREFIX,
198
                    'CHECK_NAME'    =>  $CHECK_NAME,
199
                    'CHECK_ALIAS'    => $CHECK_ALIAS,
200
                    'CHECK_GROUP'    => $CHECK_GROUP,
201
                ];
202
                $res = $this->twig->render($f->getRelativePathname(), $tplData);
203
204
                $path = sprintf('%s%s%s', $fPath, DIRECTORY_SEPARATOR, $fName);
205
                file_put_contents($path, $res);
206
                //'config.example.yml.twig', 'README.mdpp.twig'
207
                $this->createConf($fPath, $tplData, 'config.example.yml.twig', 'config.yml');
0 ignored issues
show
Unused Code introduced by
The call to Tvi\MonitorBundle\Comman...orCommand::createConf() has too many arguments starting with 'config.example.yml.twig'. ( Ignorable by Annotation )

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

207
                $this->/** @scrutinizer ignore-call */ 
208
                       createConf($fPath, $tplData, 'config.example.yml.twig', 'config.yml');

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
208
                $this->createConf($fPath, $tplData, 'README.mdpp.twig', 'README.mdpp');
209
210
            } else {
211
                $path = sprintf('%s%s%s', $checkPath, DIRECTORY_SEPARATOR, $fName);
212
213
                $tplData = [
214
                    'NAMESPACE'      => $NAMESPACE,
215
                    'SERVICE_REPFIX' => $SERVICE_PREFIX,
216
                    'CHECK_NAME'    =>  $CHECK_NAME,
217
                    'CHECK_ALIAS'    => $CHECK_ALIAS,
218
                    'CHECK_GROUP'    => $CHECK_GROUP,
219
                ];
220
                $res = $this->twig->render($f->getRelativePathname(), $tplData);
221
222
                file_put_contents($path, $res);
223
224
225
                $this->createConf($checkPath, $tplData, 'config.example.yml.twig', 'config.example.yml');
226
                $this->createConf($checkPath, $tplData, 'README.mdpp.twig', 'README.mdpp');
227
            }
228
        }
229
    }
230
231
    private function createConf($basePath, $tplData)
0 ignored issues
show
Coding Style introduced by
Private method name "CheckGeneratorCommand::createConf" must be prefixed with an underscore
Loading history...
Coding Style introduced by
Missing doc comment for function createConf()
Loading history...
232
    {
233
        v($basePath, $tplData);
0 ignored issues
show
Bug introduced by
The function v was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

233
        /** @scrutinizer ignore-call */ 
234
        v($basePath, $tplData);
Loading history...
234
//        $r = array_filter($tpls, function (SplFileInfo $f) {
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected at least 8 spaces, found 0
Loading history...
235
//            return $f->getBasename() == 'config.example.yml.twig';
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected at least 8 spaces, found 0
Loading history...
236
//        });
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected at least 8 spaces, found 0
Loading history...
237
//
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected at least 8 spaces, found 0
Loading history...
238
//        $f = current($r);
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected at least 8 spaces, found 0
Loading history...
239
//        $res = $this->twig->render($f->getRelativePathname(), $tplData);
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected at least 8 spaces, found 0
Loading history...
240
//
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected at least 8 spaces, found 0
Loading history...
241
//        $fName = $f->getBasename('.example.yml.twig');
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected at least 8 spaces, found 0
Loading history...
242
//        $path = sprintf('%s%s%s%s', $basePath, DIRECTORY_SEPARATOR, $fName, '.yml');
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected at least 8 spaces, found 0
Loading history...
243
//        file_put_contents($path, $res);
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected at least 8 spaces, found 0
Loading history...
244
    }
245
}
246