|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +/* |
| 6 | + * This file is part of the Micro framework package. |
| 7 | + * |
| 8 | + * (c) Stanislau Komar <kost@micro-php.net> |
| 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 Micro\Plugin\Http\Business\Executor; |
| 15 | + |
| 16 | +use Micro\Plugin\Http\Business\Formatter\LogFormatterInterface; |
| 17 | +use Micro\Plugin\Http\Exception\HttpException; |
| 18 | +use Psr\Log\LoggerInterface; |
| 19 | +use Symfony\Component\HttpFoundation\Request; |
| 20 | +use Symfony\Component\HttpFoundation\Response; |
| 21 | + |
| 22 | +/** |
| 23 | + * @author Stanislau Komar <kost@micro-php.net> |
| 24 | + */ |
| 25 | +readonly class HttpExecutorLoggerAwareDecorator implements RouteExecutorInterface |
| 26 | +{ |
| 27 | + public function __construct( |
| 28 | + private RouteExecutorInterface $decorated, |
| 29 | + private LoggerInterface $loggerAccess, |
| 30 | + private LoggerInterface $loggerError, |
| 31 | + private LogFormatterInterface $logAccessFormatter, |
| 32 | + private LogFormatterInterface $logErrorFormatter |
| 33 | + ) { |
| 34 | + } |
| 35 | + |
| 36 | + /** |
| 37 | + * {@inheritDoc} |
| 38 | + */ |
| 39 | + public function execute(Request $request, bool $flush = true): Response |
| 40 | + { |
| 41 | + $response = null; |
| 42 | + $exception = null; |
| 43 | + try { |
| 44 | + $response = $this->decorated->execute($request, $flush); |
| 45 | + } catch (HttpException $httpException) { |
| 46 | + $exception = $httpException; |
| 47 | + } catch (\Throwable $throwable) { |
| 48 | + $exception = $throwable; |
| 49 | + } finally { |
| 50 | + $this->loggerAccess->info( |
| 51 | + $this->logAccessFormatter->format($request, $response, $exception) |
| 52 | + ); |
| 53 | + |
| 54 | + if ($exception) { |
| 55 | + $this->loggerError->critical( |
| 56 | + $this->logErrorFormatter->format($request, $response, $exception) |
| 57 | + ); |
| 58 | + |
| 59 | + throw $exception; |
| 60 | + } |
| 61 | + |
| 62 | + return $response; |
| 63 | + } |
| 64 | + } |
| 65 | +} |
0 commit comments