LoggingMiddleware::process()   A
last analyzed

Complexity

Conditions 4
Paths 20

Size

Total Lines 38
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 20
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 21
c 1
b 0
f 0
dl 0
loc 38
ccs 20
cts 20
cp 1
rs 9.584
cc 4
nc 20
nop 3
crap 4
1
<?php
2
declare(strict_types=1);
3
4
namespace Shoot\Shoot\Middleware;
5
6
use Psr\Http\Message\ServerRequestInterface;
7
use Psr\Log\LoggerInterface;
8
use Shoot\Shoot\HasPresenterInterface;
9
use Shoot\Shoot\MiddlewareInterface;
10
use Shoot\Shoot\View;
11
use Throwable;
12
13
/**
14
 * Logs all views being processed by Shoot. It's recommended to add this before any other middleware.
15
 */
16
final class LoggingMiddleware implements MiddlewareInterface
17
{
18
    /** @var LoggerInterface */
19
    private $logger;
20
21
    /**
22
     * Constructs a new instance of LoggingMiddleware. Requires a PSR-3 compliant logger.
23
     *
24
     * @param LoggerInterface $logger
25
     */
26 3
    public function __construct(LoggerInterface $logger)
27
    {
28 3
        $this->logger = $logger;
29 3
    }
30
31
    /**
32
     * Process the view within the context of the current HTTP request, either before or after calling the next
33
     * middleware. Returns the processed view.
34
     *
35
     * @param View                   $view
36
     * @param ServerRequestInterface $request
37
     * @param callable               $next
38
     *
39
     * @return View
40
     *
41
     * @throws Throwable
42
     */
43 3
    public function process(View $view, ServerRequestInterface $request, callable $next): View
44
    {
45 3
        $context = [];
46 3
        $message = $view->getName();
47
48
        try {
49 3
            $startTime = microtime(true);
50
51
            /** @var View $view */
52 3
            $view = $next($view);
53
54 2
            $endTime = microtime(true);
55
56 2
            $presentationModel = $view->getPresentationModel();
57
58 2
            $context['presentation_model'] = $presentationModel->getName();
59
60 2
            if ($presentationModel instanceof HasPresenterInterface) {
61 2
                $context['presenter_name'] = $presentationModel->getPresenterName();
62
            }
63
64 2
            $context['time_taken'] = sprintf("%f seconds", $endTime - $startTime);
65
66 2
            if ($view->hasSuppressedException()) {
67 1
                $context['exception'] = $view->getSuppressedException();
68
69 1
                $this->logger->warning($message, $context);
70
            } else {
71 1
                $this->logger->debug($message, $context);
72
            }
73
74 2
            return $view;
75 1
        } catch (Throwable $exception) {
76 1
            $context['exception'] = $exception;
77
78 1
            $this->logger->error($message, $context);
79
80 1
            throw $exception;
81
        }
82
    }
83
}
84