Passed
Push — develop ( f18770...47bbaf )
by Andrea
10:42
created

PannelloAmministrazioneController::phpunittest()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 31
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
cc 4
eloc 21
nc 4
nop 1
dl 0
loc 31
rs 9.584
c 0
b 0
f 0
ccs 0
cts 0
cp 0
crap 20
1
<?php
2
3
namespace Cdf\PannelloAmministrazioneBundle\Controller;
4
5
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
6
use Symfony\Component\HttpFoundation\Request;
7
use Symfony\Component\HttpFoundation\Response;
8
use Symfony\Component\Finder\Finder;
9
use Symfony\Component\Filesystem\Filesystem;
10
use Symfony\Component\Process\Process;
11
use Fi\OsBundle\DependencyInjection\OsFunctions;
12
use Symfony\Component\Lock\LockFactory;
13
use Symfony\Component\Lock\Store\FlockStore;
14
use Symfony\Component\Lock\LockInterface;
15
use Cdf\PannelloAmministrazioneBundle\Utils\Utility as Pautils;
16
use Cdf\PannelloAmministrazioneBundle\Utils\ProjectPath;
17
use Cdf\PannelloAmministrazioneBundle\Utils\Commands as Pacmd;
18
use Cdf\BiCoreBundle\Utils\Api\ApiUtils;
19
use Doctrine\ORM\EntityManagerInterface as EM;
20
21
/**
22
 * Suppress all warnings from these two rules.
23
 *
24
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
25
 */
26
27
class PannelloAmministrazioneController extends AbstractController
28
{
29
    private ProjectPath $apppaths;
30
    private Pacmd $pacommands;
31
    private Pautils $pautils;
32
    protected LockInterface $locksystem;
33
    protected LockFactory $factory;
34
    private string $appname;
35
    private string $lockfile;
36
    private EM $em;
37
38 1
    public function __construct(string $appname, string $lockfile, ProjectPath $projectpath, Pacmd $pacommands, Pautils $pautils, EM $em)
39
    {
40 1
        $store = new FlockStore(sys_get_temp_dir());
41 1
        $factory = new LockFactory($store);
42 1
        $this->locksystem = $factory->createLock('pannelloamministrazione-command');
43 1
        $this->locksystem->release();
44 1
        $this->appname = $appname;
45 1
        $this->lockfile = $lockfile;
46 1
        $this->apppaths = $projectpath;
47 1
        $this->pacommands = $pacommands;
48 1
        $this->pautils = $pautils;
49 1
        $this->em = $em;
50 1
    }
51
52
    /**
53
     *
54
     * @return array<mixed>
55
     */
56 1
    private function findEntities() : array
57
    {
58 1
        $entitiesprogetto = array();
59 1
        $prefix = 'App\\Entity\\';
60 1
        $prefixBase = 'Base';
61 1
        $entities = $this->em->getConfiguration()->getMetadataDriverImpl()->getAllClassNames();
62
        // compute additional API models since external bundles
63 1
        $additionalEntities = $this->findAPIModels();
64 1
        foreach ($entities as $entity) {
65 1
            if (substr($entity, 0, strlen($prefix)) == $prefix) {
66 1
                if (substr(substr($entity, strlen($prefix)), 0, strlen($prefixBase)) != $prefixBase) {
67 1
                    $entitiesprogetto[] = substr($entity, strlen($prefix));
68
                }
69
            }
70
        }
71
        // merge of found arrays
72 1
        $outcomes = array_merge($entitiesprogetto, $additionalEntities);
73 1
        return $outcomes;
74
    }
75
76
    /**
77
     * It looks for Models existent into included external bundles.
78
     * It uses ApiUtils in order to know where to search and what look for.
79
     *
80
     * @return array<mixed>
81
     */
82 1
    private function findAPIModels(): array
83
    {
84 1
        $apiUtil = new ApiUtils();
85 1
        $apiUtil->setRootDir($this->apppaths->getVendorPath());
86 1
        return $apiUtil->apiModels();
87
    }
88
89 1
    public function index() : Response
90
    {
91 1
        $finder = new Finder();
92 1
        $fs = new Filesystem();
93
94 1
        $projectDir = $this->apppaths->getRootPath();
95 1
        $docDir = $this->apppaths->getDocPath();
96
97 1
        $mwbs = array();
98
99 1
        if ($fs->exists($docDir)) {
100 1
            $finder->in($docDir)->files()->name('*.mwb');
101 1
            foreach ($finder as $file) {
102 1
                $mwbs[] = $file->getBasename();
103
            }
104
        }
105 1
        sort($mwbs);
106 1
        $svn = $fs->exists($projectDir.'/.svn');
107 1
        $git = $fs->exists($projectDir.'/.git');
108 1
        if (!OsFunctions::isWindows()) {
109 1
            $delcmd = 'rm -rf';
110 1
            $setfilelock = 'touch '.$this->lockfile;
111 1
            $remfilelock = 'rm '.$this->lockfile;
112 1
            $windows = false;
113
        } else {
114
            // @codeCoverageIgnoreStart
115
            $delcmd = 'del';
116
            $setfilelock = 'echo $null >> '.$this->lockfile;
117
            $remfilelock = 'del '.$this->lockfile;
118
            $windows = true;
119
            // @codeCoverageIgnoreEnd
120
        }
121 1
        $dellogsfiles = $delcmd.' '.$this->apppaths->getLogsPath().DIRECTORY_SEPARATOR.'*';
122 1
        $delcacheprodfiles = $delcmd.' '.$this->apppaths->getCachePath().DIRECTORY_SEPARATOR.'prod'.DIRECTORY_SEPARATOR.'*';
123 1
        $delcachedevfiles = $delcmd.' '.$this->apppaths->getCachePath().DIRECTORY_SEPARATOR.'dev'.DIRECTORY_SEPARATOR.'*';
124 1
        $setmaintenancefile = $setfilelock;
125 1
        $remmaintenancefile = $remfilelock;
126
127
        $comandishell = array(
128 1
            array('text' => $this->fixSlash($dellogsfiles), 'link' => '#'),
129 1
            array('text' => $this->fixSlash($delcacheprodfiles), 'link' => '#'),
130 1
            array('text' => $this->fixSlash($delcachedevfiles), 'link' => '#'),
131 1
            array('text' => $this->fixSlash($setmaintenancefile), 'link' => '#'),
132 1
            array('text' => $this->fixSlash($remmaintenancefile), 'link' => '#'),
133
                //array("text"=>"prova", "link"=>"#"),
134
        );
135 1
        $composerinstall = '';
136 1
        if (false == $windows) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
137 1
            $composerinstall = $composerinstall.' cd '.$projectDir.' && composer install --no-dev --optimize-autoloader --no-interaction 2>&1';
138 1
            $sed = "sed -i -e 's/cercaquestastringa/sostituisciconquestastringa/g' ".$projectDir.'/.env';
139 1
            $comandishell[] = array('text' => $composerinstall, 'link' => '#');
140 1
            $comandishell[] = array('text' => $sed, 'link' => '#');
141
        }
142
143
        $comandisymfony = array(
144 1
            array('text' => 'list', 'link' => '#'),
145
            array('text' => 'cache:clear --env=prod --no-debug', 'link' => '#'),
146
            array('text' => 'fos:user:create admin pass [email protected]', 'link' => '#'),
147
            array('text' => 'fos:user:promote username ROLE_SUPER_ADMIN', 'link' => '#'),
148 1
            array('text' => "assets:install $projectDir/public", 'link' => '#'),
149
            array('text' => 'pannelloamministrazione:checkgitversion', 'link' => '#'),
150
        );
151
152 1
        $entities = $this->findEntities();
153 1
        sort($entities);
154
155
        $twigparms = array(
156 1
            'svn' => $svn, 'git' => $git, 'mwbs' => $mwbs, 'entities' => $entities,
157 1
            'rootdir' => $this->fixSlash($projectDir),
158 1
            'comandishell' => $comandishell,
159 1
            'comandisymfony' => $comandisymfony,
160 1
            'iswindows' => $windows,
161 1
            'appname' => $this->appname,
162
        );
163
164 1
        return $this->render('@PannelloAmministrazione/PannelloAmministrazione/index.html.twig', $twigparms);
165
    }
166
167 1
    private function fixSlash(string $path) : string
168
    {
169 1
        return str_replace('\\', '\\\\', $path);
170
    }
171
172
    private function getLockMessage() : string
173
    {
174
        return "<h2 style='color: orange;'>E' già in esecuzione un comando, riprova tra qualche secondo!</h2>";
175
    }
176
177 1
    public function aggiornaSchemaDatabase(): Response
178
    {
179 1
        if (!$this->locksystem->acquire()) {
180
            return new Response($this->getLockMessage());
181
        } else {
182 1
            $this->locksystem->acquire();
183 1
            $command = $this->pacommands;
184 1
            $result = $command->aggiornaSchemaDatabase();
185
186 1
            $this->locksystem->release();
187 1
            if (0 != $result['errcode']) {
188
                $twigparms = array('errcode' => $result['errcode'], 'command' => $result['command'], 'message' => $result['message']);
189
                $view = $this->renderView('@PannelloAmministrazione/PannelloAmministrazione/outputcommand.html.twig', $twigparms);
190
191
                return new Response($view, 500);
192
            } else {
193 1
                $twigparms = array('errcode' => $result['errcode'], 'command' => $result['command'], 'message' => $result['message']);
194
195 1
                return $this->render('@PannelloAmministrazione/PannelloAmministrazione/outputcommand.html.twig', $twigparms);
196
            }
197
        }
198
    }
199
200
    /* FORMS */
201
202
    /**
203
     * Generate form item, controllers and twigs for the given entity/model
204
     */
205 1
    public function generateFormCrud(Request $request) : Response
206
    {
207 1
        if (!$this->locksystem->acquire()) {
208
            return new Response($this->getLockMessage());
209
        } else {
210 1
            $entityform = $request->get('entityform');
211 1
            $generatemplate = 'true' === $request->get('generatemplate') ? true : false;
212 1
            $this->locksystem->acquire();
213
214
            //we are working with an API?
215 1
            $isApi = false;
216
            //verify if provided string belongs to an API model
217 1
            if (\str_contains($entityform, '(API)')) {
0 ignored issues
show
Bug introduced by
It seems like $entityform can also be of type null; however, parameter $haystack of str_contains() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

217
            if (\str_contains(/** @scrutinizer ignore-type */ $entityform, '(API)')) {
Loading history...
218
                $isApi = true;
219
                $entityform = trim(\str_replace('(API)', '', $entityform));
220
            }
221
222
            // Setup an utility pack of commands (Commands.php)
223 1
            $command = $this->pacommands;
224 1
            $result = $command->generateFormCrud($entityform, $generatemplate, $isApi);
225
226 1
            $this->locksystem->release();
227
            //$retcc = '';
228 1
            if ($result['errcode'] < 0) {
229
                $twigparms = array('errcode' => $result['errcode'], 'command' => 'Generazione Form Crud', 'message' => $result['message']);
230
231
                return new Response(
232
                    $this->renderView('@PannelloAmministrazione/PannelloAmministrazione/outputcommand.html.twig', $twigparms),
233
                    500
234
                );
235
            } else {
236
                //$retcc = $command->clearCacheEnv($this->get('kernel')->getEnvironment());
237
            }
238 1
            $twigparms = array('errcode' => $result['errcode'], 'command' => $result['command'], 'message' => $result['message']);
239
240 1
            return $this->render('@PannelloAmministrazione/PannelloAmministrazione/outputcommand.html.twig', $twigparms);
241
        }
242
    }
243
244
    /* ENTITIES */
245
246 1
    public function generateEntity(Request $request) : Response
247
    {
248 1
        if (!$this->locksystem->acquire()) {
249
            return new Response($this->getLockMessage());
250
        } else {
251 1
            $this->locksystem->acquire();
252 1
            $wbFile = $request->get('file');
253 1
            $command = $this->pacommands;
254 1
            $result = $command->generateEntity($wbFile);
0 ignored issues
show
Bug introduced by
It seems like $wbFile can also be of type null; however, parameter $wbFile of Cdf\PannelloAmministrazi...mands::generateEntity() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

254
            $result = $command->generateEntity(/** @scrutinizer ignore-type */ $wbFile);
Loading history...
255 1
            $twigparms = array('errcode' => $result['errcode'], 'command' => $result['command'], 'message' => $result['message']);
0 ignored issues
show
Unused Code introduced by
The assignment to $twigparms is dead and can be removed.
Loading history...
256 1
            $this->locksystem->release();
257 1
            if (0 != $result['errcode']) {
258 1
                $twigparms = array('errcode' => $result['errcode'], 'command' => $result['command'], 'message' => $result['message']);
259 1
                $view = $this->renderView('@PannelloAmministrazione/PannelloAmministrazione/outputcommand.html.twig', $twigparms);
260
261 1
                return new Response($view, 500);
262
            } else {
263 1
                $twigparms = array('errcode' => $result['errcode'], 'command' => $result['command'], 'message' => $result['message']);
264
265 1
                return $this->render('@PannelloAmministrazione/PannelloAmministrazione/outputcommand.html.twig', $twigparms);
266
            }
267
        }
268
    }
269
270
    /* VCS (GIT,SVN) */
271
272
    /**
273
     * @codeCoverageIgnore
274
     */
275
    public function getVcs() : Response
276
    {
277
        set_time_limit(0);
278
        $this->apppaths = $this->apppaths;
279
        if (!$this->locksystem->acquire()) {
280
            return new Response($this->getLockMessage());
281
        } else {
282
            $this->locksystem->acquire();
283
            $command = $this->pacommands;
284
            $result = $command->getVcs();
285
            $this->locksystem->release();
286
            $twigparms = array('errcode' => $result['errcode'], 'command' => $result['command'], 'message' => $result['message']);
287
288
            return $this->render('@PannelloAmministrazione/PannelloAmministrazione/outputcommand.html.twig', $twigparms);
289
        }
290
    }
291
292
    /* CLEAR CACHE */
293
294
    /**
295
     * Suppress PMD warnings per exit.
296
     *
297
     * @//SuppressWarnings(PHPMD)
298
     */
299
    public function clearCache(Request $request) : Response
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed. ( Ignorable by Annotation )

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

299
    public function clearCache(/** @scrutinizer ignore-unused */ Request $request) : Response

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
300
    {
301
        set_time_limit(0);
302
        if (!$this->locksystem->acquire()) {
303
            return new Response($this->getLockMessage());
304
        } else {
305
            $this->locksystem->acquire();
306
            $command = $this->pacommands;
307
            $result = $command->clearcache();
308
309
            $this->locksystem->release();
310
311
            if (0 != $result['errcode']) {
312
                $twigparms = array('errcode' => $result['errcode'], 'command' => $result['command'], 'message' => $result['message']);
313
                $view = $this->renderView('@PannelloAmministrazione/PannelloAmministrazione/outputcommand.html.twig', $twigparms);
314
315
                return new Response($view, 500);
316
            } else {
317
                $twigparms = array('errcode' => $result['errcode'], 'command' => $result['command'], 'message' => $result['message']);
318
319
                return $this->render('@PannelloAmministrazione/PannelloAmministrazione/outputcommand.html.twig', $twigparms);
320
            }
321
        }
322
    }
323
324
    /* CLEAR CACHE */
325
326 1
    public function symfonyCommand(Request $request) : Response
327
    {
328 1
        set_time_limit(0);
329
330 1
        $simfonycommand = $request->get('symfonycommand');
331 1
        if (!$this->locksystem->acquire()) {
332
            return new Response($this->getLockMessage());
333
        } else {
334 1
            $this->locksystem->acquire();
335 1
            $this->apppaths = $this->apppaths;
336 1
            $pammutils = $this->pautils;
337 1
            $command = $this->apppaths->getConsoleExecute().' '.$simfonycommand;
338 1
            $result = $pammutils->runCommand($command);
339
340 1
            $this->locksystem->release();
341 1
            if (0 != $result['errcode']) {
342 1
                $twigparms = array('errcode' => $result['errcode'], 'command' => $result['command'], 'message' => $result['message']);
343 1
                $view = $this->renderView('@PannelloAmministrazione/PannelloAmministrazione/outputcommand.html.twig', $twigparms);
344
345 1
                return new Response($view, 500);
346
            } else {
347 1
                $twigparms = array('errcode' => $result['errcode'], 'command' => $result['command'], 'message' => $result['message']);
348
349 1
                return $this->render('@PannelloAmministrazione/PannelloAmministrazione/outputcommand.html.twig', $twigparms);
350
            }
351
        }
352
    }
353
354
    /**
355
     * Suppress PMD warnings per exit.
356
     *
357
     * @SuppressWarnings(PHPMD)
358
     */
359 1
    public function unixCommand(Request $request): Response
360
    {
361 1
        set_time_limit(0);
362 1
        $pammutils = $this->pautils;
363 1
        $unixcommand = $request->get('unixcommand');
364
        //Se viene lanciato il comando per cancellare il file di lock su bypassa tutto e si lancia
365 1
        $dellockfile = 'DELETELOCK';
366 1
        if ($unixcommand == $dellockfile) {
367
            $this->locksystem->release();
368
369
            return new Response('File di lock cancellato');
370
        }
371
372 1
        if (!$this->locksystem->acquire()) {
373
            return new Response($this->getLockMessage());
374
        } else {
375 1
            $this->locksystem->acquire();
376 1
            $result = $pammutils->runCommand($unixcommand);
0 ignored issues
show
Bug introduced by
It seems like $unixcommand can also be of type null; however, parameter $command of Cdf\PannelloAmministrazi...s\Utility::runCommand() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

376
            $result = $pammutils->runCommand(/** @scrutinizer ignore-type */ $unixcommand);
Loading history...
377
378 1
            $this->locksystem->release();
379
            // eseguito deopo la fine del comando
380 1
            if (0 != $result['errcode']) {
381 1
                $twigparms = array('errcode' => $result['errcode'], 'command' => $result['command'], 'message' => $result['message']);
382 1
                $view = $this->renderView('@PannelloAmministrazione/PannelloAmministrazione/outputcommand.html.twig', $twigparms);
383
384 1
                return new Response($view, 500);
385
            } else {
386 1
                $twigparms = array('errcode' => $result['errcode'], 'command' => $result['command'], 'message' => $result['message']);
387
388 1
                return $this->render('@PannelloAmministrazione/PannelloAmministrazione/outputcommand.html.twig', $twigparms);
389
            }
390
        }
391
    }
392
393
    /**
394
     * @codeCoverageIgnore
395
     */
396
    public function phpunittest(Request $request) : Response
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed. ( Ignorable by Annotation )

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

396
    public function phpunittest(/** @scrutinizer ignore-unused */ Request $request) : Response

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
397
    {
398
        set_time_limit(0);
399
        $this->apppaths = $this->apppaths;
400
        if (!$this->locksystem->acquire()) {
401
            return new Response($this->getLockMessage());
402
        } else {
403
            if (!OsFunctions::isWindows()) {
404
                $this->locksystem->acquire();
405
                //$phpPath = OsFunctions::getPHPExecutableFromPath();
406
                $command = 'vendor'.DIRECTORY_SEPARATOR.'bin'.DIRECTORY_SEPARATOR.'simple-phpunit';
407
                $process = new Process(array($command));
408
                $process->setWorkingDirectory($this->apppaths->getRootPath());
409
410
                $process->run();
411
412
                $this->locksystem->release();
413
                // eseguito dopo la fine del comando
414
                if (!$process->isSuccessful()) {
415
                    $twigparms = array('errcode' => -1, 'command' => $command, 'message' => $process->getOutput().$process->getErrorOutput());
416
                    $view = $this->renderView('@PannelloAmministrazione/PannelloAmministrazione/outputcommand.html.twig', $twigparms);
417
418
                    return new Response($view, 500);
419
                } else {
420
                    $twigparms = array('errcode' => 0, 'command' => $command, 'message' => $process->getOutput().$process->getErrorOutput());
421
422
                    return $this->render('@PannelloAmministrazione/PannelloAmministrazione/outputcommand.html.twig', $twigparms);
423
                }
424
            } else {
425
                // @codeCoverageIgnoreStart
426
                return new Response('Non previsto in ambiente windows!', 500);
427
                // @codeCoverageIgnoreEnd
428
            }
429
        }
430
    }
431
}
432