-
Notifications
You must be signed in to change notification settings - Fork 98
Expand file tree
/
Copy pathPluginCommand.php
More file actions
438 lines (384 loc) · 14.5 KB
/
PluginCommand.php
File metadata and controls
438 lines (384 loc) · 14.5 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
<?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\Process;
use Bake\Utility\TemplateRenderer;
use Bake\View\BakeView;
use Cake\Command\PluginLoadCommand;
use Cake\Console\Arguments;
use Cake\Console\ConsoleIo;
use Cake\Console\ConsoleOptionParser;
use Cake\Core\App;
use Cake\Core\Configure;
use Cake\Core\Plugin;
use Cake\Utility\Filesystem;
use Cake\Utility\Inflector;
use RuntimeException;
use function Cake\Core\env;
/**
* The Plugin Command handles creating an empty plugin, ready to be used
*/
class PluginCommand extends BakeCommand
{
/**
* Plugin path.
*
* @var string
*/
public string $path;
protected bool $isVendor = false;
/**
* 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
{
$name = $args->getArgument('name');
if (empty($name)) {
$io->error('You must provide a plugin name in CamelCase format.');
$io->out('To make an "MyExample" plugin, run <info>`cake bake plugin MyExample`</info>.');
return static::CODE_ERROR;
}
$parts = explode('/', $name);
$plugin = implode('/', array_map([Inflector::class, 'camelize'], $parts));
if ($args->getOption('standalone-path')) {
$this->path = $args->getOption('standalone-path');
$this->path = rtrim($this->path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
$this->isVendor = true;
if (!is_dir($this->path)) {
$io->error(sprintf('Path `%s` does not exist.', $this->path));
return static::CODE_ERROR;
}
}
$pluginPath = $this->_pluginPath($plugin);
if (is_dir($pluginPath) && !$args->getOption('class-only')) {
$io->out(sprintf('Plugin: %s already exists, no action taken', $plugin));
$io->out(sprintf('Path: %s', $pluginPath));
return static::CODE_ERROR;
}
if (!$this->bake($plugin, $args, $io)) {
$io->error(sprintf('An error occurred trying to bake: %s in %s', $plugin, $this->path . $plugin));
$this->abort();
}
return static::CODE_SUCCESS;
}
/**
* Bake the plugin's contents
*
* Also update the autoloader and the root composer.json file if it can be found
*
* @param string $plugin Name of the plugin in CamelCased format
* @param \Cake\Console\Arguments $args The command arguments.
* @param \Cake\Console\ConsoleIo $io The console io
* @return bool|null
*/
public function bake(string $plugin, Arguments $args, ConsoleIo $io): ?bool
{
if (!$this->isVendor) {
$pathOptions = App::path('plugins');
$this->path = current($pathOptions);
if (count($pathOptions) > 1) {
$this->findPath($pathOptions, $io);
}
}
$io->out(sprintf('<info>Plugin Name:</info> %s', $plugin));
$io->out(sprintf('<info>Plugin Directory:</info> %s', $this->path . $plugin));
$io->hr();
$looksGood = $io->askChoice('Look okay?', ['y', 'n', 'q'], 'y');
if (strtolower($looksGood) !== 'y') {
return null;
}
$this->_generateFiles($plugin, $this->path, $args, $io);
if (!$this->isVendor) {
if (!$args->getOption('class-only')) {
$this->_modifyApplication($plugin, $io);
}
$composer = $this->findComposer($args, $io);
try {
$cwd = getcwd();
// Windows makes running multiple commands at once hard.
chdir(dirname($this->_rootComposerFilePath()));
$command = 'php ' . escapeshellarg($composer) . ' dump-autoload';
$process = new Process($io);
$io->out($process->call($command));
chdir($cwd);
} catch (RuntimeException $e) {
$error = $e->getMessage();
$io->error(sprintf('Could not run `composer dump-autoload`: %s', $error));
$this->abort();
}
}
$io->hr();
$io->out(sprintf('<success>Created:</success> %s in %s', $plugin, $this->path . $plugin), 2);
$emptyFile = $this->path . '.gitkeep';
$this->deleteEmptyFile($emptyFile, $io);
return true;
}
/**
* Modify the application class
*
* @param string $plugin Name of plugin the plugin.
* @param \Cake\Console\ConsoleIo $io ConsoleIo
* @return void
*/
protected function _modifyApplication(string $plugin, ConsoleIo $io): void
{
$this->executeCommand(PluginLoadCommand::class, [$plugin], $io);
}
/**
* Generate all files for a plugin
*
* Find the first path which contains `src/Template/Bake/Plugin` that contains
* something, and use that as the template to recursively render a plugin's
* contents. Allows the creation of a bake them containing a `Plugin` folder
* to provide customized bake output for plugins.
*
* @param string $pluginName the CamelCase name of the plugin
* @param string $path the path to the plugins dir (the containing folder)
* @param \Cake\Console\Arguments $args CLI arguments.
* @param \Cake\Console\ConsoleIo $io The io instance.
* @return void
*/
protected function _generateFiles(
string $pluginName,
string $path,
Arguments $args,
ConsoleIo $io,
): void {
$namespace = str_replace('/', '\\', $pluginName);
$baseNamespace = Configure::read('App.namespace');
$name = $pluginName;
$vendor = 'your-name-here';
if (str_contains($pluginName, '/')) {
[$vendor, $name] = explode('/', $pluginName);
}
$package = Inflector::dasherize($vendor) . '/' . Inflector::dasherize($name);
$composerConfig = json_decode(
file_get_contents(ROOT . DS . 'composer.json'),
true,
);
$renderer = $this->createTemplateRenderer()
->set([
'name' => $name,
'package' => $package,
'namespace' => $namespace,
'baseNamespace' => $baseNamespace,
'plugin' => $pluginName,
'routePath' => Inflector::dasherize($pluginName),
'path' => $path,
'root' => ROOT,
'cakeVersion' => $composerConfig['require']['cakephp/cakephp'],
]);
$root = $path . $pluginName . DS;
$paths = [];
if ($args->hasOption('theme')) {
$paths[] = Plugin::templatePath($args->getOption('theme'));
}
$paths = array_merge($paths, Configure::read('App.paths.templates'));
$paths[] = Plugin::templatePath('Bake');
$fs = new Filesystem();
$templates = [];
do {
$templatesPath = array_shift($paths) . BakeView::BAKE_TEMPLATE_FOLDER . '/Plugin';
if (is_dir($templatesPath)) {
$files = iterator_to_array(
$fs->findRecursive($templatesPath, '/\.twig$/'),
);
if (!$this->isVendor) {
$vendorFiles = [
'.gitignore.twig', 'README.md.twig', 'composer.json.twig', 'phpunit.xml.dist.twig',
'bootstrap.php.twig', 'schema.sql.twig',
];
foreach ($files as $key => $file) {
if (in_array($file->getFilename(), $vendorFiles, true)) {
unset($files[$key]);
}
}
}
if ($args->getOption('class-only')) {
$files = array_filter($files, function ($file) {
return $file->getFilename() === 'Plugin.php.twig';
});
}
$templates = array_keys($files);
}
} while (!$templates);
sort($templates);
foreach ($templates as $template) {
$template = substr($template, strrpos($template, 'Plugin' . DIRECTORY_SEPARATOR) + 7, -4);
$template = rtrim($template, '.');
$filename = $template;
if ($filename === 'src' . DIRECTORY_SEPARATOR . 'Plugin.php') {
$filename = 'src' . DIRECTORY_SEPARATOR . $name . 'Plugin.php';
}
$this->_generateFile($renderer, $template, $root, $filename, $io);
}
}
/**
* Generate a file
*
* @param \Bake\Utility\TemplateRenderer $renderer The renderer to use.
* @param string $template The template to render
* @param string $root The path to the plugin's root
* @param string $filename Filename to generate.
* @param \Cake\Console\ConsoleIo $io The io instance.
* @return void
*/
protected function _generateFile(
TemplateRenderer $renderer,
string $template,
string $root,
string $filename,
ConsoleIo $io,
): void {
$io->out(sprintf('Generating %s file...', $template));
$out = $renderer->generate('Bake.Plugin/' . $template);
$io->createFile($root . $filename, $out);
}
/**
* The path to the main application's composer file
*
* This is a test isolation wrapper
*
* @return string the abs file path
*/
protected function _rootComposerFilePath(): string
{
return ROOT . DS . 'composer.json';
}
/**
* find and change $this->path to the user selection
*
* @param array<string> $pathOptions The list of paths to look in.
* @param \Cake\Console\ConsoleIo $io The io object
* @return void
*/
public function findPath(array $pathOptions, ConsoleIo $io): void
{
$valid = false;
foreach ($pathOptions as $i => $path) {
if (!is_dir($path)) {
unset($pathOptions[$i]);
}
}
$pathOptions = array_values($pathOptions);
$max = count($pathOptions);
if ($max === 0) {
$io->error('No valid plugin paths found! Please configure a plugin path that exists.');
$this->abort();
}
if ($max === 1) {
$this->path = $pathOptions[0];
return;
}
$choice = 0;
while (!$valid) {
foreach ($pathOptions as $i => $option) {
$io->out($i + 1 . '. ' . $option);
}
$prompt = 'Choose a plugin path from the paths above.';
$choice = (int)$io->ask($prompt);
if ($choice > 0 && $choice <= $max) {
$valid = true;
}
}
$this->path = $pathOptions[$choice - 1];
}
/**
* Gets the option parser instance and configures it.
*
* @param \Cake\Console\ConsoleOptionParser $parser The option parser
* @return \Cake\Console\ConsoleOptionParser
*/
public function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionParser
{
$parser->setDescription(
'Create the directory structure, AppController class and testing setup for a new plugin. ' .
'Can create plugins in any of your bootstrapped plugin paths.',
)->addArgument('name', [
'help' => 'CamelCased name of the plugin to create.'
. ' For standalone plugins you can use vendor prefixed names like MyVendor/MyPlugin.',
])->addOption('composer', [
'default' => ROOT . DS . 'composer.phar',
'help' => 'The path to the composer executable.',
])->addOption('force', [
'short' => 'f',
'boolean' => true,
'help' => 'Force overwriting existing files without prompting.',
])->addOption('theme', [
'short' => 't',
'help' => 'The theme to use when baking code.',
'default' => Configure::read('Bake.theme') ?: null,
'choices' => $this->_getBakeThemes(),
])
->addOption('standalone-path', [
'short' => 'p',
'help' => 'Generate a standalone plugin in the provided path.',
])->addOption('class-only', [
'short' => 'c',
'boolean' => true,
'help' => 'Generate only the plugin class.',
]);
return $parser;
}
/**
* Uses either the CLI option or looks in $PATH and cwd for composer.
*
* @param \Cake\Console\Arguments $args The command arguments.
* @param \Cake\Console\ConsoleIo $io The console io
* @return string|bool Either the path to composer or false if it cannot be found.
*/
public function findComposer(Arguments $args, ConsoleIo $io): string|bool
{
if ($args->hasOption('composer')) {
/** @var string $path */
$path = $args->getOption('composer');
if (file_exists($path)) {
return $path;
}
}
$composer = false;
$path = env('PATH');
if (!empty($path)) {
$paths = explode(PATH_SEPARATOR, $path);
$composer = $this->_searchPath($paths, $io);
}
return $composer;
}
/**
* Search the $PATH for composer.
*
* @param array<string> $path The paths to search.
* @param \Cake\Console\ConsoleIo $io The console io
* @return string|bool
*/
protected function _searchPath(array $path, ConsoleIo $io): string|bool
{
$composer = ['composer.phar', 'composer'];
foreach ($path as $dir) {
foreach ($composer as $cmd) {
if (is_file($dir . DS . $cmd)) {
$io->verbose('Found composer executable in ' . $dir);
return $dir . DS . $cmd;
}
}
}
return false;
}
}