MakeServiceCommand.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. namespace App\Console\Commands;
  3. use Illuminate\Console\Command;
  4. class MakeServiceCommand extends Command
  5. {
  6. /**
  7. * The name and signature of the console command.
  8. *
  9. * @var string
  10. */
  11. protected $signature = 'make:service
  12. {--provider : Register in the provider}
  13. {name : fileName}';
  14. /**
  15. * The console command description.
  16. *
  17. * @var string
  18. */
  19. protected $description = 'Create Service file';
  20. /**
  21. * Create a new command instance.
  22. *
  23. * @return void
  24. */
  25. public function __construct()
  26. {
  27. parent::__construct();
  28. }
  29. /**
  30. * Execute the console command.
  31. *
  32. * @return void
  33. */
  34. public function handle()
  35. {
  36. if (!file_exists(base_path('app\\Services'))){
  37. mkdir('app\\Services',666,false);
  38. }
  39. $fileName=$this->argument('name');
  40. if (!file_exists(base_path('app\\Services\\'.$fileName.'.php'))){
  41. file_put_contents(base_path('app\\Services\\'.$fileName.'.php'),
  42. '<?php '.PHP_EOL.PHP_EOL.'namespace App\Services; '.PHP_EOL.PHP_EOL.'Class '.$fileName.PHP_EOL.'{ '.PHP_EOL.PHP_EOL.PHP_EOL.'}');
  43. }
  44. else $this->error("ERROR: file exists;");
  45. if ($this->option("provider")){
  46. $path = base_path("app\\Providers\\AppServiceProvider.php");
  47. $i = 0;
  48. $fop = fopen($path,"r+");
  49. $endLine = 0;
  50. $startLine = 0;
  51. while (!feof($fop)){
  52. $i += 1;
  53. $lineStr = fgets($fop);
  54. if (strpos($lineStr,"app()->singleton"))$endLine = $i;
  55. if (strpos($lineStr,"App\Services"))$startLine = $i;
  56. };
  57. fclose($fop);
  58. $fop = fopen($path,"r+");
  59. $i = 0;
  60. $arr = [];
  61. while (!feof($fop)){
  62. $i += 1;
  63. $lineStr = fgets($fop);
  64. if ($i == $endLine){
  65. $lineStr = $lineStr." app()->singleton('{$fileName}',{$fileName}::class);".PHP_EOL;
  66. }
  67. if ($i == $startLine){
  68. $lineStr = $lineStr."use App\Services\\$fileName;".PHP_EOL;
  69. }
  70. $arr[] = $lineStr;
  71. };
  72. fclose($fop);
  73. unlink($path);
  74. foreach ($arr as $value){
  75. file_put_contents($path,$value,FILE_APPEND);
  76. }
  77. }
  78. $this->info("File create success!");
  79. }
  80. }