MakeServiceCommand.php 3.1 KB

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