GenerateFormCommand::addCheckbox()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 2
Bugs 1 Features 0
Metric Value
cc 1
eloc 1
c 2
b 1
f 0
nc 1
nop 3
dl 0
loc 3
ccs 0
cts 2
cp 0
crap 2
rs 10
1
<?php
2
3
namespace Cdf\PannelloAmministrazioneBundle\Command;
4
5
use Cdf\BiCoreBundle\Entity\Colonnetabelle;
6
use Cdf\BiCoreBundle\Entity\Permessi;
7
use Cdf\BiCoreBundle\Entity\Ruoli;
8
use Cdf\PannelloAmministrazioneBundle\Utils\ProjectPath;
9
use Cdf\PannelloAmministrazioneBundle\Utils\Utility;
10
use Doctrine\ORM\EntityManagerInterface;
11
use Symfony\Component\HttpKernel\KernelInterface;
12
use Symfony\Component\Console\Command\Command;
13
use Symfony\Component\Console\Input\InputArgument;
14
use Symfony\Component\Console\Input\InputInterface;
15
use Symfony\Component\Console\Input\InputOption;
16
use Symfony\Component\Console\Output\OutputInterface;
17
use Symfony\Component\Filesystem\Filesystem;
18
use Cdf\BiCoreBundle\Utils\Entity\ModelUtils;
19
use Cdf\BiCoreBundle\Utils\Api\ApiUtils;
20
use Cdf\BiCoreBundle\Utils\String\StringUtils;
21
use Exception;
22
use function count;
23
24
/**
25
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
26
 * @SuppressWarnings(PHPMD.ExcessiveClassComplexity)
27
 */
28
class GenerateFormCommand extends Command
29
{
30
31
    //Task / Process customized for Form Creation
32
    protected static $defaultName = 'pannelloamministrazione:generateformcrud';
33
    protected ProjectPath $apppaths;
34
    protected EntityManagerInterface $em;
35
    protected Utility $pammutils;
36
    private bool $generatemplate;
37
    private string $projectname;
38
    private bool $isApi;
39
    private KernelInterface $kernel;
40
41
    /** @var array<mixed> */
42
    private array $typesMapping;
43
44 1
    protected function configure(): void
45
    {
46 1
        $this
47 1
                ->setDescription('Genera le views per il crud')
48 1
                ->setHelp('Genera le views per il crud, <br/>bi.mwb AppBundle default [--schemaupdate]<br/>')
49 1
                ->addArgument('entityform', InputArgument::REQUIRED, 'Il nome entity del form da creare')
50 1
                ->addOption('generatemplate', 't', InputOption::VALUE_OPTIONAL)
51 1
                ->addOption('projectname', 'p', InputOption::VALUE_OPTIONAL)
52 1
                ->addOption('isApi', 'a', InputOption::VALUE_OPTIONAL);
53
    }
54
55 1
    public function __construct(KernelInterface $kernel, ProjectPath $projectpath, Utility $pammutils, EntityManagerInterface $em)
56
    {
57 1
        $this->kernel = $kernel;
58 1
        $this->apppaths = $projectpath;
59 1
        $this->pammutils = $pammutils;
60 1
        $this->em = $em;
61 1
        $this->loadTypesMapping();
62
63
        // you *must* call the parent constructor
64 1
        parent::__construct();
65
    }
66
67
    /**
68
     * Load mapping between types and loading methods
69
     */
70 1
    private function loadTypesMapping(): void
71
    {
72 1
        $this->typesMapping = array();
73 1
        $this->typesMapping['datetime'] = 'addDateTimeType';
74 1
        $this->typesMapping['double'] = 'addNumberType';
75 1
        $this->typesMapping['int'] = 'addIntegerType';
76 1
        $this->typesMapping['int64'] = 'addIntegerType';
77 1
        $this->typesMapping['void'] = 'addStringType';
78 1
        $this->typesMapping['fk'] = 'addFkType';
79 1
        $this->typesMapping['enum'] = 'addEnumType';
80 1
        $this->typesMapping['comment'] = 'addComment';
81 1
        $this->typesMapping['bool'] = 'addCheckbox';
82
    }
83
84
    /**
85
     * Browse available functions and return the function to be used for source code portion.
86
     *
87
     * @param array<mixed> $attribute
88
     * @param string $attributeName
89
     * @return string
90
     */
91
    private function getFunctionForSourceCode(array &$attribute, string $attributeName): ?string
92
    {
93
        $function = null;
94
        if (\str_contains($attributeName, '_id')) {
95
            $function = $this->typesMapping['fk'];
96
        } elseif (\str_contains($attributeName, '_enum')) {
97
            $function = $this->typesMapping['enum'];
98
        } elseif (\str_contains($attributeName, '_desc')) {
99
            $function = $this->typesMapping['comment'];
100
        } elseif ($attributeName == 'id') {
101
            //the record will be ignored and not included into the form
102
        } elseif (isset($this->typesMapping[$attribute['type']]) && $attribute['type'] == 'bool') {
103
            $function = $this->typesMapping[$attribute['type']];
104
        } elseif (isset($this->typesMapping[$attribute['format']])) {
105
            $function = $this->typesMapping[$attribute['format']];
106
        } else {
107
            $function = $this->typesMapping['void'];
108
        }
109
        return $function;
110
    }
111
112
    /**
113
     * It insert main types to be used into a Form
114
     *
115
     * @param array<string> $lines
116
     * @param int $position
117
     * @return void
118
     */
119 1
    private function insertUseOfTypes(array &$lines, int $position): void
120
    {
121 1
        array_splice($lines, ++$position, 0, 'use Symfony\Component\Form\Extension\Core\Type\SubmitType;');
122 1
        array_splice($lines, ++$position, 0, 'use Symfony\Component\Form\Extension\Core\Type\DateTimeType;');
123 1
        array_splice($lines, ++$position, 0, 'use Symfony\Component\Form\Extension\Core\Type\NumberType;');
124 1
        array_splice($lines, ++$position, 0, 'use Symfony\Component\Form\Extension\Core\Type\TextType;');
125 1
        array_splice($lines, ++$position, 0, 'use Symfony\Component\Form\Extension\Core\Type\CheckboxType;');
126 1
        array_splice($lines, ++$position, 0, 'use Symfony\Component\Form\Extension\Core\Type\DateType;');
127 1
        array_splice($lines, ++$position, 0, 'use Symfony\Component\Form\Extension\Core\Type\IntegerType;');
128 1
        array_splice($lines, ++$position, 0, 'use Symfony\Component\Form\Extension\Core\Type\TextareaType;');
129 1
        array_splice($lines, ++$position, 0, 'use Symfony\Component\Form\Extension\Core\Type\MailType;');
130 1
        array_splice($lines, ++$position, 0, 'use Symfony\Component\Form\Extension\Core\Type\ChoiceType;');
131 1
        array_splice($lines, ++$position, 0, 'use Cdf\BiCoreBundle\Utils\FieldType\HiddenIntegerType;');
132
    }
133
134
    /**
135
     * It insert setExtraOption method to created form
136
     *
137
     * @param array<string> $lines
138
     * @param int $position
139
     */
140
    private function insertSetExtraOptionFunction(array &$lines, int $position): void
141
    {
142
        array_splice($lines, ++$position, 0, '
143
    
144
    private function setExtraOption(array $options):array 
145
    {
146
        $arraychoices = array();
147
        if (isset($options["extra-options"])) {
148
            foreach($options["extra-options"] as $key=>$value) {
149
                foreach($value as $extraOption) {
150
                    $arraychoices[$key][$extraOption["descrizione"]] = $extraOption["id"];
151
                }
152
            }
153
        }
154
        return $arraychoices;
155
    }
156
    
157
    ');
158
    }
159
160
    /**
161
     * It inserts submitparams options, and arraychoices filling if API form
162
     *
163
     * @param array<string> $lines
164
     * @param int $position
165
     */
166 1
    private function insertParamsOptions(array &$lines, int $position): void
167
    {
168 1
        if ($this->isApi) {
169
            array_splice($lines, $position, 0, '        $arraychoices = $this->setExtraOption($options);');
170
            $position++;
171
        }
172 1
        array_splice($lines, $position, 0, '        $submitparms = array('
173 1
                . "'label' => 'Salva','attr' => array(\"class\" => \"btn-outline-primary bisubmit\", \"aria-label\" => \"Salva\"));");
174
    }
175
176
    /**
177
     * Add portion of code to manage a field as datetime
178
     *
179
     * @param array<string> $lines
180
     * @param int $position
181
     * @param string $attributeName
182
     * @return void
183
184
     * @SuppressWarnings(PHPMD.UnusedPrivateMethod)
185
     */
186
    private function addDateTimeType(array &$lines, int $position, string $attributeName): void
187
    {
188
        array_splice($lines, ++$position, 0, "            ->add('" . $attributeName . "', DateTimeType::class, array(");
189
        array_splice($lines, ++$position, 0, "                  'widget' => 'single_text',");
190
        array_splice($lines, ++$position, 0, "                  'format' => 'dd/MM/yyyy HH:mm',");
191
        array_splice($lines, ++$position, 0, "                  'attr' => array('class' => 'bidatetimepicker'),");
192
        array_splice($lines, ++$position, 0, "                  ))");
193
    }
194
195
    /**
196
     * @param array<string> $lines
197
     * @param int $position
198
     * @param string $attributeName
199
     * @return void
200
     *
201
     * @SuppressWarnings(PHPMD.UnusedPrivateMethod)
202
     */
203
    private function addFkType(array &$lines, $position, $attributeName)
204
    {
205
        array_splice($lines, ++$position, 0, "            ->add('" . $attributeName . "',HiddenIntegerType::class)");
206
        $strpos = strpos($attributeName, '_id');
207
        if ($strpos === false) {
208
            return;
209
        }
210
211
        $choiceName = substr($attributeName, 0, $strpos);
212
213
        //it fixes cases such as event_type_id
214
        $parametri = array('str' => $choiceName, 'primamaiuscola' => true);
215
        $upperName = StringUtils::toCamelCase($parametri);
216
217
        //$upperName = ucfirst($choiceName);
218
        array_splice($lines, ++$position, 0, '            ->add(\'' . $choiceName . '\',ChoiceType::class,
219
            array(
220
                    \'choices\' => isset($arraychoices[\'' . $choiceName . '\'])?$arraychoices[\'' . $choiceName . '\']:[], 
221
                    \'mapped\' => false,
222
                    \'data\' => ($options["data"]->get' . $upperName . 'Id() > 0) ? $options["data"]->get' . $upperName . 'Id() : null ,
223
                    \'placeholder\' => \'---\'
224
                    )
225
                )
226
            ');
227
    }
228
229
    /**
230
     * @param array<string> $lines
231
     * @param int $position
232
     * @param string $attributeName
233
     * @return void
234
235
     * @SuppressWarnings(PHPMD.UnusedPrivateMethod)
236
     */
237
    private function addEnumType(array &$lines, $position, $attributeName)
238
    {
239
        array_splice($lines, ++$position, 0, "            ->add('" . $attributeName . "',HiddenIntegerType::class)");
240
        $strpos = strpos($attributeName, '_enum');
241
        if ($strpos === false) {
242
            return;
243
        }
244
        $choiceName = substr($attributeName, 0, $strpos);
245
246
        //it fixes cases such as event_type_id
247
        $parametri = array('str' => $choiceName, 'primamaiuscola' => true);
248
        $upperName = StringUtils::toCamelCase($parametri);
249
250
        //$upperName = ucfirst($choiceName);
251
        array_splice($lines, ++$position, 0, '            ->add(\'' . $choiceName . '\',ChoiceType::class,
252
            array(
253
                    \'choices\' => isset($arraychoices[\'' . $choiceName . '\'])?$arraychoices[\'' . $choiceName . '\']:[], 
254
                    \'mapped\' => false,
255
                    \'data\' => ($options["data"]->get' . $upperName . 'Enum() >= 0) ? $options["data"]->get' . $upperName . 'Enum() : null ,
256
                    \'placeholder\' => \'---\'
257
                    )
258
                )
259
            ');
260
    }
261
262
    /**
263
     * Add a boolean checkbox
264
     *
265
     * @param array<string> $lines
266
     * @param int $position
267
     * @param string $attributeName
268
     * @return void
269
270
     * @SuppressWarnings(PHPMD.UnusedPrivateMethod)
271
     */
272
    private function addCheckbox(array &$lines, $position, $attributeName)
273
    {
274
        array_splice($lines, ++$position, 0, '            ->add(\'' . $attributeName . '\',CheckboxType::class,
275
            array(
276
                    \'false_values\' => [0, false, null], 
277
                    \'required\' => false
278
                    )
279
                )
280
            ');
281
    }
282
283
    /**
284
     * Add portion of code to manage a field as float/number
285
     *
286
     * @param array<string> $lines
287
     * @param int $position
288
     * @param string $attributeName
289
     * @return void
290
291
     * @SuppressWarnings(PHPMD.UnusedPrivateMethod)
292
     */
293
    private function addNumberType(array &$lines, $position, $attributeName)
294
    {
295
        array_splice($lines, ++$position, 0, "            ->add('" . $attributeName . "',NumberType::class)");
296
    }
297
298
    /**
299
     * Add portion of code to manage a field as integer
300
     *
301
     * @param array<string> $lines
302
     * @param int $position
303
     * @param string $attributeName
304
     * @return void
305
306
     * @SuppressWarnings(PHPMD.UnusedPrivateMethod)
307
     */
308
    private function addIntegerType(array &$lines, $position, $attributeName)
309
    {
310
        array_splice($lines, ++$position, 0, "            ->add('" . $attributeName . "',IntegerType::class)");
311
    }
312
313
    /**
314
     * Add portion of code to manage a commmented string
315
     *
316
     * @param array<string> $lines
317
     * @param int $position
318
     * @param string $attributeName
319
     * @param bool $commented
320
     * @return void
321
322
     * @SuppressWarnings(PHPMD.UnusedPrivateMethod)
323
     */
324
    private function addComment(array &$lines, $position, $attributeName, bool $commented = false)
325
    {
326
        $this->addStringType($lines, $position, $attributeName, true);
327
    }
328
329
    /**
330
     * Add portion of code to manage a field as string
331
     *
332
     * @param array<string> $lines
333
     * @param int $position
334
     * @param string $attributeName
335
     * @param bool $commented
336
     * @return void
337
338
     */
339
    private function addStringType(array &$lines, $position, $attributeName, $commented = false)
340
    {
341
        $comment = '';
342
        if ($commented) {
343
            $comment = '//';
344
        }
345
        array_splice($lines, ++$position, 0, $comment . "            ->add('" . $attributeName . "',TextType::class)");
346
    }
347
348
    /**
349
     * Execute command in order to create the new form class
350
     */
351 1
    protected function execute(InputInterface $input, OutputInterface $output): int
352
    {
353 1
        set_time_limit(0);
354
355
        //TODO: refactor variables
356 1
        $bundlename = 'App';
357 1
        $entityform = $input->getArgument('entityform');
358 1
        $this->generatemplate = $input->getOption('generatemplate');
359 1
        $this->isApi = (bool) $input->getOption('isApi');
360 1
        $attributes = [];
361 1
        $modelClass = "";
362
363
        //to be changed form generation in order to cover API/REST type
364 1
        $command = $this->apppaths->getConsoleExecute() . ' --env=dev' . ' make:form ' . $entityform . 'Type';
365
        //Append also entity class if is an ORM
366 1
        if ($this->isApi) {
367
            $command .= ' -n';
368
        } else {
369 1
            $command .= ' ' . $entityform;
370
        }
371 1
        $resultcrud = $this->pammutils->runCommand($command);
372 1
        if (0 == $resultcrud['errcode']) {
373 1
            $fs = new Filesystem();
374
            //Controller
375 1
            $controlleFile = $this->apppaths->getSrcPath() . '/Controller/' . $entityform . 'Controller.php';
376
377 1
            $formFile = $this->apppaths->getSrcPath() . '/Form/' . $entityform . 'Type.php';
378
379 1
            $lines = file($formFile, FILE_IGNORE_NEW_LINES);
380 1
            if ($lines ===false) {
381
                throw new Exception("Impossibile fare il parse del file " . $formFile);
382
            }
383
384 1
            $pos1 = $this->findPosition($lines, 'use Symfony\Component\Form\AbstractType');
385
386
            //Some objects to be used
387 1
            $this->insertUseOfTypes($lines, $pos1);
388 1
            if ($this->isApi) {
389
                $this->projectname = $input->getOption('projectname');
390
                if ($this->projectname === null) {
391
                    throw new Exception("projectname non specificato");
392
                }
393
                $apiUtil = new ApiUtils();
394
                $modelClass = $apiUtil->getModelClass($this->projectname, $entityform);
395
                array_splice($lines, $pos1, 0, 'use ' . $modelClass . ';');
396
                $modelUtil = new ModelUtils();
397
                $attributes = $modelUtil->getAttributes($modelClass);
398
            }
399
400 1
            $pos2 = $this->findPosition($lines, '{', true);
401 1
            if ($this->isApi) {
402
                $this->insertSetExtraOptionFunction($lines, $pos2);
403
            }
404 1
            $pos2 = $this->findPosition($lines, '$builder', false);
405
406 1
            $this->insertParamsOptions($lines, $pos2);
407
408 1
            $pos3 = $this->findPosition($lines, '->add(', false);
409 1
            array_splice($lines, $pos3 + 1, 0, "            ->add('submit', SubmitType::class, \$submitparms)");
410
411 1
            if ($this->isApi) {
412
                $pos3 = $this->findPosition($lines, '->add(');
413
                //comment the line ->add()
414
                $lines[$pos3] = '//' . $lines[$pos3];
415
                //in this position should be added form attributes
416
                foreach (array_reverse($attributes) as $attributeName => $attribute) {
417
                    $function = $this->getFunctionForSourceCode($attribute, $attributeName);
418
                    if (isset($function)) {
419
                        $this->$function($lines, $pos3, $attributeName);
420
                    }
421
                }
422
            }
423
424 1
            array_splice($lines, count($lines) - 3, 0, "            'parametriform' => array(),'extra-options' => null,");
425
426 1
            file_put_contents($formFile, implode("\n", $lines));
427
428 1
            $code = $this->getControllerCode(str_replace('/', '\\', $bundlename), $entityform, $modelClass);
429 1
            $fs->dumpFile($controlleFile, $code);
430 1
            $output->writeln('<info>Creato ' . $controlleFile . '</info>');
431
432
            //Routing
433 1
            $retmsg = $this->generateFormRouting($entityform);
434
            //Twig template
435 1
            $this->copyTableStructureWiew($entityform);
436
437 1
            $this->generateFormsDefaultTableValues($entityform);
438 1
            $output->writeln('<info>' . $retmsg . '</info>');
439
440 1
            return 0;
441
        } else {
442
            $output->writeln('<error>' . $resultcrud['message'] . '</error>');
443
444
            return 1;
445
        }
446
    }
447
448
    /**
449
     *
450
     * @param array<mixed> $arr
451
     * @param string $keyword
452
     * @param bool $first
453
     * @return int
454
     */
455 1
    private function findPosition(array $arr, string $keyword, bool $first = true): int
456
    {
457 1
        $returnIndex = -1;
458 1
        foreach ($arr as $index => $string) {
459 1
            if (strpos($string, $keyword) !== false) {
460 1
                $returnIndex = $index;
461 1
                if ($first) {
462 1
                    break;
463
                }
464
            }
465
        }
466 1
        return $returnIndex;
467
    }
468
469 1
    private function generateFormRouting(string $entityform): string
470
    {
471
        //Routing del form
472 1
        $bundlename = 'App';
473 1
        $fs = new Filesystem();
474 1
        $routingFile = $this->apppaths->getSrcPath() . '/../config/routes/' . strtolower($entityform) . '.yml';
475
476 1
        $code = $this->getRoutingCode(str_replace('/', '', $bundlename), $entityform);
477 1
        $fs->dumpFile($routingFile, $code);
478
479 1
        $dest = $this->apppaths->getSrcPath() . '/../config/routes.yaml';
480
481 1
        $routingContext = str_replace('/', '', $bundlename) . '_' . $entityform . ':' . "\n" .
482 1
                '  resource: routes/' . strtolower($entityform) . '.yml' . "\n" .
483 1
                '  prefix: /' . $entityform . "\n\n";
484
485
        //Si fa l'append nel file routing del bundle per aggiungerci le rotte della tabella che stiamo gestendo
486 1
        $fh = file_get_contents($dest);
487 1
        if (false !== $fh) {
488 1
            file_put_contents($dest, $routingContext . $fh);
489 1
            $retmsg = 'Routing ' . $dest . " generato automaticamente da pannelloammonistrazionebundle\n\n* * * * CLEAR CACHE * * * *\n";
490
        } else {
491
            $retmsg = 'Impossibile generare il ruoting automaticamente da pannelloammonistrazionebundle\n';
492
        }
493
494 1
        return $retmsg;
495
    }
496
497 1
    private function copyTableStructureWiew(string $entityform): void
498
    {
499 1
        $fs = new Filesystem();
500
        /* $publicfolder = $this->apppaths->getPublicPath();
501
502
          if (!$fs->exists($publicfolder . "/js")) {
503
          $fs->mkdir($publicfolder . "/js", 0777);
504
          }
505
506
          if (!$fs->exists($publicfolder . "/css")) {
507
          $fs->mkdir($publicfolder . "/css", 0777);
508
          } */
509
510 1
        $templatetablefolder = $this->apppaths->getTemplatePath() . DIRECTORY_SEPARATOR . $entityform;
511 1
        $crudfolder = $this->kernel->locateResource('@BiCoreBundle')
512 1
                . DIRECTORY_SEPARATOR . 'Resources/views/Standard/Crud';
513 1
        $tabellafolder = $this->kernel->locateResource('@BiCoreBundle')
514 1
                . DIRECTORY_SEPARATOR . 'Resources/views/Standard/Tabella';
515
516 1
        $fs->mirror($crudfolder, $templatetablefolder . '/Crud');
517 1
        if ($this->generatemplate) {
518
            $fs->mirror($tabellafolder, $templatetablefolder . '/Tabella');
519
        }
520
521
        //$fs->touch($publicfolder . DIRECTORY_SEPARATOR . "js" . DIRECTORY_SEPARATOR . $entityform . ".js");
522
        //$fs->touch($publicfolder . DIRECTORY_SEPARATOR . "css" . DIRECTORY_SEPARATOR . $entityform . ".css");
523
    }
524
525 1
    private function generateFormsDefaultTableValues(string $entityform): void
526
    {
527
        //Si inserisce il record di default nella tabella permessi
528 1
        $ruoloAmm = $this->em->getRepository(Ruoli::class)->findOneBy(array('superadmin' => true)); //SuperAdmin
529
530 1
        $newPermesso = new Permessi();
531 1
        $newPermesso->setCrud('crud');
532 1
        $newPermesso->setModulo($entityform);
533 1
        $newPermesso->setRuoli($ruoloAmm);
534 1
        $this->em->persist($newPermesso);
535 1
        $this->em->flush();
536
537 1
        $tabelle = new Colonnetabelle();
538 1
        $tabelle->setNometabella($entityform);
539 1
        $this->em->persist($tabelle);
540 1
        $this->em->flush();
541
    }
542
543
    /**
544
     * Return the portion of code for Controller
545
     */
546 1
    private function getControllerCode(string $bundlename, string $tabella, string $swaggerModel): string
547
    {
548 1
        $code = '';
549 1
        if ($this->isApi) {
550
            $code = $this->getControllerCodeAPI($bundlename, $tabella, $swaggerModel);
551
        } else {
552 1
            $code = $this->getControllerCodeORM($bundlename, $tabella);
553
        }
554 1
        return $code;
555
    }
556
557
    /**
558
     *  It creates a Skeleton for a controller class that extends FiController
559
     *  */
560 1
    private function getControllerCodeORM(string $bundlename, string $tabella): string
561
    {
562 1
        $codeTemplate = <<<EOF
563
<?php
564
namespace [bundle]\Controller;
565
566
use Symfony\Component\HttpFoundation\Request;
567
use Symfony\Component\HttpFoundation\Response;
568
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
569
use Cdf\BiCoreBundle\Controller\FiController;
570
use Cdf\BiCoreBundle\Utils\Tabella\ParametriTabella;
571
use [bundle]\Entity\[tabella];
572
use [bundle]\Form\[tabella]Type;
573
                
574
/**
575
* [tabella] controller.
576
*
577
*/
578
579
class [tabella]Controller extends FiController {
580
581
}
582 1
EOF;
583 1
        $codebundle = str_replace('[bundle]', $bundlename, $codeTemplate);
584 1
        $code = str_replace('[tabella]', $tabella, $codebundle);
585
586 1
        return $code;
587
    }
588
589
    /**
590
     *  It creates a Skeleton for a controller class that extends ApiController
591
     *  */
592
    private function getControllerCodeAPI(string $bundlename, string $tabella, string $modelPath): string
593
    {
594
        $projectname = $this->projectname;
595
        $codeTemplate = <<<EOF
596
<?php
597
namespace [bundle]\Controller;
598
599
use Symfony\Component\HttpFoundation\Request;
600
use Symfony\Component\HttpFoundation\Response;
601
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
602
use Cdf\BiCoreBundle\Controller\FiApiController;
603
use Cdf\BiCoreBundle\Utils\Tabella\ParametriTabella;
604
use [modelPath];
605
use [bundle]\Form\[tabella]Type;
606
                
607
/**
608
* [tabella] controller.
609
* @var(biproject="$projectname")
610
*/
611
612
class [tabella]Controller extends FiApiController {
613
614
}
615
EOF;
616
        $codebundle = str_replace('[bundle]', $bundlename, $codeTemplate);
617
        $codebundle = str_replace('[modelPath]', $modelPath, $codebundle);
618
        $code = str_replace('[tabella]', $tabella, $codebundle);
619
620
        return $code;
621
    }
622
623 1
    private function getRoutingCode(string $bundlename, string $tabella): string
624
    {
625 1
        $codeTemplate = <<<'EOF'
626
[tabella]_container:
627
    path:  /
628
    controller: '[bundle]\Controller\[tabella]Controller::index'
629
630
[tabella]_lista:
631
    path:  /lista
632
    controller: '[bundle]\Controller\[tabella]Controller::lista'
633
    options:
634
        expose: true
635
636
[tabella]_indexdettaglio:
637
    path:  /indexDettaglio
638
    controller: '[bundle]\Controller\[tabella]Controller::indexDettaglio'
639
    options:
640
        expose: true
641
642
[tabella]_new:
643
    path:  /new
644
    controller: '[bundle]\Controller\[tabella]Controller::new'
645
    methods:    GET|POST
646
647
[tabella]_edit:
648
    path:  /{id}/edit
649
    controller: '[bundle]\Controller\[tabella]Controller::edit'
650
651
[tabella]_update:
652
    path:  /{id}/update
653
    controller: '[bundle]\Controller\[tabella]Controller::update'
654
    methods:    POST|PUT
655
656
[tabella]_aggiorna:
657
    path:  /{id}/{token}/aggiorna
658
    controller: '[bundle]\Controller\[tabella]Controller::aggiorna'
659
    methods:    POST|PUT
660
    options:
661
        expose: true
662
663
[tabella]_delete:
664
    path:  /{id}/{token}/delete
665
    controller: '[bundle]\Controller\[tabella]Controller::delete'
666
    methods:    POST|DELETE
667
668
[tabella]_deletemultiple:
669
    path:  /{token}/delete
670
    controller: '[bundle]\Controller\[tabella]Controller::delete'
671
    methods:    POST|DELETE
672
673
[tabella]_tabella:
674
    path:  /tabella
675
    controller: '[bundle]\Controller\[tabella]Controller::tabella'
676
    methods:    POST
677 1
EOF;
678 1
        $codebundle = str_replace('[bundle]', $bundlename, $codeTemplate);
679 1
        $code = str_replace('[tabella]', $tabella, $codebundle);
680
681 1
        return $code;
682
    }
683
}
684