You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

112 lines
2.8KB

  1. <?php
  2. namespace App\Console\Commands;
  3. use Exception;
  4. use Illuminate\Console\Command;
  5. use Illuminate\Support\Facades\Log;
  6. use Illuminate\Support\Str;
  7. abstract class BaseCommand extends Command
  8. {
  9. const RESULTCODE_SUCCESS = 0;
  10. const RESULTCODE_WARN = 1;
  11. const RESULTCODE_FAILED = 2;
  12. /**
  13. * Create a new command instance.
  14. *
  15. * @return void
  16. */
  17. public function __construct()
  18. {
  19. parent::__construct();
  20. }
  21. abstract protected function service(): int;
  22. protected bool $outputInfoForBase = true;
  23. /**
  24. * Execute the console command.
  25. *
  26. * @return int
  27. */
  28. public function handle()
  29. {
  30. $ret = 0;
  31. $this->boot();
  32. try {
  33. $ret = $this->service();
  34. } catch (Exception $e) {
  35. $message = sprintf(
  36. "例外発生:%s:%s:%s:%d",
  37. get_class($e),
  38. $e->getMessage(),
  39. $e->getFile(),
  40. $e->getLine()
  41. );
  42. $this->outputError($message, $e->getTrace());
  43. $ret = self::RESULTCODE_FAILED;
  44. }
  45. if ($ret === self::RESULTCODE_SUCCESS) {
  46. $this->outputInfoForBase("成功しました。");
  47. } else if ($ret === self::RESULTCODE_WARN) {
  48. $this->outputWarn("一部失敗があります。");
  49. } else if ($ret === self::RESULTCODE_FAILED) {
  50. $this->outputError("失敗しました");
  51. } else {
  52. $this->outputError(sprintf("未定義のエラーコード:%d", $ret));
  53. }
  54. return $ret;
  55. }
  56. private function boot()
  57. {
  58. Log::setDefaultDriver("batch");
  59. Log::withContext([
  60. '__scheduleId' => strval(Str::uuid()),
  61. ...$this->arguments(),
  62. ]);
  63. $this->outputInfoForBase(sprintf("バッチ起動 %s", $this->getCommandName()));
  64. }
  65. protected function outputInfo(string $message, array $context = [])
  66. {
  67. Log::info($message, $this->getContext($context));
  68. $this->info($message);
  69. }
  70. private function outputInfoForBase(string $message, array $context = [])
  71. {
  72. if ($this->outputInfoForBase) {
  73. Log::info($message, $this->getContext($context));
  74. }
  75. $this->info($message);
  76. }
  77. protected function outputWarn(string $message, array $context = [])
  78. {
  79. Log::warning($message, $this->getContext($context));
  80. $this->warn($message);
  81. }
  82. protected function outputError(string $message, array $context = [])
  83. {
  84. Log::error($message, $this->getContext($context));
  85. $this->error($message);
  86. }
  87. private function getContext(array $context = [])
  88. {
  89. return array_merge($context, ["context" => $this->arguments()]);
  90. }
  91. protected function getCommandName(): string
  92. {
  93. return "";
  94. }
  95. }