PannelloAmministrazioneController::findEntities()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 11
c 0
b 0
f 0
nc 4
nop 0
dl 0
loc 18
ccs 12
cts 12
cp 1
crap 4
rs 9.9
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
    }
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
        ini_set("memory_milit", "256M");
92 1
        $finder = new Finder();
93 1
        $fs = new Filesystem();
94
95 1
        $projectDir = $this->apppaths->getRootPath();
96 1
        $docDir = $this->apppaths->getDocPath();
97
98 1
        $mwbs = array();
99
100 1
        if ($fs->exists($docDir)) {
101 1
            $finder->in($docDir)->files()->name('*.mwb');
102 1
            foreach ($finder as $file) {
103 1
                $mwbs[] = $file->getBasename();
104
            }
105
        }
106 1
        sort($mwbs);
107 1
        $svn = $fs->exists($projectDir.'/.svn');
108 1
        $git = $fs->exists($projectDir.'/.git');
109 1
        if (!OsFunctions::isWindows()) {
110 1
            $delcmd = 'rm -rf';
111 1
            $setfilelock = 'touch '.$this->lockfile;
112 1
            $remfilelock = 'rm '.$this->lockfile;
113 1
            $windows = false;
114
        } else {
115
            // @codeCoverageIgnoreStart
116
            $delcmd = 'del';
117
            $setfilelock = 'echo $null >> '.$this->lockfile;
118
            $remfilelock = 'del '.$this->lockfile;
119
            $windows = true;
120
            // @codeCoverageIgnoreEnd
121
        }
122 1
        $dellogsfiles = $delcmd.' '.$this->apppaths->getLogsPath().DIRECTORY_SEPARATOR.'*';
123 1
        $delcacheprodfiles = $delcmd.' '.$this->apppaths->getCachePath().DIRECTORY_SEPARATOR.'prod'.DIRECTORY_SEPARATOR.'*';
124 1
        $delcachedevfiles = $delcmd.' '.$this->apppaths->getCachePath().DIRECTORY_SEPARATOR.'dev'.DIRECTORY_SEPARATOR.'*';
125 1
        $setmaintenancefile = $setfilelock;
126 1
        $remmaintenancefile = $remfilelock;
127
128 1
        $comandishell = array(
129 1
            array('text' => $this->fixSlash($dellogsfiles), 'link' => '#'),
130 1
            array('text' => $this->fixSlash($delcacheprodfiles), 'link' => '#'),
131 1
            array('text' => $this->fixSlash($delcachedevfiles), 'link' => '#'),
132 1
            array('text' => $this->fixSlash($setmaintenancefile), 'link' => '#'),
133 1
            array('text' => $this->fixSlash($remmaintenancefile), 'link' => '#'),
134 1
                //array("text"=>"prova", "link"=>"#"),
135 1
        );
136 1
        $composerinstall = '';
137 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...
138 1
            $composerinstall = $composerinstall.' cd '.$projectDir.' && composer install --no-dev --optimize-autoloader --no-interaction 2>&1';
139 1
            $sed = "sed -i -e 's/cercaquestastringa/sostituisciconquestastringa/g' ".$projectDir.'/.env';
140 1
            $comandishell[] = array('text' => $composerinstall, 'link' => '#');
141 1
            $comandishell[] = array('text' => $sed, 'link' => '#');
142
        }
143
144 1
        $comandisymfony = array(
145 1
            array('text' => 'list', 'link' => '#'),
146 1
            array('text' => 'cache:clear --env=prod --no-debug', 'link' => '#'),
147 1
            array('text' => 'fos:user:create admin pass [email protected]', 'link' => '#'),
148 1
            array('text' => 'fos:user:promote username ROLE_SUPER_ADMIN', 'link' => '#'),
149 1
            array('text' => "assets:install $projectDir/public", 'link' => '#'),
150 1
            array('text' => 'pannelloamministrazione:checkgitversion', 'link' => '#'),
151 1
        );
152
153 1
        $entities = $this->findEntities();
154 1
        sort($entities);
155
156 1
        $twigparms = array(
157 1
            'svn' => $svn, 'git' => $git, 'mwbs' => $mwbs, 'entities' => $entities,
158 1
            'rootdir' => $this->fixSlash($projectDir),
159 1
            'comandishell' => $comandishell,
160 1
            'comandisymfony' => $comandisymfony,
161 1
            'iswindows' => $windows,
162 1
            'appname' => $this->appname,
163 1
        );
164
165 1
        return $this->render('@PannelloAmministrazione/PannelloAmministrazione/index.html.twig', $twigparms);
166
    }
167
168 1
    private function fixSlash(string $path) : string
169
    {
170 1
        return str_replace('\\', '\\\\', $path);
171
    }
172
173
    private function getLockMessage() : string
174
    {
175
        return "<h2 style='color: orange;'>E' già in esecuzione un comando, riprova tra qualche secondo!</h2>";
176
    }
177
178 1
    public function aggiornaSchemaDatabase(): Response
179
    {
180 1
        if (!$this->locksystem->acquire()) {
181
            return new Response($this->getLockMessage());
182
        } else {
183 1
            $this->locksystem->acquire();
184 1
            $command = $this->pacommands;
185 1
            $result = $command->aggiornaSchemaDatabase();
186
187 1
            $this->locksystem->release();
188 1
            if (0 != $result['errcode']) {
189
                $twigparms = array('errcode' => $result['errcode'], 'command' => $result['command'], 'message' => $result['message']);
190
                $view = $this->renderView('@PannelloAmministrazione/PannelloAmministrazione/outputcommand.html.twig', $twigparms);
191
192
                return new Response($view, 500);
193
            } else {
194 1
                $twigparms = array('errcode' => $result['errcode'], 'command' => $result['command'], 'message' => $result['message']);
195
196 1
                return $this->render('@PannelloAmministrazione/PannelloAmministrazione/outputcommand.html.twig', $twigparms);
197
            }
198
        }
199
    }
200
201
    /* FORMS */
202
203
    /**
204
     * Generate form item, controllers and twigs for the given entity/model
205
     */
206 1
    public function generateFormCrud(Request $request) : Response
207
    {
208 1
        if (!$this->locksystem->acquire()) {
209
            return new Response($this->getLockMessage());
210
        } else {
211 1
            $entityform = $request->get('entityform');
212 1
            $generatemplate = 'true' === $request->get('generatemplate') ? true : false;
213 1
            $this->locksystem->acquire();
214
215
            //we are working with an API?
216 1
            $isApi = false;
217
            //verify if provided string belongs to an API model
218 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

218
            if (\str_contains(/** @scrutinizer ignore-type */ $entityform, '(API)')) {
Loading history...
219
                $isApi = true;
220
                $entityform = trim(\str_replace('(API)', '', $entityform));
221
            }
222
223
            // Setup an utility pack of commands (Commands.php)
224 1
            $command = $this->pacommands;
225 1
            $result = $command->generateFormCrud($entityform, $generatemplate, $isApi);
226
227 1
            $this->locksystem->release();
228
            //$retcc = '';
229 1
            if ($result['errcode'] < 0) {
230
                $twigparms = array('errcode' => $result['errcode'], 'command' => 'Generazione Form Crud', 'message' => $result['message']);
231
232
                return new Response(
233
                    $this->renderView('@PannelloAmministrazione/PannelloAmministrazione/outputcommand.html.twig', $twigparms),
234
                    500
235
                );
236
            } else {
237
                //$retcc = $command->clearCacheEnv($this->get('kernel')->getEnvironment());
238
            }
239 1
            $twigparms = array('errcode' => $result['errcode'], 'command' => $result['command'], 'message' => $result['message']);
240
241 1
            return $this->render('@PannelloAmministrazione/PannelloAmministrazione/outputcommand.html.twig', $twigparms);
242
        }
243
    }
244
245
    /* ENTITIES */
246
247 1
    public function generateEntity(Request $request) : Response
248
    {
249 1
        if (!$this->locksystem->acquire()) {
250
            return new Response($this->getLockMessage());
251
        } else {
252 1
            $this->locksystem->acquire();
253 1
            $wbFile = $request->get('file');
254 1
            $command = $this->pacommands;
255 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

255
            $result = $command->generateEntity(/** @scrutinizer ignore-type */ $wbFile);
Loading history...
256 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...
257 1
            $this->locksystem->release();
258 1
            if (0 != $result['errcode']) {
259 1
                $twigparms = array('errcode' => $result['errcode'], 'command' => $result['command'], 'message' => $result['message']);
260 1
                $view = $this->renderView('@PannelloAmministrazione/PannelloAmministrazione/outputcommand.html.twig', $twigparms);
261
262 1
                return new Response($view, 500);
263
            } else {
264 1
                $twigparms = array('errcode' => $result['errcode'], 'command' => $result['command'], 'message' => $result['message']);
265
266 1
                return $this->render('@PannelloAmministrazione/PannelloAmministrazione/outputcommand.html.twig', $twigparms);
267
            }
268
        }
269
    }
270
271
    /* VCS (GIT,SVN) */
272
273
    /**
274
     * @codeCoverageIgnore
275
     */
276
    public function getVcs() : Response
277
    {
278
        set_time_limit(0);
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
            $pammutils = $this->pautils;
336 1
            $command = $this->apppaths->getConsoleExecute().' '.$simfonycommand;
337 1
            $result = $pammutils->runCommand($command);
338
339 1
            $this->locksystem->release();
340 1
            if (0 != $result['errcode']) {
341 1
                $twigparms = array('errcode' => $result['errcode'], 'command' => $result['command'], 'message' => $result['message']);
342 1
                $view = $this->renderView('@PannelloAmministrazione/PannelloAmministrazione/outputcommand.html.twig', $twigparms);
343
344 1
                return new Response($view, 500);
345
            } else {
346 1
                $twigparms = array('errcode' => $result['errcode'], 'command' => $result['command'], 'message' => $result['message']);
347
348 1
                return $this->render('@PannelloAmministrazione/PannelloAmministrazione/outputcommand.html.twig', $twigparms);
349
            }
350
        }
351
    }
352
353
    /**
354
     * Suppress PMD warnings per exit.
355
     *
356
     * @SuppressWarnings(PHPMD)
357
     */
358 1
    public function unixCommand(Request $request): Response
359
    {
360 1
        set_time_limit(0);
361 1
        $pammutils = $this->pautils;
362 1
        $unixcommand = $request->get('unixcommand');
363
        //Se viene lanciato il comando per cancellare il file di lock su bypassa tutto e si lancia
364 1
        $dellockfile = 'DELETELOCK';
365 1
        if ($unixcommand == $dellockfile) {
366
            $this->locksystem->release();
367
368
            return new Response('File di lock cancellato');
369
        }
370
371 1
        if (!$this->locksystem->acquire()) {
372
            return new Response($this->getLockMessage());
373
        } else {
374 1
            $this->locksystem->acquire();
375 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

375
            $result = $pammutils->runCommand(/** @scrutinizer ignore-type */ $unixcommand);
Loading history...
376
377 1
            $this->locksystem->release();
378
            // eseguito deopo la fine del comando
379 1
            if (0 != $result['errcode']) {
380 1
                $twigparms = array('errcode' => $result['errcode'], 'command' => $result['command'], 'message' => $result['message']);
381 1
                $view = $this->renderView('@PannelloAmministrazione/PannelloAmministrazione/outputcommand.html.twig', $twigparms);
382
383 1
                return new Response($view, 500);
384
            } else {
385 1
                $twigparms = array('errcode' => $result['errcode'], 'command' => $result['command'], 'message' => $result['message']);
386
387 1
                return $this->render('@PannelloAmministrazione/PannelloAmministrazione/outputcommand.html.twig', $twigparms);
388
            }
389
        }
390
    }
391
392
    /**
393
     * @codeCoverageIgnore
394
     */
395
    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

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