1: <?php
2:
3: namespace CHEZ14\ApiKit\Filters;
4:
5: use CHEZ14\ApiKit\Controllers\DumbController;
6: use CHEZ14\ApiKit\Exceptions\ApiException;
7: use CodeIgniter\Filters\FilterInterface;
8: use CodeIgniter\HTTP\RequestInterface;
9: use CodeIgniter\HTTP\ResponseInterface;
10: use Config\Services;
11: use Throwable;
12:
13: class ApiExceptionCatcher implements FilterInterface
14: {
15: /**
16: * Set the previous exception handler to forward this to.
17: *
18: * @var callable<Throwable>
19: */
20: protected $previousExceptionHandler;
21:
22: /**
23: * Help handle exception thrown by the controller. This will help handle the
24: * ApiException thrown by controller, but specificly just for that
25: * exception. Any other exception will be forwarded to next handler.
26: *
27: * @param Throwable $e The provided exception
28: * @return void
29: */
30: public function handleApiException(Throwable $e)
31: {
32: if (!$e || !($e instanceof ApiException)) {
33: return call_user_func($this->previousExceptionHandler, $e);
34: }
35:
36: // Change the Response Interface
37: $controller = new DumbController();
38: $controller->initController(Services::request(), Services::response(), Services::logger());
39: $controller->throwError($e);
40: }
41:
42: /**
43: * Do whatever processing this filter needs to do. By default it should not
44: * return anything during normal execution. However, when an abnormal state
45: * is found, it should return an instance of CodeIgniter\HTTP\Response. If
46: * it does, script execution will end and that Response will be sent back to
47: * the client, allowing for error pages, redirects, etc.
48: *
49: * @param RequestInterface $request Original Request
50: * @param array|null $arguments Arguments for this filter
51: * @return mixed
52: */
53: public function before(RequestInterface $request, $arguments = null)
54: {
55: // Register the API Handler thingy. This will help accept.
56: $this->previousExceptionHandler = set_exception_handler([$this, 'handleApiException']);
57: }
58:
59: /**
60: * Allows After filters to inspect and modify the response object as needed.
61: * This method does not allow any way to stop execution of other after
62: * filters, short of throwing an Exception or Error.
63: *
64: * @param RequestInterface $request Original Request
65: * @param ResponseInterface $response Original Response
66: * @param array|null $arguments Arguments for this filter
67: * @return mixed
68: */
69: public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
70: {
71: // Restore the Exception handler
72: restore_exception_handler();
73: }
74: }
75: