MakeServiceCommand.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. $sign = 0;
  52. while (!feof($fop)){
  53. $i += 1;
  54. $lineStr = fgets($fop);
  55. if (strpos($lineStr,"loadingService(){"))$sign = $i;
  56. if (strpos($lineStr,"app()->singleton"))$endLine = $i;
  57. if (strpos($lineStr,"App\Services"))$startLine = $i;
  58. };
  59. fclose($fop);
  60. $fop = fopen($path,"r+");
  61. $i = 0;
  62. $header = [];
  63. $content = [];
  64. $footer = [];
  65. while (!feof($fop)){
  66. $i += 1;
  67. $lineStr = fgets($fop);
  68. if ($i == $startLine){
  69. $lineStr = $lineStr."use App\Services\\$fileName;".PHP_EOL;
  70. }
  71. if ($i<=$sign)$header[] = $lineStr;
  72. if ($i>$sign && $i<= $endLine){
  73. $content[] = $lineStr;
  74. }
  75. if ($i>$endLine)$footer[] = $lineStr;
  76. };
  77. $content[] = " app()->singleton('{$fileName}',{$fileName}::class);".PHP_EOL;
  78. array_multisort($content);
  79. fclose($fop);
  80. unlink($path);
  81. foreach (array_merge($header,$content,$footer) as $value){
  82. file_put_contents($path,$value,FILE_APPEND);
  83. }
  84. }
  85. $this->info("File create success!");
  86. }
  87. }