Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

379 lines
11KB

  1. <?php
  2. namespace App\Http\Controllers\Web;
  3. use App\Codes\EnvironmentName;
  4. use App\Codes\HTTPResultCode as ResultCode;
  5. use App\Codes\UserRole;
  6. use App\Exceptions\AppCommonException;
  7. use App\Exceptions\ExclusiveException;
  8. use App\Exceptions\GeneralErrorMessageException;
  9. use App\Exceptions\ParamException;
  10. use App\Sessions\SessionUser;
  11. use App\Util\DBUtil;
  12. use Exception;
  13. use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
  14. use Illuminate\Foundation\Bus\DispatchesJobs;
  15. use Illuminate\Foundation\Validation\ValidatesRequests;
  16. use Illuminate\Http\Client\Response as ClientResponse;
  17. use Illuminate\Http\JsonResponse;
  18. use Illuminate\Http\Request;
  19. use Illuminate\Http\Response;
  20. use Illuminate\Routing\Controller as BaseController;
  21. use Illuminate\Support\Arr;
  22. use Illuminate\Support\Facades\Auth;
  23. use Illuminate\Support\Facades\Log;
  24. use Illuminate\Support\Facades\Validator;
  25. use Illuminate\Support\Str;
  26. use Illuminate\Validation\ValidationException;
  27. use LogicException;
  28. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  29. use Symfony\Component\HttpKernel\Exception\HttpException;
  30. abstract class WebController extends BaseController
  31. {
  32. use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
  33. const COL_NAME_CREATED_AT = 'created_at';
  34. const COL_NAME_UPDATED_AT = 'updated_at';
  35. const COL_NAME_RESULT_CODE = 'result';
  36. const COL_NAME_DATA = 'data';
  37. const COL_NAME_MESSAGES = 'messages';
  38. const COL_NAME_GENERAL_MESSAGE = 'general';
  39. const COL_NAME_EMAIL_ID = 'email_id';
  40. const COL_NAME_ERRORS = 'errors';
  41. /**
  42. * バリデートした結果を格納
  43. *
  44. * @var array
  45. */
  46. protected $validated = [];
  47. /**
  48. * 画面へ返却するメールID
  49. *
  50. * @var integer|null
  51. */
  52. private int|null $emailId = null;
  53. /**
  54. * 返却するメッセージ
  55. *
  56. * @var array|null
  57. */
  58. private array|null $messages = null;
  59. /**
  60. * 返却するメッセージ
  61. *
  62. * @var string|null
  63. */
  64. private string|null $generalMessage = null;
  65. /**
  66. * 返却するデータ
  67. *
  68. * @var mixed|null
  69. */
  70. private $data = null;
  71. protected DBUtil $transaction;
  72. protected SessionUser $sessionUser;
  73. /**
  74. * 返却する結果コード
  75. *
  76. * @var ResultCode|null
  77. */
  78. protected ResultCode|null $resultCode = ResultCode::SECCESS;
  79. public function __construct()
  80. {
  81. $this->transaction = DBUtil::instance();
  82. $this->sessionUser = SessionUser::instance();
  83. }
  84. /**
  85. * パラメータオブジェクト
  86. */
  87. protected function getParam(): IParam
  88. {
  89. if (!property_exists(static::class, 'param')) {
  90. throw new LogicException("param未定義");
  91. }
  92. $param = $this->param;
  93. if (!is_subclass_of($param, IParam::class)) {
  94. throw new LogicException("param型不正");
  95. }
  96. return $this->param;
  97. }
  98. /**
  99. * コントローラーの名前
  100. * オーバーライドされることを想定
  101. * 主に、Routeのドキュメント作成用
  102. *
  103. * @return string
  104. */
  105. public function name(): string
  106. {
  107. return "---未設定---";
  108. }
  109. /**
  110. * コントローラーの説明
  111. * オーバーライドされることを想定
  112. * 主に、Routeのドキュメント作成用
  113. *
  114. * @return string
  115. */
  116. public function description(): string
  117. {
  118. return "---未設定---";
  119. }
  120. /**
  121. * オーバーライド必要
  122. * メインロジック
  123. *
  124. * @param Request $request
  125. * @return Response|JsonResponse|string
  126. */
  127. protected function run(Request $request): Response|JsonResponse|BinaryFileResponse|ClientResponse |string
  128. {
  129. return $this->successResponse();
  130. }
  131. private function getRules()
  132. {
  133. return $this->getParam()->rules();
  134. }
  135. public function entry(Request $request)
  136. {
  137. $this->setLogContext($request);
  138. try {
  139. $validator = Validator::make($request->all(), $this->getRules());
  140. $validator->validate();
  141. } catch (ValidationException $e) {
  142. logger("validate error", ['errors' => $e->errors(), 'request' => $request->all(), 'path' => $request->path()]);
  143. logger($request->toArray());
  144. return $this->validateErrorResponse($e);
  145. }
  146. try {
  147. $this->validated = $validator->validated();
  148. $this->getParam()->setData($this->validated);
  149. $this->transaction->beginTransaction();
  150. $ret = $this->run($request);
  151. $this->transaction->commit();
  152. return $ret;
  153. } catch (GeneralErrorMessageException $e) {
  154. $this->transaction->rollBack();
  155. return $this->failedResponse([], $e->getMessage());
  156. } catch (AppCommonException $e) {
  157. $this->transaction->rollBack();
  158. logs()->error(sprintf("Appエラー:%s File:%s Line:%d", $e->getMessage(), $e->getFile(), $e->getLine()));
  159. return $this->failedResponse();
  160. } catch (ExclusiveException $e) {
  161. $this->transaction->rollBack();
  162. logs()->error(sprintf("排他エラー:%s", $e->getMessage()));
  163. return $this->exclusiveErrorResponse();
  164. } catch (LogicException $e) {
  165. $this->transaction->rollBack();
  166. logs()->error([
  167. sprintf("実装エラー:%s", $e->getMessage()),
  168. get_class($e),
  169. $e->getFile(),
  170. $e->getLine(),
  171. $request->all(),
  172. ]);
  173. logger(array_filter($e->getTrace(), function ($val, $key) {
  174. return $key <= 5;
  175. }, ARRAY_FILTER_USE_BOTH));
  176. return $this->failedResponse();
  177. } catch (ValidationException $e) {
  178. $this->transaction->rollBack();
  179. return $this->validateErrorResponse($e);
  180. } catch (HttpException $e) {
  181. $this->transaction->rollBack();
  182. if ($e->getStatusCode() === 401) {
  183. return $this->unAuthorizedResponse();
  184. }
  185. throw $e;
  186. } catch (ParamException $e) {
  187. $this->transaction->rollBack();
  188. throw $this->validateErrorResponse([$e->target => $e->getMessage()]);
  189. } catch (Exception $e) {
  190. $this->transaction->rollBack();
  191. logs()->error([
  192. sprintf("例外エラー:%s", $e->getMessage()),
  193. get_class($e),
  194. $e->getFile(),
  195. $e->getLine(),
  196. $request->all(),
  197. ]);
  198. logger(array_filter($e->getTrace(), function ($val, $key) {
  199. return $key <= 5;
  200. }, ARRAY_FILTER_USE_BOTH));
  201. return $this->failedResponse();
  202. }
  203. }
  204. protected function successResponse(array|object $data = [], array|string $messages = [])
  205. {
  206. return $this->setData($data)
  207. ->setMessages($messages)
  208. ->setResultCode(ResultCode::SECCESS)
  209. ->makeResponse();
  210. }
  211. protected function failedResponse(array|object $data = [], array|string $messages = [])
  212. {
  213. return $this->setData($data)
  214. ->setMessages($messages)
  215. ->setResultCode(ResultCode::FAILED)
  216. ->makeResponse();
  217. }
  218. protected function unAuthorizedResponse(array|object $data = [], array|string $messages = [])
  219. {
  220. return $this->setData($data)
  221. ->setMessages($messages)
  222. ->setResultCode(ResultCode::UNAUTHORIZED)
  223. ->makeResponse();
  224. }
  225. protected function exclusiveErrorResponse(array|object $data = [], array|string $messages = [])
  226. {
  227. return $this->setData($data)
  228. ->setMessages($messages)
  229. ->setResultCode(ResultCode::EXCLUSIVE_ERROR)
  230. ->makeResponse();
  231. }
  232. protected function validateErrorResponse(ValidationException|array $exception, string|null $generalMessage = null)
  233. {
  234. $errorMessages = [];
  235. $general = null;
  236. if ($exception instanceof ValidationException) {
  237. foreach ($exception->errors() as $key => $m) {
  238. $errorMessages[$key] = $m[0];
  239. }
  240. }
  241. if (is_array($exception)) {
  242. $errorMessages = $exception;
  243. }
  244. $general = $generalMessage ?? data_get($errorMessages, self::COL_NAME_GENERAL_MESSAGE);
  245. return $this->setData([])
  246. ->setMessages($errorMessages)
  247. ->setGeneralMessage($general)
  248. ->setResultCode(ResultCode::FAILED)
  249. ->makeResponse();
  250. }
  251. protected function makeResponse()
  252. {
  253. if ($this->resultCode === null) {
  254. abort(403);
  255. }
  256. $ret = [];
  257. Arr::set($ret, self::COL_NAME_RESULT_CODE, $this->resultCode->value);
  258. if ($this->data !== null) {
  259. Arr::set($ret, self::COL_NAME_DATA, $this->data);
  260. }
  261. if ($this->messages !== null) {
  262. Arr::set($ret, self::COL_NAME_MESSAGES . "." . self::COL_NAME_ERRORS, $this->messages);
  263. }
  264. if ($this->generalMessage !== null) {
  265. Arr::set($ret, self::COL_NAME_MESSAGES . "." . self::COL_NAME_GENERAL_MESSAGE, $this->generalMessage);
  266. }
  267. if ($this->emailId !== null) {
  268. Arr::set($ret, self::COL_NAME_MESSAGES . "." . self::COL_NAME_EMAIL_ID, $this->emailId);
  269. }
  270. if (request()->wantsJson()) {
  271. return response()
  272. ->json($ret)
  273. ->withHeaders($this->makeHeader());
  274. } else {
  275. if (app()->environment([EnvironmentName::PRODUCTOIN->value])) {
  276. abort(500);
  277. }
  278. return response()
  279. ->json($ret)
  280. ->withHeaders($this->makeHeader());
  281. }
  282. }
  283. private function makeHeader(): array
  284. {
  285. $header = [];
  286. $user = Auth::user();
  287. if ($user) {
  288. $header["App-User-Auth"] = sprintf("%s", $user->id);
  289. } else {
  290. $header["App-User-Auth"] = 'none';
  291. }
  292. return $header;
  293. }
  294. // 返却用データの登録
  295. protected function setEmailId(int $emailId)
  296. {
  297. $this->emailId = $emailId;
  298. return $this;
  299. }
  300. protected function setMessages(array|string $messages)
  301. {
  302. if (is_array($messages)) {
  303. $this->messages = $messages;
  304. } else {
  305. $this->setGeneralMessage($messages);
  306. }
  307. return $this;
  308. }
  309. protected function setGeneralMessage(string|null $generalMessage)
  310. {
  311. $this->generalMessage = $generalMessage;
  312. return $this;
  313. }
  314. protected function setData($data)
  315. {
  316. $this->data = $data;
  317. return $this;
  318. }
  319. protected function setResultCode(ResultCode $resultCode)
  320. {
  321. $this->resultCode = $resultCode;
  322. return $this;
  323. }
  324. protected function setLogContext(Request $request)
  325. {
  326. Log::withContext([
  327. '__requestUuid__' => strval(Str::uuid()),
  328. '__userId__' => Auth::id(),
  329. '__path__' => $request->path(),
  330. ]);
  331. }
  332. }