領収証発行サービス
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.

106 line
2.7KB

  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("例外発生:%s:%s:%d", $e->getMessage(), $e->getFile(), $e->getLine());
  36. $this->outputError($message, $e->getTrace());
  37. $ret = self::RESULTCODE_FAILED;
  38. }
  39. if ($ret === self::RESULTCODE_SUCCESS) {
  40. $this->outputInfoForBase("成功しました。");
  41. } else if ($ret === self::RESULTCODE_WARN) {
  42. $this->outputWarn("一部失敗があります。");
  43. } else if ($ret === self::RESULTCODE_FAILED) {
  44. $this->outputError("失敗しました");
  45. } else {
  46. $this->outputError(sprintf("未定義のエラーコード:%d", $ret));
  47. }
  48. return $ret;
  49. }
  50. private function boot()
  51. {
  52. Log::setDefaultDriver("batch");
  53. Log::withContext([
  54. '__scheduleId' => strval(Str::uuid()),
  55. ...$this->arguments(),
  56. ]);
  57. $this->outputInfoForBase(sprintf("バッチ起動 %s", $this->getCommandName()));
  58. }
  59. protected function outputInfo(string $message, array $context = [])
  60. {
  61. Log::info($message, $this->getContext($context));
  62. $this->info($message);
  63. }
  64. private function outputInfoForBase(string $message, array $context = [])
  65. {
  66. if ($this->outputInfoForBase) {
  67. Log::info($message, $this->getContext($context));
  68. }
  69. $this->info($message);
  70. }
  71. protected function outputWarn(string $message, array $context = [])
  72. {
  73. Log::warning($message, $this->getContext($context));
  74. $this->warn($message);
  75. }
  76. protected function outputError(string $message, array $context = [])
  77. {
  78. Log::error($message, $this->getContext($context));
  79. $this->error($message);
  80. }
  81. private function getContext(array $context = [])
  82. {
  83. return array_merge($context, ["context" => $this->arguments()]);
  84. }
  85. protected function getCommandName(): string
  86. {
  87. return "";
  88. }
  89. }