Files
core/app/Console/Commands/Modules/CreateNew.php
T

119 lines
3.4 KiB
PHP

<?php
namespace App\Console\Commands\Modules;
use Illuminate\Console\Command;
use Illuminate\Support\Str;
class CreateNew extends Command
{
/**
* The name and signature of the console command.
* @var string
*/
protected $signature = 'module:new
{name : module name}
{parentModule? : name of parent module}
{--entity= : entity}';
/**
* The console command description.
* @var string
*/
protected $description = 'Create new CMS module.';
protected $moduleName;
protected $moduleNamespace;
protected $entity;
protected $entityNamespace;
/**
* Execute the console command.
*/
public function handle()
{
$defaultEntityNamespace = $this->loadArguments();
$path = preg_replace('|/{2,}|i', '/', config('modules.paths.modules') . '/' . $this->moduleNamespace);
if (is_dir($path)) {
$this->error('Module already exists in ' . $path);
return;
}
if (!is_dir($path))
mkdir($path);
// copy stub files
\File::copyDirectory(config('modules.paths.stubs'), $path);
$files = \File::allFiles($path);
foreach ($files as $file) {
$newName = str_replace('stub', 'php', $this->replacePlaceholders($file->getPathname()));
// ignore new entity when using existing entity
if ($this->entityNamespace != $defaultEntityNamespace && Str::contains('Entities', $file)) {
\File::delete($file);
continue;
}
// rename file
\File::move($file, $newName);
// change its content
$content = file_get_contents($newName);
$content = $this->replacePlaceholders($content);
file_put_contents($newName, $content);
}
$this->info('Module successfully created.');
}
/**
* Find and replace all placeholders in given content
*
* @param $content
*
* @return mixed
*/
private function replacePlaceholders($content)
{
$replace = [
'$Module$' => $this->moduleName,
'$ModuleNamespace$' => str_replace('/', '\\', $this->moduleNamespace),
'$module$' => strtolower($this->moduleName),
'$EntityNamespace$' => $this->entityNamespace,
'$Entity$' => $this->entity
];
foreach ($replace as $what => $for) {
$content = str_replace($what, $for, $content);
}
return $content;
}
/**
* Load command arguments
* @return string
*/
private function loadArguments()
{
$parent = $this->argument('parentModule');
$this->moduleName = $moduleName = $this->argument('name');
$this->moduleNamespace = trim($parent . '/' . $moduleName, '/');
$entity = $this->option('entity');
$defaultEntityNamespace = '\\Modules\\' . str_replace('/', '\\', $this->moduleNamespace) . '\Entities\\';
if (!empty($entity)) {
$parts = explode('\\', $entity);
$this->entity = $parts[count($parts) - 1];
unset($parts[count($parts) - 1]);
$this->entityNamespace = implode('\\', $parts);
} else {
$this->entityNamespace = $defaultEntityNamespace;
$this->entity = $this->moduleName;
}
return $defaultEntityNamespace;
}
}