|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +/* |
| 6 | +* This file is part of https://github.com/josantonius/php-exception-handler repository. |
| 7 | +* |
| 8 | +* (c) Josantonius <hello@josantonius.dev> |
| 9 | +* |
| 10 | +* For the full copyright and license information, please view the LICENSE |
| 11 | +* file that was distributed with this source code. |
| 12 | +*/ |
| 13 | + |
| 14 | +namespace Josantonius\ExceptionHandler; |
| 15 | + |
| 16 | +use Throwable; |
| 17 | +use Josantonius\ExceptionHandler\Exceptions\NotCallableException; |
| 18 | +use Josantonius\ExceptionHandler\Exceptions\WrongMethodNameException; |
| 19 | + |
| 20 | +/** |
| 21 | + * Handling exceptions. |
| 22 | + */ |
| 23 | +class ExceptionHandler |
| 24 | +{ |
| 25 | + /** |
| 26 | + * Sets a exception handler. |
| 27 | + * |
| 28 | + * @param callable $callback Exception handler function. |
| 29 | + * @param string[] $runBeforeCallback Method names to call in the exception before run callback. |
| 30 | + * @param string[] $runAfterCallback Method names to call in the exception after run callback. |
| 31 | + * |
| 32 | + * @throws NotCallableException if the callback is not callable. |
| 33 | + * @throws WrongMethodNameException if the method names are not strings. |
| 34 | + */ |
| 35 | + public function __construct( |
| 36 | + private $callback, |
| 37 | + private array $runBeforeCallback = [], |
| 38 | + private array $runAfterCallback = [] |
| 39 | + ) { |
| 40 | + if ($callback && !is_callable($callback)) { |
| 41 | + throw new NotCallableException(); |
| 42 | + } |
| 43 | + |
| 44 | + $methodNames = array_merge($runBeforeCallback, $runAfterCallback); |
| 45 | + |
| 46 | + if (array_filter($methodNames, fn ($method) => !is_string($method))) { |
| 47 | + throw new WrongMethodNameException(); |
| 48 | + } |
| 49 | + |
| 50 | + set_exception_handler(fn (Throwable $exception) => $this->handler($exception)); |
| 51 | + } |
| 52 | + |
| 53 | + /** |
| 54 | + * Handle exception. |
| 55 | + */ |
| 56 | + private function handler(Throwable $exception): void |
| 57 | + { |
| 58 | + foreach ($this->runBeforeCallback as $method) { |
| 59 | + if (method_exists($exception, $method)) { |
| 60 | + $exception->$method(); |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + ($this->callback)($exception); |
| 65 | + |
| 66 | + foreach ($this->runAfterCallback as $method) { |
| 67 | + if (method_exists($exception, $method)) { |
| 68 | + $exception->$method(); |
| 69 | + } |
| 70 | + } |
| 71 | + } |
| 72 | +} |
0 commit comments