-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathModuleCreateCommand.php
More file actions
608 lines (526 loc) · 20.8 KB
/
ModuleCreateCommand.php
File metadata and controls
608 lines (526 loc) · 20.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
<?php
/**
* This file is part of the PPI Framework.
*
* @copyright Copyright (c) 2011-2016 Paul Dragoonis <paul@ppi.io>
* @license http://opensource.org/licenses/mit-license.php MIT
*
* @link http://www.ppi.io
*/
namespace PPI\Framework\Console\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ChoiceQuestion;
use Symfony\Component\Console\Question\ConfirmationQuestion;
/**
* Module Command.
*
* @author Paul Dragoonis <paul@ppi.io>
* @author Vítor Brandão <vitor@ppi.io>
*/
class ModuleCreateCommand extends AbstractCommand
{
const TPL_ENGINE_LATTE = 'latte';
const TPL_ENGINE_PLATES = 'plates';
const TPL_ENGINE_PHP = 'php';
const TPL_ENGINE_TWIG = 'twig';
const TPL_ENGINE_SMARTY = 'smarty';
const ROUTING_ENGINE_SYMFONY = 'symfony';
const ROUTING_ENGINE_AURA = 'aura';
const ROUTING_ENGINE_LARAVEL = 'laravel';
const ROUTING_ENGINE_FASTROUTE = 'fastroute';
const ROUTING_ENGINE_NULL = 'NullRouter';
protected $skeletonModuleDir;
protected $modulesDir;
protected $moduleDir;
protected $moduleName;
protected $tplEngine;
protected $routingEngine;
protected $configEnabledTemplatingEngines = [];
/**
* @var array
*/
protected $coreDirs = [
'src',
'src/Controller',
'tests',
'resources',
'resources/config'
];
/**
* @var array
*/
protected $coreFiles = [
'Module.php',
'resources/config/config.php',
];
protected $tplEngineCoreFiles = [
'resources/views',
'resources/views/index'
];
protected $routingEngineCoreFiles = [
'resources/routes'
];
/**
* @var array
*/
protected $tplEngineFilesMap = [
self::TPL_ENGINE_LATTE => [
'resources/views/index/index.html.latte',
],
self::TPL_ENGINE_PLATES => [
'resources/views/index/index.html.plates',
],
self::TPL_ENGINE_PHP => [
'resources/views/index/index.html.php',
],
self::TPL_ENGINE_TWIG => [
'resources/views/index/base.html.twig',
'resources/views/index/index.html.twig',
],
self::TPL_ENGINE_SMARTY => [
'resources/views/index/base.html.smarty',
'resources/views/index/index.html.smarty',
],
];
protected $routingEngineFilesMap = [
self::ROUTING_ENGINE_SYMFONY => [
'src/Controller/Index.php',
'src/Controller/Shared.php',
'resources/routes/symfony.yml'
],
self::ROUTING_ENGINE_AURA => [
'src/Controller/Index.php',
'src/Controller/Shared.php',
'resources/routes/aura.php',
],
self::ROUTING_ENGINE_LARAVEL => [
'src/Controller/Index.php',
'src/Controller/Shared.php',
'resources/routes/laravel.php',
],
self::ROUTING_ENGINE_FASTROUTE => [
'src/Controller/IndexInvoke.php',
'src/Controller/Shared.php',
'resources/routes/fastroute.php',
],
];
protected $routingEngineTokenMap = [
self::ROUTING_ENGINE_AURA => [
'[ROUTING_LOAD_METHOD]' => 'loadAuraRoutes',
'[ROUTING_DEF_FILE]' => 'aura.php',
'[ROUTING_GETROUTES_RETVAL]' => '\Aura\Router\Router',
],
self::ROUTING_ENGINE_LARAVEL => [
'[ROUTING_LOAD_METHOD]' => 'loadLaravelRoutes',
'[ROUTING_DEF_FILE]' => 'laravel.php',
'[ROUTING_GETROUTES_RETVAL]' => '\Illuminate\Routing\Router',
],
self::ROUTING_ENGINE_FASTROUTE => [
'[ROUTING_LOAD_METHOD]' => 'loadFastRouteRoutes',
'[ROUTING_DEF_FILE]' => 'fastroute.php',
'[ROUTING_GETROUTES_RETVAL]' => '\PPI\FastRoute\Wrapper\FastRouteWrapper',
],
];
/**
* @param string $moduleDir
*/
public function setSkeletonModuleDir($moduleDir)
{
$this->skeletonModuleDir = realpath($moduleDir);
}
/**
* @param string $moduleDir
*
* @return void
*/
public function setTargetModuleDir($moduleDir)
{
$this->modulesDir = realpath($moduleDir);
}
/**
* @param array $tplEngines
*
* @return void
*/
public function setEnabledTemplatingEngines(array $tplEngines)
{
$this->configEnabledTemplatingEngines = $tplEngines;
}
/**
* @return void
*/
protected function configure()
{
$this->setName('module:create')
->setDescription('Create a module')
->addArgument('name', InputArgument::REQUIRED, 'What is your module name?')
->addOption('dir', null, InputOption::VALUE_OPTIONAL, 'Specify the modules directory')
->addOption('tpl', null, InputOption::VALUE_OPTIONAL, 'Specify the templating engine')
->addOption('routing', null, InputOption::VALUE_OPTIONAL, 'Specify the routing engine');
}
/**
* @param InputInterface $input
* @param OutputInterface $output
* @throws \Exception
* @return void
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->moduleName = $input->getArgument('name');
$this->moduleDir = $this->modulesDir . DIRECTORY_SEPARATOR . $this->moduleName;
// Acquire Module Information
$this->askQuestions($input, $output);
$this->createModuleStructure($this->moduleDir, $this->moduleName);
$output->writeln("<info>Created module successfully</info>");
$output->writeln("Name: <info>{$this->moduleName}</info>");
$output->writeln(sprintf("Path: <info>%s</info>", $this->moduleDir));
// Copy the core files
$this->copyFiles($this->skeletonModuleDir, $this->moduleDir, $this->coreFiles);
$tokenizedFiles = $this->getTokenizedCoreFiles();
$tokens = [];
$tokens['[MODULE_NAME]'] = $this->moduleName;
if(null !== $this->tplEngine && $this->isValidTemplatingEngine($this->tplEngine)) {
$this->processTemplatingFiles();
$output->writeln(sprintf("Templating: <info>%s</info>", $this->tplEngine));
}
if($this->isValidRoutingEngine($this->routingEngine)) {
$this->processRoutingFiles($tokenizedFiles, $tokens);
$output->writeln(sprintf("Router: <info>%s</info>", $this->routingEngine));
} else {
$tokens['[ROUTING_TRAIT]'] = '';
}
// replace tokens from specified tokenizable files
$this->replaceTokensInFiles($this->moduleDir, $tokenizedFiles, $tokens);
$output->writeln("<comment>This module is not enabled. Enable it in <info>config[modules]</info> key</comment>");
$this->checkEnabledTemplatingEngines($input, $output);
$this->checkEnabledRouters($input, $output);
}
protected function isValidTemplatingEngine($tplEngine)
{
return in_array($tplEngine, [
self::TPL_ENGINE_LATTE,
self::TPL_ENGINE_PLATES,
self::TPL_ENGINE_PHP,
self::TPL_ENGINE_SMARTY,
self::TPL_ENGINE_TWIG,
]);
}
protected function isValidRoutingEngine($routingEngine)
{
return in_array($routingEngine, [
self::ROUTING_ENGINE_SYMFONY,
self::ROUTING_ENGINE_AURA,
self::ROUTING_ENGINE_LARAVEL,
self::ROUTING_ENGINE_FASTROUTE,
self::ROUTING_ENGINE_NULL,
]);
}
/**
* @param string $moduleDir
* @param array $files
* @param array $tokens
*/
protected function replaceTokensInFiles($moduleDir, $files, $tokens)
{
foreach ($files as $file) {
$file = $moduleDir . DIRECTORY_SEPARATOR . $file;
if (!is_writeable($file)) {
throw new \InvalidArgumentException(sprintf('File %s is not writeable', $file));
}
file_put_contents($file, str_replace(array_keys($tokens), array_values($tokens), file_get_contents($file)));
}
}
/**
* @param string $skeletonDir
* @param string $moduleDir
* @param array $files
*
* @throws \InvalidArgumentException When a file path being created already exists
*/
protected function copyFiles($skeletonDir, $moduleDir, $files)
{
foreach ($files as $file) {
$srcFile = $skeletonDir . DIRECTORY_SEPARATOR . $file;
$dstFile = $moduleDir . DIRECTORY_SEPARATOR . $file;
if (!file_exists($srcFile)) {
throw new \InvalidArgumentException(sprintf('File does not exist: %s', $srcFile));
}
if (file_exists($dstFile)) {
throw new \InvalidArgumentException(sprintf('File already exists: %s', $dstFile));
}
copy($srcFile, $dstFile);
}
}
/**
* @param string $moduleDir
* @param string $moduleName
*
* @throws \InvalidArgumentException When a dir path being created already exists
*/
protected function createModuleStructure($moduleDir, $moduleName)
{
if (is_dir($moduleDir)) {
throw new \InvalidArgumentException(sprintf('Unable to create module: %s it already exists at %s%s', $moduleName, $moduleDir, $moduleName));
}
@mkdir($moduleDir);
// Create base structure
foreach ($this->coreDirs as $coreDir) {
$tmpDir = $moduleDir . DIRECTORY_SEPARATOR . $coreDir;
@mkdir($tmpDir);
}
}
/**
* @param InputInterface $input
* @param OutputInterface $output
*/
protected function askQuestions(InputInterface $input, OutputInterface $output)
{
$questionHelper = $this->getHelper('question');
// Module DIR
if ($input->getOption('dir') == null) {
$modulesDirQuestion = new ChoiceQuestion('Where is the modules dir?', [1 => $this->modulesDir], $this->modulesDir);
$modulesDirQuestion->setErrorMessage('Modules dir: %s is invalid.');
$this->modulesDir = $questionHelper->ask($input, $output, $modulesDirQuestion);
}
if($this->askForTemplating($input, $output)) {
$this->chooseTemplatingEngine($input, $output);
}
if($this->askForContoller($input, $output)) {
if($this->askForRouting($input, $output)) {
return $this->chooseRouter($input, $output);
}
}
}
/**
* @param InputInterface $input
* @param OutputInterface $output
*/
private function checkEnabledRouters(InputInterface $input, OutputInterface $output)
{
// Aura Check
if ($this->routingEngine == self::ROUTING_ENGINE_AURA && !class_exists('\Aura\Router\Router')) {
$output->writeln("<comment>Aura Router doesn't appear to be loaded. Run: <info>composer require ppi/aura-router</info></comment>");
}
// Laravel check
if ($this->routingEngine == self::ROUTING_ENGINE_LARAVEL && !class_exists('\PPI\LaravelRouting\LaravelRouter')) {
$output->writeln("<comment>Laravel Router doesn't appear to be loaded. Run: <info>composer require ppi/laravel-router</info></comment>");
}
if ($this->routingEngine == self::ROUTING_ENGINE_FASTROUTE && !class_exists('\PPI\FastRoute\Wrapper\FastRouteWrapper')) {
$output->writeln("<comment>FastRoute Router doesn't appear to be loaded. Run: <info>composer require ppi/fast-route</info></comment>");
}
}
/**
* @param InputInterface $input
* @param OutputInterface $output
*/
private function checkEnabledTemplatingEngines(InputInterface $input, OutputInterface $output)
{
// PHP Templating Engine checks
if ($this->tplEngine == self::TPL_ENGINE_PHP) {
if (!in_array($this->tplEngine, $this->configEnabledTemplatingEngines)) {
$output->writeln(sprintf("<comment>PHP is not an enabled templating engine. Add <info>%s</info> it in <info>config[framework][templating][engines]</info> key</comment>", $this->tplEngine));
}
}
// Twig Checks
if ($this->tplEngine == self::TPL_ENGINE_TWIG) {
if (!in_array($this->tplEngine, $this->configEnabledTemplatingEngines)) {
$output->writeln(sprintf("<comment>Twig is not an enabled templating engine. Add <info>%s</info> it in <info>config[framework][templating][engines]</info> key</comment>", $this->tplEngine));
}
if (!class_exists('\Twig_Environment')) {
$output->writeln("<comment>Twig doesn't appear to be loaded. Run: <info>composer require ppi/twig-module</info></comment>");
}
}
// Smarty Checks
if ($this->tplEngine == self::TPL_ENGINE_SMARTY) {
if (!in_array($this->tplEngine, $this->configEnabledTemplatingEngines)) {
$output->writeln(sprintf("<comment>Smarty is not an enabled templating engine. Add <info>%s</info> it in <info>config[framework][templating][engines]</info> key</comment>", $this->tplEngine));
}
if (!class_exists('\Smarty')) {
$output->writeln("<comment>Smarty doesn't appear to be loaded. Run: <info>composer require ppi/smarty-module</info></comment>");
}
}
// Plates Checks
if ($this->tplEngine == self::TPL_ENGINE_PLATES) {
if (!in_array($this->tplEngine, $this->configEnabledTemplatingEngines)) {
$output->writeln(sprintf("<comment>Plates is not an enabled templating engine. Add <info>%s</info> it in <info>config[framework][templating][engines]</info> key</comment>", $this->tplEngine));
}
if (!class_exists('\PPI\PlatesModule\Wrapper\PlatesWrapper')) {
$output->writeln("<comment>Plates doesn't appear to be loaded. Run: <info>composer require ppi/plates-module</info></comment>");
}
}
// Plates Checks
if ($this->tplEngine == self::TPL_ENGINE_LATTE) {
if (!in_array($this->tplEngine, $this->configEnabledTemplatingEngines)) {
$output->writeln(sprintf("<comment>Latte is not an enabled templating engine. Add <info>%s</info> it in <info>config[framework][templating][engines]</info> key</comment>", $this->tplEngine));
}
if (!class_exists('\PPI\LatteModule\Wrapper\LatteWrapper')) {
$output->writeln("<comment>Latte doesn't appear to be loaded. Run: <info>composer require ppi/latte-module</info></comment>");
}
}
}
/**
* @param InputInterface $input
* @param OutputInterface $output
* @return boolean
*/
private function askForTemplating(InputInterface $input, OutputInterface $output)
{
$questionHelper = $this->getHelper('question');
$question = new ConfirmationQuestion("Do you need templates? (yes/no):\n", false);
return $questionHelper->ask($input, $output, $question);
}
private function askForRouting(InputInterface $input, OutputInterface $output)
{
$questionHelper = $this->getHelper('question');
$question = new ConfirmationQuestion("Which router do you want? (yes/no):\n", false);
return $questionHelper->ask($input, $output, $question);
}
private function chooseTemplatingEngine($input, $output)
{
$tplQuestion = new ChoiceQuestion('Choose your templating engine [php]',
[
1 => 'php',
2 => 'twig',
3 => 'smarty',
4 => 'plates',
5 => 'latte',
99 => 'skip'
]
);
$tplQuestion->setErrorMessage('Templating engine %s is invalid.');
if(99 !== ($tplEngine = $this->getHelper('question')->ask($input, $output, $tplQuestion))) {
$this->tplEngine = $tplEngine;
}
}
/**
* @param InputInterface $input
* @param OutputInterface $output
*
* @return void
*/
private function chooseRouter(InputInterface $input, OutputInterface $output)
{
$routingQuestion = new ChoiceQuestion('Choose your routing engine:',
[
1 => self::ROUTING_ENGINE_SYMFONY,
2 => self::ROUTING_ENGINE_AURA,
3 => self::ROUTING_ENGINE_LARAVEL,
4 => self::ROUTING_ENGINE_FASTROUTE,
99 => 'skip'
]
);
// @todo - test question when you don't choose any option, or an invalid one (like -1)
$routingQuestion->setErrorMessage('Routing engine %s is invalid.');
$chosenRouter = $this->getHelper('question')->ask($input, $output, $routingQuestion);
if(99 == $chosenRouter) {
$chosenRouter = 'NullRouter';
}
$this->routingEngine = $chosenRouter;
}
/**
* @param $tplEngine
*
* @return void
*/
private function getTemplatingFilesFromEngine($tplEngine)
{
if(!isset($this->tplEngineFilesMap[$tplEngine])) {
throw new \InvalidArgumentException('Invalid templating engine specified for map files: ' . $tplEngine);
}
}
/**
* @return void
*/
private function processTemplatingFiles()
{
$tplFiles = $this->getTemplatingFilesFromEngine($this->tplEngine);
// Copy core templating files over
foreach($this->tplEngineCoreFiles as $coreFile) {
$tplFiles[] = $coreFile;
}
// Copy templating files over relevant to the specified engine
$this->copyFiles($this->skeletonModuleDir, $this->moduleDir, $tplFiles);
// Setting up templating tokens
$tokenizedFiles = [];
foreach ($tplFiles as $tplFile) {
$tokenizedFiles[] = $tplFile;
}
$tokens['[TPL_ENGINE_EXT]'] = $this->tplEngine;
$this->replaceTokensInFiles($this->moduleDir, $tokenizedFiles, $tokens);
}
/**
* @throws \Exception
*
* @return void
*/
private function processRoutingFiles($tokenizedFiles, $tokens)
{
if(!isset($this->routingEngineFilesMap[$this->routingEngine])) {
throw new \Exception('Routing engine not found in routing files map: ' . $this->routingEngine);
}
// Copy routing files over
$routingFiles = $this->routingEngineFilesMap[$this->routingEngine];
// If a valid routing engine and that's not null router
if($this->routingEngine !== 99) {
// Create core routing directories
foreach($this->routingEngineCoreFiles as $coreFile) {
@mkdir($this->moduleDir . DIRECTORY_SEPARATOR . $coreFile);
}
}
//var_dump(__METHOD__, __LINE__, $routingFiles); exit;
$this->copyFiles($this->skeletonModuleDir, $this->moduleDir, $routingFiles);
// Setting up routing tokenizable files
foreach ($routingFiles as $routingFile) {
$tokenizedFiles[] = $routingFile;
}
// Get all the tokens for this routing engine and the values the map to.
$routingTokensMap = $this->getRoutingTokenMap($this->routingEngine);
foreach ($routingTokensMap as $routingTokenKey => $routingTokenVal) {
$tokens[$routingTokenKey] = $routingTokenVal;
}
// Replace tokens in all files
$this->replaceTokensInFiles($this->moduleDir, $tokenizedFiles, $tokens);
// Replace the ROUTING placeholder with this heredoc
// Prepare the fastroute route file
if ($this->routingEngine === self::ROUTING_ENGINE_FASTROUTE) {
rename(
$moduleDir . DIRECTORY_SEPARATOR . $routingFiles[0],
str_replace('IndexInvoke', 'Index', $moduleDir . DIRECTORY_SEPARATOR . $routingFiles[0]
));
}
}
/**
* @return array
*/
protected function getTokenizedCoreFiles()
{
$files = [];
foreach ($this->coreFiles as $coreFile) {
$files[] = $coreFile;
}
return $files;
}
/**
* @param $routingEngine
* @return array
* @throws \Exception
*/
private function getRoutingTokenMap($routingEngine) {
// if(!isset($this->routingEngineTokenMap[$routingEngine])) {
// throw new \Exception('No routing engine tokenizable files found for routing engine: ' . $this->routingEngine);
// }
$tokenMap = [];
switch($routingEngine) {
case self::ROUTING_ENGINE_SYMFONY:
$tokenMap['[ROUTING_TRAIT]'] = 'use \PPI\Framework\Module\Routing\SymfonyTrait;';
break;
default:
throw new \Exception('Unimplemented routing engine: ' . $routingEngine);
break;
}
return $tokenMap;
}
}