Passed
Push — master ( 832cd5...6641eb )
by Andrea
21:59 queued 13s
created

PannelloAmministrazioneController::clearCache()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 21
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
cc 3
eloc 15
nc 3
nop 1
dl 0
loc 21
ccs 0
cts 14
cp 0
crap 12
rs 9.7666
c 0
b 0
f 0
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 Cdf\PannelloAmministrazioneBundle\Utils\Utility as Pautils;
15
use Cdf\PannelloAmministrazioneBundle\Utils\ProjectPath;
16
use Cdf\PannelloAmministrazioneBundle\Utils\Commands as Pacmd;
17
use Cdf\BiCoreBundle\Utils\Api\ApiUtils;
18
19
class PannelloAmministrazioneController extends AbstractController
20
{
21
    private $apppaths;
22
    private $pacommands;
23
    private $pautils;
24
    protected $locksystem;
25
    protected $factory;
26
    private $appname;
27
    private $lockfile;
28
29 1
    public function __construct($appname, $lockfile, ProjectPath $projectpath, Pacmd $pacommands, Pautils $pautils)
30
    {
31 1
        $store = new FlockStore(sys_get_temp_dir());
32 1
        $factory = new LockFactory($store);
33 1
        $this->locksystem = $factory->createLock('pannelloamministrazione-command');
34 1
        $this->locksystem->release();
35 1
        $this->appname = $appname;
36 1
        $this->lockfile = $lockfile;
37 1
        $this->apppaths = $projectpath;
38 1
        $this->pacommands = $pacommands;
39 1
        $this->pautils = $pautils;
40 1
    }
41
42 1
    private function findEntities()
43
    {
44 1
        $entitiesprogetto = array();
45 1
        $prefix = 'App\\Entity\\';
46 1
        $prefixBase = 'Base';
47 1
        $entities = $this->get('doctrine')->getManager()->getConfiguration()->getMetadataDriverImpl()->getAllClassNames();
48
        // compute additional API models since external bundles
49 1
        $additionalEntities = $this->findAPIModels();
50 1
        foreach ($entities as $entity) {
51 1
            if (substr($entity, 0, strlen($prefix)) == $prefix) {
52 1
                if (substr(substr($entity, strlen($prefix)), 0, strlen($prefixBase)) != $prefixBase) {
53 1
                    $entitiesprogetto[] = substr($entity, strlen($prefix));
54
                }
55
            }
56
        }
57
        // merge of found arrays
58 1
        $outcomes = array_merge($entitiesprogetto, $additionalEntities);
59 1
        return $outcomes;
60
    }
61
62
    /**
63
     * It looks for Models existent into included external bundles.
64
     * It uses ApiUtils in order to know where to search and what look for.
65
     */
66 1
    private function findAPIModels(): array
67
    {
68 1
        $apiUtil = new ApiUtils();
69 1
        $apiUtil->setRootDir($this->apppaths->getVendorPath());
70 1
        return $apiUtil->apiModels();
71
    }
72
73 1
    public function index()
74
    {
75 1
        $finder = new Finder();
76 1
        $fs = new Filesystem();
77
78 1
        $projectDir = $this->apppaths->getRootPath();
79 1
        $docDir = $this->apppaths->getDocPath();
80
81 1
        $mwbs = array();
82
83 1
        if ($fs->exists($docDir)) {
84 1
            $finder->in($docDir)->files()->name('*.mwb');
85 1
            foreach ($finder as $file) {
86 1
                $mwbs[] = $file->getBasename();
87
            }
88
        }
89 1
        sort($mwbs);
90 1
        $svn = $fs->exists($projectDir.'/.svn');
91 1
        $git = $fs->exists($projectDir.'/.git');
92 1
        if (!OsFunctions::isWindows()) {
93 1
            $delcmd = 'rm -rf';
94 1
            $setfilelock = 'touch '.$this->lockfile;
95 1
            $remfilelock = 'rm '.$this->lockfile;
96 1
            $windows = false;
97
        } else {
98
            // @codeCoverageIgnoreStart
99
            $delcmd = 'del';
100
            $setfilelock = 'echo $null >> '.$this->lockfile;
101
            $remfilelock = 'del '.$this->lockfile;
102
            $windows = true;
103
            // @codeCoverageIgnoreEnd
104
        }
105 1
        $dellogsfiles = $delcmd.' '.$this->apppaths->getLogsPath().DIRECTORY_SEPARATOR.'*';
106 1
        $delcacheprodfiles = $delcmd.' '.$this->apppaths->getCachePath().DIRECTORY_SEPARATOR.'prod'.DIRECTORY_SEPARATOR.'*';
107 1
        $delcachedevfiles = $delcmd.' '.$this->apppaths->getCachePath().DIRECTORY_SEPARATOR.'dev'.DIRECTORY_SEPARATOR.'*';
108 1
        $setmaintenancefile = $setfilelock;
109 1
        $remmaintenancefile = $remfilelock;
110
111
        $comandishell = array(
112 1
            array('text' => $this->fixSlash($dellogsfiles), 'link' => '#'),
113 1
            array('text' => $this->fixSlash($delcacheprodfiles), 'link' => '#'),
114 1
            array('text' => $this->fixSlash($delcachedevfiles), 'link' => '#'),
115 1
            array('text' => $this->fixSlash($setmaintenancefile), 'link' => '#'),
116 1
            array('text' => $this->fixSlash($remmaintenancefile), 'link' => '#'),
117
                //array("text"=>"prova", "link"=>"#"),
118
        );
119 1
        $composerinstall = '';
120 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...
121 1
            $composerinstall = $composerinstall.' cd '.$projectDir.' && composer install --no-dev --optimize-autoloader --no-interaction 2>&1';
122 1
            $sed = "sed -i -e 's/cercaquestastringa/sostituisciconquestastringa/g' ".$projectDir.'/.env';
123 1
            $comandishell[] = array('text' => $composerinstall, 'link' => '#');
124 1
            $comandishell[] = array('text' => $sed, 'link' => '#');
125
        }
126
127
        $comandisymfony = array(
128 1
            array('text' => 'list', 'link' => '#'),
129
            array('text' => 'cache:clear --env=prod --no-debug', 'link' => '#'),
130
            array('text' => 'fos:user:create admin pass [email protected]', 'link' => '#'),
131
            array('text' => 'fos:user:promote username ROLE_SUPER_ADMIN', 'link' => '#'),
132 1
            array('text' => "assets:install $projectDir/public", 'link' => '#'),
133
            array('text' => 'pannelloamministrazione:checkgitversion', 'link' => '#'),
134
        );
135
136 1
        $entities = $this->findEntities();
137 1
        sort($entities);
138
139
        $twigparms = array(
140 1
            'svn' => $svn, 'git' => $git, 'mwbs' => $mwbs, 'entities' => $entities,
141 1
            'rootdir' => $this->fixSlash($projectDir),
142 1
            'comandishell' => $comandishell,
143 1
            'comandisymfony' => $comandisymfony,
144 1
            'iswindows' => $windows,
145 1
            'appname' => $this->appname,
146
        );
147
148 1
        return $this->render('@PannelloAmministrazione/PannelloAmministrazione/index.html.twig', $twigparms);
149
    }
150
151 1
    private function fixSlash($path)
152
    {
153 1
        return str_replace('\\', '\\\\', $path);
154
    }
155
156
    private function getLockMessage()
157
    {
158
        return "<h2 style='color: orange;'>E' già in esecuzione un comando, riprova tra qualche secondo!</h2>";
159
    }
160
161 1
    public function aggiornaSchemaDatabase()
162
    {
163 1
        if (!$this->locksystem->acquire()) {
164
            return new Response($this->getLockMessage());
165
        } else {
166 1
            $this->locksystem->acquire();
167 1
            $command = $this->pacommands;
168 1
            $result = $command->aggiornaSchemaDatabase();
169
170 1
            $this->locksystem->release();
171 1
            if (0 != $result['errcode']) {
172
                $twigparms = array('errcode' => $result['errcode'], 'command' => $result['command'], 'message' => $result['message']);
173
                $view = $this->renderView('@PannelloAmministrazione/PannelloAmministrazione/outputcommand.html.twig', $twigparms);
174
175
                return new Response($view, 500);
176
            } else {
177 1
                $twigparms = array('errcode' => $result['errcode'], 'command' => $result['command'], 'message' => $result['message']);
178
179 1
                return $this->render('@PannelloAmministrazione/PannelloAmministrazione/outputcommand.html.twig', $twigparms);
180
            }
181
        }
182
    }
183
184
    /* FORMS */
185
186
    /**
187
     * Generate form item, controllers and twigs for the given entity/model
188
     */
189 1
    public function generateFormCrud(Request $request)
190
    {
191 1
        if (!$this->locksystem->acquire()) {
192
            return new Response($this->getLockMessage());
193
        } else {
194 1
            $entityform = $request->get('entityform');
195 1
            $generatemplate = 'true' === $request->get('generatemplate') ? true : false;
196 1
            $this->locksystem->acquire();
197
198
            //we are working with an API?
199 1
            $isApi = false;
200
            //verify if provided string belongs to an API model
201 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

201
            if (\str_contains(/** @scrutinizer ignore-type */ $entityform, '(API)')) {
Loading history...
202
                $isApi = true;
203
                $entityform = trim(\str_replace('(API)', '', $entityform));
204
            }
205
206
            // Setup an utility pack of commands (Commands.php)
207 1
            $command = $this->pacommands;
208 1
            $result = $command->generateFormCrud($entityform, $generatemplate, $isApi);
209
210 1
            $this->locksystem->release();
211
            //$retcc = '';
212 1
            if ($result['errcode'] < 0) {
213
                $twigparms = array('errcode' => $result['errcode'], 'command' => 'Generazione Form Crud', 'message' => $result['message']);
214
215
                return new Response(
216
                    $this->renderView('@PannelloAmministrazione/PannelloAmministrazione/outputcommand.html.twig', $twigparms),
217
                    500
218
                );
219
            } else {
220
                //$retcc = $command->clearCacheEnv($this->get('kernel')->getEnvironment());
221
            }
222 1
            $twigparms = array('errcode' => $result['errcode'], 'command' => $result['command'], 'message' => $result['message']);
223
224 1
            return $this->render('@PannelloAmministrazione/PannelloAmministrazione/outputcommand.html.twig', $twigparms);
225
        }
226
    }
227
228
    /* ENTITIES */
229
230 1
    public function generateEntity(Request $request)
231
    {
232 1
        if (!$this->locksystem->acquire()) {
233
            return new Response($this->getLockMessage());
234
        } else {
235 1
            $this->locksystem->acquire();
236 1
            $wbFile = $request->get('file');
237 1
            $command = $this->pacommands;
238 1
            $result = $command->generateEntity($wbFile);
239 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...
240 1
            $this->locksystem->release();
241 1
            if (0 != $result['errcode']) {
242 1
                $twigparms = array('errcode' => $result['errcode'], 'command' => $result['command'], 'message' => $result['message']);
243 1
                $view = $this->renderView('@PannelloAmministrazione/PannelloAmministrazione/outputcommand.html.twig', $twigparms);
244
245 1
                return new Response($view, 500);
246
            } else {
247 1
                $twigparms = array('errcode' => $result['errcode'], 'command' => $result['command'], 'message' => $result['message']);
248
249 1
                return $this->render('@PannelloAmministrazione/PannelloAmministrazione/outputcommand.html.twig', $twigparms);
250
            }
251
        }
252
    }
253
254
    /* VCS (GIT,SVN) */
255
256
    /**
257
     * @codeCoverageIgnore
258
     */
259
    public function getVcs()
260
    {
261
        set_time_limit(0);
262
        $this->apppaths = $this->apppaths;
263
        if (!$this->locksystem->acquire()) {
264
            return new Response($this->getLockMessage());
265
        } else {
266
            $this->locksystem->acquire();
267
            $command = $this->pacommands;
268
            $result = $command->getVcs();
269
            $this->locksystem->release();
270
            $twigparms = array('errcode' => $result['errcode'], 'command' => $result['command'], 'message' => $result['message']);
271
272
            return $this->render('@PannelloAmministrazione/PannelloAmministrazione/outputcommand.html.twig', $twigparms);
273
        }
274
    }
275
276
    /* CLEAR CACHE */
277
278
    /**
279
     * Suppress PMD warnings per exit.
280
     *
281
     * @//SuppressWarnings(PHPMD)
282
     */
283
    public function clearCache(Request $request)
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

283
    public function clearCache(/** @scrutinizer ignore-unused */ Request $request)

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...
284
    {
285
        set_time_limit(0);
286
        if (!$this->locksystem->acquire()) {
287
            return new Response($this->getLockMessage());
288
        } else {
289
            $this->locksystem->acquire();
290
            $command = $this->pacommands;
291
            $result = $command->clearcache();
292
293
            $this->locksystem->release();
294
295
            if (0 != $result['errcode']) {
296
                $twigparms = array('errcode' => $result['errcode'], 'command' => $result['command'], 'message' => $result['message']);
297
                $view = $this->renderView('@PannelloAmministrazione/PannelloAmministrazione/outputcommand.html.twig', $twigparms);
298
299
                return new Response($view, 500);
300
            } else {
301
                $twigparms = array('errcode' => $result['errcode'], 'command' => $result['command'], 'message' => $result['message']);
302
303
                return $this->render('@PannelloAmministrazione/PannelloAmministrazione/outputcommand.html.twig', $twigparms);
304
            }
305
        }
306
    }
307
308
    /* CLEAR CACHE */
309
310 1
    public function symfonyCommand(Request $request)
311
    {
312 1
        set_time_limit(0);
313
314 1
        $simfonycommand = $request->get('symfonycommand');
315 1
        if (!$this->locksystem->acquire()) {
316
            return new Response($this->getLockMessage());
317
        } else {
318 1
            $this->locksystem->acquire();
319 1
            $this->apppaths = $this->apppaths;
320 1
            $pammutils = $this->pautils;
321 1
            $command = $this->apppaths->getConsoleExecute().' '.$simfonycommand;
322 1
            $result = $pammutils->runCommand($command);
323
324 1
            $this->locksystem->release();
325 1
            if (0 != $result['errcode']) {
326 1
                $twigparms = array('errcode' => $result['errcode'], 'command' => $result['command'], 'message' => $result['message']);
327 1
                $view = $this->renderView('@PannelloAmministrazione/PannelloAmministrazione/outputcommand.html.twig', $twigparms);
328
329 1
                return new Response($view, 500);
330
            } else {
331 1
                $twigparms = array('errcode' => $result['errcode'], 'command' => $result['command'], 'message' => $result['message']);
332
333 1
                return $this->render('@PannelloAmministrazione/PannelloAmministrazione/outputcommand.html.twig', $twigparms);
334
            }
335
        }
336
    }
337
338
    /**
339
     * Suppress PMD warnings per exit.
340
     *
341
     * @SuppressWarnings(PHPMD)
342
     */
343 1
    public function unixCommand(Request $request)
344
    {
345 1
        set_time_limit(0);
346 1
        $pammutils = $this->pautils;
347 1
        $unixcommand = $request->get('unixcommand');
348
        //Se viene lanciato il comando per cancellare il file di lock su bypassa tutto e si lancia
349 1
        $dellockfile = 'DELETELOCK';
350 1
        if ($unixcommand == $dellockfile) {
351
            $this->locksystem->release();
352
353
            return new Response('File di lock cancellato');
354
        }
355
356 1
        if (!$this->locksystem->acquire()) {
357
            return new Response($this->getLockMessage());
358
        } else {
359 1
            $this->locksystem->acquire();
360 1
            $result = $pammutils->runCommand($unixcommand);
361
362 1
            $this->locksystem->release();
363
            // eseguito deopo la fine del comando
364 1
            if (0 != $result['errcode']) {
365 1
                $twigparms = array('errcode' => $result['errcode'], 'command' => $result['command'], 'message' => $result['message']);
366 1
                $view = $this->renderView('@PannelloAmministrazione/PannelloAmministrazione/outputcommand.html.twig', $twigparms);
367
368 1
                return new Response($view, 500);
369
            } else {
370 1
                $twigparms = array('errcode' => $result['errcode'], 'command' => $result['command'], 'message' => $result['message']);
371
372 1
                return $this->render('@PannelloAmministrazione/PannelloAmministrazione/outputcommand.html.twig', $twigparms);
373
            }
374
        }
375
    }
376
377
    /**
378
     * @codeCoverageIgnore
379
     */
380
    public function phpunittest(Request $request)
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

380
    public function phpunittest(/** @scrutinizer ignore-unused */ Request $request)

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...
381
    {
382
        set_time_limit(0);
383
        $this->apppaths = $this->apppaths;
384
        if (!$this->locksystem->acquire()) {
385
            return new Response($this->getLockMessage());
386
        } else {
387
            if (!OsFunctions::isWindows()) {
388
                $this->locksystem->acquire();
389
                //$phpPath = OsFunctions::getPHPExecutableFromPath();
390
                $command = 'vendor'.DIRECTORY_SEPARATOR.'bin'.DIRECTORY_SEPARATOR.'simple-phpunit';
391
                $process = new Process(array($command));
392
                $process->setWorkingDirectory($this->apppaths->getRootPath());
393
394
                $process->run();
395
396
                $this->locksystem->release();
397
                // eseguito dopo la fine del comando
398
                if (!$process->isSuccessful()) {
399
                    $twigparms = array('errcode' => -1, 'command' => $command, 'message' => $process->getOutput().$process->getErrorOutput());
400
                    $view = $this->renderView('@PannelloAmministrazione/PannelloAmministrazione/outputcommand.html.twig', $twigparms);
401
402
                    return new Response($view, 500);
403
                } else {
404
                    $twigparms = array('errcode' => 0, 'command' => $command, 'message' => $process->getOutput().$process->getErrorOutput());
405
406
                    return $this->render('@PannelloAmministrazione/PannelloAmministrazione/outputcommand.html.twig', $twigparms);
407
                }
408
            } else {
409
                // @codeCoverageIgnoreStart
410
                return new Response('Non previsto in ambiente windows!', 500);
411
                // @codeCoverageIgnoreEnd
412
            }
413
        }
414
    }
415
}
416