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

364 lines
10KB

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