|
<?php |
|
|
|
namespace App\Console\Commands; |
|
|
|
use Illuminate\Console\Command; |
|
use Illuminate\Filesystem\Filesystem; |
|
|
|
class MakeService extends Command |
|
{ |
|
/** |
|
* The filesystem instance |
|
* |
|
* @var Filesystem |
|
*/ |
|
protected Filesystem $files; |
|
|
|
/** |
|
* The name and signature of the console command. |
|
* |
|
* @var string |
|
*/ |
|
protected $signature = 'make:service {name : The name of the service}'; |
|
|
|
/** |
|
* The console command description. |
|
* |
|
* @var string |
|
*/ |
|
protected $description = 'Create a new service class'; |
|
|
|
/** |
|
* Create a new command instance. |
|
* |
|
* @return void |
|
*/ |
|
public function __construct(FileSystem $files) |
|
{ |
|
parent::__construct(); |
|
$this->files = $files; |
|
} |
|
|
|
/** |
|
* Execute the console command. |
|
* |
|
* @return int |
|
*/ |
|
public function handle(): int |
|
{ |
|
$name = $this->argument('name'); |
|
|
|
// Define base directory for services |
|
$baseDir = app_path('Services'); |
|
|
|
// Replace backslashes or forward slashes with DIRECTORY_SEPARATOR |
|
$path = str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $name); |
|
|
|
// Determine the final directory and file name |
|
$filePath = $baseDir . DIRECTORY_SEPARATOR . $path . '.php'; |
|
|
|
// Extract the directory from the path |
|
$dir = dirname($filePath); |
|
|
|
// check if already exists, if not create it |
|
if (!is_dir($dir)) { |
|
$this->files->makeDirectory($dir, 0755, true); |
|
} |
|
|
|
// check if the file is already exists |
|
if ($this->files->exists($filePath)) { |
|
$this->warn('Service already exists!'); |
|
return 1; |
|
} |
|
|
|
// Generate the class stub |
|
$namespace = $this->generateNamespace($name); |
|
$stub = $this->getStub($namespace, class_basename($name)); |
|
|
|
// Write the file |
|
$this->files->put($filePath, $stub); |
|
|
|
$this->info("Service created successfully"); |
|
|
|
return 0; |
|
} |
|
|
|
/** |
|
* Generate the namespace for the service. |
|
* |
|
* @param string $name |
|
* @return string |
|
*/ |
|
private function generateNameSpace(string $name): string |
|
{ |
|
// clean up the name and clean slashes |
|
$newName = trim(str_replace('/', '\\', $name), '\\'); |
|
$namespace = 'App\\Services'; |
|
|
|
// if there are directories specified in the name, add them to the namespace |
|
if (strpos($newName, "\\") !== false) { |
|
$namespace .= '\\' . dirname($name); |
|
} |
|
|
|
return $namespace; |
|
} |
|
|
|
/** |
|
* Get the service stub to generate the class file. |
|
* |
|
* @param string $namespace |
|
* @param string $className |
|
* @return string |
|
*/ |
|
protected function getStub(string $namespace, string $className): string |
|
{ |
|
return <<<HEREDOC |
|
<?php |
|
|
|
namespace $namespace; |
|
|
|
/** |
|
* $className |
|
* |
|
* Descriptio of the service |
|
*/ |
|
class $className { |
|
|
|
} |
|
HEREDOC; |
|
} |
|
} |