Completed
Push — develop ( 95bf16...af59cb )
by jake
02:39
created

ErrorlogHandler   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 158
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 9
c 2
b 0
f 0
lcom 1
cbo 2
dl 0
loc 158
ccs 39
cts 39
cp 1
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A setLogLevel() 0 5 1
A setRethrow() 0 5 1
A __invoke() 0 12 3
A log() 0 8 1
A formatException() 0 10 1
A formatResponse() 0 11 1
1
<?php
2
/**
3
 * Errorlog Handler
4
 *
5
 * PHP version 5
6
 *
7
 * Copyright (C) 2016 Jake Johns
8
 *
9
 * This software may be modified and distributed under the terms
10
 * of the MIT license.  See the LICENSE file for details.
11
 *
12
 * @category  Middleware
13
 * @package   Vperyod\ErrorlogHandler
14
 * @author    Jake Johns <[email protected]>
15
 * @copyright 2016 Jake Johns
16
 * @license   http://jnj.mit-license.org/2016 MIT License
17
 * @link      https://github.com/vperyod/vperyod.errorlog-handler
18
 */
19
20
namespace Vperyod\ErrorlogHandler;
21
22
use Psr\Http\Message\ResponseInterface as Response;
23
use Psr\Http\Message\ServerRequestInterface as Request;
24
25
use Psr\Log\LoggerInterface as Logger;
26
use Psr\Log\LogLevel as Level;
27
28
use Exception;
29
30
/**
31
 * ErrorlogHandler
32
 *
33
 * @category Middleware
34
 * @package  Vperyod\ErrorlogHandler
35
 * @author   Jake Johns <[email protected]>
36
 * @license  http://jnj.mit-license.org/2016 MIT License
37
 * @link     https://github.com/vperyod/vperyod.errorlog-handler
38
 */
39
class ErrorlogHandler
40
{
41
42
    /**
43
     * Log
44
     *
45
     * @var Logger
46
     *
47
     * @access protected
48
     */
49
    protected $log;
50
51
    /**
52
     * Rethrow exception?
53
     *
54
     * @var bool
55
     *
56
     * @access protected
57
     */
58
    protected $rethrow = true;
59
60
    /**
61
     * Level
62
     *
63
     * @var string
64
     *
65
     * @access protected
66
     */
67
    protected $level = Level::ALERT;
68
69
    /**
70
     * Create an ErrorlogHandler
71
     *
72
     * @param Logger $logger Psr\Log logger
73
     *
74
     * @access public
75
     */
76 4
    public function __construct(Logger $logger)
77
    {
78 4
        $this->logger = $logger;
0 ignored issues
show
Bug introduced by
The property logger does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
79 4
    }
80
81
    /**
82
     * Set log level to use
83
     *
84
     * @param mixed $level Level to log exceptions
85
     *
86
     * @return $this
87
     *
88
     * @access public
89
     */
90 1
    public function setLogLevel($level)
91
    {
92 1
        $this->level = $level;
93 1
        return $this;
94
    }
95
96
    /**
97
     * Set if handler should retrhow exception
98
     *
99
     * @param bool $bool exception is re thrown if true
100
     *
101
     * @return $this
102
     *
103
     * @access public
104
     */
105 1
    public function setRethrow($bool)
106
    {
107 1
        $this->rethrow = (bool) $bool;
108 1
        return $this;
109
    }
110
111
    /**
112
     * Log an exception if thrown
113
     *
114
     * @param Request  $request  PSR7 HTTP Request
115
     * @param Response $response PSR7 HTTP Response
116
     * @param callable $next     Next callable middleware
117
     *
118
     * @return Response
119
     *
120
     * @access public
121
     *
122
     * @throws Exception throws caught exception if rethrow is true
123
     */
124 4
    public function __invoke(Request $request, Response $response, callable $next)
125
    {
126
        try {
127 4
            return $next($request, $response);
128 3
        } catch (Exception $exception) {
129 3
            $this->log($exception);
130 3
            if ($this->rethrow) {
131 2
                throw $exception;
132
            }
133 1
            return $this->formatResponse($exception, $response);
134
        }
135
    }
136
137
    /**
138
     * Log
139
     *
140
     * @param Exception $exception Exception to log
141
     *
142
     * @return void
143
     *
144
     * @access protected
145
     */
146 3
    protected function log(Exception $exception)
147
    {
148 3
        $this->logger->log(
149 3
            $this->level,
150 3
            $this->formatException($exception),
151 3
            ['exception' => $exception]
152 3
        );
153 3
    }
154
155
    /**
156
     * Format Exception into log message
157
     *
158
     * @param Exception $exception Exception to log
159
     *
160
     * @return string
161
     *
162
     * @access protected
163
     */
164 3
    protected function formatException(Exception $exception)
165
    {
166 3
        return sprintf(
167 3
            'Uncaught Exception %s: "%s" at %s line %s',
168 3
            get_class($exception),
169 3
            $exception->getMessage(),
170 3
            $exception->getFile(),
171 3
            $exception->getLine()
172 3
        );
173
    }
174
175
    /**
176
     * Format response to return
177
     *
178
     * @param Exception $exception Caught exception
179
     * @param Response  $response  Response object
180
     *
181
     * @return Response
182
     *
183
     * @access protected
184
     */
185 1
    protected function formatResponse(Exception $exception, Response $response)
186
    {
187 1
        $response = $response->withStatus(500)
188 1
            ->withHeader('Content-Type', 'text/plain; charset=utf-8');
189 1
        $response->getBody()->write(
190 1
            get_class($exception)
191
            . ': '
192 1
            . $exception->getMessage()
193 1
        );
194 1
        return $response;
195
    }
196
}
197