-
Notifications
You must be signed in to change notification settings - Fork 98
Expand file tree
/
Copy pathTemplateCommand.php
More file actions
472 lines (421 loc) · 14.6 KB
/
TemplateCommand.php
File metadata and controls
472 lines (421 loc) · 14.6 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
<?php
declare(strict_types=1);
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @since 0.1.0
* @license https://www.opensource.org/licenses/mit-license.php MIT License
*/
namespace Bake\Command;
use Bake\Utility\Model\AssociationFilter;
use Bake\Utility\TableScanner;
use Cake\Console\Arguments;
use Cake\Console\ConsoleIo;
use Cake\Console\ConsoleOptionParser;
use Cake\Core\App;
use Cake\Core\Configure;
use Cake\Datasource\ConnectionManager;
use Cake\Datasource\EntityInterface;
use Cake\ORM\Table;
use Cake\Utility\Inflector;
use Cake\View\Exception\MissingTemplateException;
use Exception;
use RuntimeException;
use function Cake\Core\namespaceSplit;
/**
* Task class for creating view template files.
*/
class TemplateCommand extends BakeCommand
{
/**
* Name of the controller being used
*
* @var string
*/
public string $controllerName;
/**
* Classname of the controller being used
*
* @var string
*/
public string $controllerClass;
/**
* Name with plugin of the model being used
*
* @var string
*/
public string $modelName;
/**
* Actions to use for scaffolding
*
* @var array<string>
*/
public array $scaffoldActions = ['index', 'view', 'add', 'edit'];
/**
* Actions that exclude hidden fields
*
* @var array<string>
*/
public array $excludeHiddenActions = ['index', 'view'];
/**
* AssociationFilter utility
*
* @var \Bake\Utility\Model\AssociationFilter|null
*/
protected ?AssociationFilter $_associationFilter = null;
/**
* Template path.
*
* @var string
*/
public string $path;
/**
* Output extension
*
* @var string
*/
public string $ext = 'php';
/**
* Override initialize
*
* @return void
*/
public function initialize(): void
{
parent::initialize();
$templatePaths = App::path('templates');
if ($templatePaths === []) {
throw new RuntimeException(
'Could not read template paths. ' .
'Ensure `App.paths.templates` is defined in your application configuration.',
);
}
$this->path = current($templatePaths);
}
/**
* Execute the command.
*
* @param \Cake\Console\Arguments $args The command arguments.
* @param \Cake\Console\ConsoleIo $io The console io
* @return int|null The exit code or null for success
*/
public function execute(Arguments $args, ConsoleIo $io): ?int
{
$this->extractCommonProperties($args);
$name = $args->getArgument('name') ?? '';
$name = $this->_getName($name);
if (empty($name)) {
$io->out('Possible tables to bake view templates for based on your current database:');
/** @var \Cake\Database\Connection $connection */
$connection = ConnectionManager::get($this->connection);
$scanner = new TableScanner($connection);
foreach ($scanner->listUnskipped() as $table) {
$io->out('- ' . $this->_camelize($table));
}
return static::CODE_SUCCESS;
}
$template = $args->getArgument('template');
$action = $args->getArgument('action');
$this->controller($args, $name, (string)$args->getOption('controller'));
$this->model($name);
if ($template && $action === null) {
$action = $template;
}
if ($template) {
$this->bake($args, $io, $template, true, $action);
return static::CODE_SUCCESS;
}
$vars = $this->_loadController($io);
$methods = $this->_methodsToBake();
foreach ($methods as $method) {
try {
$content = $this->getContent($args, $io, $method, $vars);
$this->bake($args, $io, $method, $content);
} catch (MissingTemplateException $e) {
$io->verbose($e->getMessage());
} catch (RuntimeException $e) {
$io->error($e->getMessage());
}
}
return static::CODE_SUCCESS;
}
/**
* Set the model class for the table.
*
* @param string $table The table/model that is being baked.
* @return void
*/
public function model(string $table): void
{
$tableName = $this->_camelize($table);
$plugin = $this->plugin;
if ($plugin) {
$plugin = $plugin . '.';
}
$this->modelName = $plugin . $tableName;
}
/**
* Set the controller related properties.
*
* @param \Cake\Console\Arguments $args The arguments
* @param string $table The table/model that is being baked.
* @param string|null $controller The controller name if specified.
* @return void
*/
public function controller(Arguments $args, string $table, ?string $controller = null): void
{
$tableName = $this->_camelize($table);
if (empty($controller)) {
$controller = $tableName;
}
$this->controllerName = $controller;
$plugin = $this->plugin;
if ($plugin) {
$plugin .= '.';
}
$prefix = $this->getPrefix($args);
if ($prefix) {
$prefix .= '/';
}
$this->controllerClass = (string)App::className($plugin . $prefix . $controller, 'Controller', 'Controller');
}
/**
* Get the path base for view templates.
*
* @param \Cake\Console\Arguments $args The arguments
* @param string|null $container Unused.
* @return string
*/
public function getTemplatePath(Arguments $args, ?string $container = null): string
{
$path = parent::getTemplatePath($args, $container);
$path .= $this->controllerName . DS;
return $path;
}
/**
* Get a list of actions that can / should have view templates baked for them.
*
* @return array<string> Array of action names that should be baked
*/
protected function _methodsToBake(): array
{
$base = Configure::read('App.namespace');
$methods = [];
if (class_exists($this->controllerClass)) {
$methods = array_diff(
array_map(
'Cake\Utility\Inflector::underscore',
get_class_methods($this->controllerClass),
),
array_map(
'Cake\Utility\Inflector::underscore',
get_class_methods($base . '\Controller\AppController'),
),
);
}
if (empty($methods)) {
$methods = $this->scaffoldActions;
}
foreach ($methods as $i => $method) {
if ($method[0] === '_') {
unset($methods[$i]);
}
}
return $methods;
}
/**
* Loads Controller and sets variables for the template
* Available template variables:
*
* - 'modelObject'
* - 'modelClass'
* - 'entityClass'
* - 'primaryKey'
* - 'displayField'
* - 'singularVar'
* - 'pluralVar'
* - 'singularHumanName'
* - 'pluralHumanName'
* - 'fields'
* - 'keyFields'
* - 'schema'
*
* @param \Cake\Console\ConsoleIo $io Instance of the ConsoleIO
* @return array Returns variables to be made available to a view template
*/
protected function _loadController(ConsoleIo $io): array
{
if ($this->getTableLocator()->exists($this->modelName)) {
$modelObject = $this->getTableLocator()->get($this->modelName);
} else {
$modelObject = $this->getTableLocator()->get($this->modelName, [
'connectionName' => $this->connection,
]);
}
$namespace = Configure::read('App.namespace');
$primaryKey = $displayField = $singularVar = $singularHumanName = null;
$schema = $fields = $hidden = $modelClass = null;
try {
$primaryKey = (array)$modelObject->getPrimaryKey();
$displayField = $modelObject->getDisplayField();
$singularVar = $this->_singularName($this->controllerName);
$singularHumanName = $this->_singularHumanName($this->controllerName);
$schema = $modelObject->getSchema();
$fields = $schema->columns();
$hidden = $modelObject->newEmptyEntity()->getHidden() ?: ['token', 'password', 'passwd'];
$modelClass = $this->modelName;
} catch (Exception $exception) {
$io->error($exception->getMessage());
$this->abort();
}
[, $entityClass] = namespaceSplit($this->_entityName($this->modelName));
$entityClass = sprintf('%s\Model\Entity\%s', $namespace, $entityClass);
if (!class_exists($entityClass)) {
$entityClass = EntityInterface::class;
}
$associations = $this->_filteredAssociations($modelObject);
$keyFields = [];
if (!empty($associations['BelongsTo'])) {
foreach ($associations['BelongsTo'] as $assoc) {
$keyFields[$assoc['foreignKey']] = $assoc['variable'];
}
}
$pluralVar = Inflector::variable($this->controllerName);
$pluralHumanName = $this->_pluralHumanName($this->controllerName);
// Handle cases where singular and plural are identical (e.g., "news", "sheep")
// to avoid generating invalid code like `foreach ($news as $news)`
if ($singularVar === $pluralVar) {
$singularVar .= 'Entity';
}
return compact(
'modelObject',
'modelClass',
'entityClass',
'schema',
'primaryKey',
'displayField',
'singularVar',
'pluralVar',
'singularHumanName',
'pluralHumanName',
'fields',
'hidden',
'associations',
'keyFields',
'namespace',
);
}
/**
* Assembles and writes bakes the view file.
*
* @param \Cake\Console\Arguments $args CLI arguments
* @param \Cake\Console\ConsoleIo $io Console io
* @param string $template Template file to use.
* @param string|true $content Content to write.
* @param ?string $outputFile The output file to create. If null will use `$template`
* @return void
*/
public function bake(
Arguments $args,
ConsoleIo $io,
string $template,
string|bool $content = '',
?string $outputFile = null,
): void {
if ($outputFile === null) {
$outputFile = $template;
}
if ($content === true) {
$content = $this->getContent($args, $io, $template);
}
if (empty($content)) {
// phpcs:ignore Generic.Files.LineLength
$io->warning("No generated content for '{$template}.{$this->ext}', not generating template.");
return;
}
$path = $this->getTemplatePath($args);
$filename = $path . Inflector::underscore($outputFile) . '.' . $this->ext;
$io->out("\n" . sprintf('Baking `%s` view template file...', $outputFile));
$io->createFile($filename, $content, $this->force);
}
/**
* Builds content from template and variables
*
* @param \Cake\Console\Arguments $args The CLI arguments
* @param \Cake\Console\ConsoleIo $io The console io
* @param string $action name to generate content to
* @param array|null $vars passed for use in templates
* @return string Content from template
*/
public function getContent(Arguments $args, ConsoleIo $io, string $action, ?array $vars = null): string
{
if (!$vars) {
$vars = $this->_loadController($io);
}
if (empty($vars['primaryKey'])) {
$io->error('Cannot generate views for models with no primary key');
$this->abort();
}
if (in_array($action, $this->excludeHiddenActions)) {
$vars['fields'] = array_diff($vars['fields'], $vars['hidden']);
}
$renderer = $this->createTemplateRenderer()
->set('action', $action)
->set('plugin', $this->plugin)
->set($vars);
$indexColumns = 0;
if ($action === 'index' && $args->getOption('index-columns') !== null) {
$indexColumns = $args->getOption('index-columns');
}
$renderer->set('indexColumns', $indexColumns);
return $renderer->generate("Bake.Template/$action");
}
/**
* Gets the option parser instance and configures it.
*
* @param \Cake\Console\ConsoleOptionParser $parser The option parser to update.
* @return \Cake\Console\ConsoleOptionParser
*/
public function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionParser
{
$parser = $this->_setCommonOptions($parser);
$parser->setDescription(
'Bake views for a controller, using built-in or custom templates. ',
)->addArgument('name', [
'help' => 'Name of the controller views to bake. You can use Plugin.name as a shortcut for plugin baking.',
])->addArgument('template', [
'help' => "Will bake a single action's file. core templates are (index, add, edit, view)",
])->addArgument('action', [
'help' => 'Will bake the template in <template> but create the filename named <action>.',
])->addOption('controller', [
'help' => 'The controller name if you have a controller that does not follow conventions.',
])->addOption('prefix', [
'help' => 'The routing prefix to generate views for.',
])->addOption('index-columns', [
'help' => 'Limit for the number of index columns',
'default' => '0',
]);
return $parser;
}
/**
* Get filtered associations
* To be mocked...
*
* @param \Cake\ORM\Table $model Table
* @return array associations
*/
protected function _filteredAssociations(Table $model): array
{
if ($this->_associationFilter === null) {
$this->_associationFilter = new AssociationFilter();
}
return $this->_associationFilter->filterAssociations($model);
}
}