Completed
Push — master ( 69b853...704888 )
by Denis
10s
created

PlainTextHandler::setDumper()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
ccs 0
cts 3
cp 0
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 2
1
<?php
2
/**
3
* Whoops - php errors for cool kids
4
* @author Filipe Dobreira <http://github.com/filp>
5
* Plaintext handler for command line and logs.
6
* @author Pierre-Yves Landuré <https://howto.biapy.com/>
7
*/
8
9
namespace Whoops\Handler;
10
11
use InvalidArgumentException;
12
use Psr\Log\LoggerInterface;
13
use Whoops\Exception\Frame;
14
15
/**
16
* Handler outputing plaintext error messages. Can be used
17
* directly, or will be instantiated automagically by Whoops\Run
18
* if passed to Run::pushHandler
19
*/
20
class PlainTextHandler extends Handler
21
{
22
    const VAR_DUMP_PREFIX = '   | ';
23
24
    /**
25
     * @var \Psr\Log\LoggerInterface
26
     */
27
    protected $logger;
28
29
    /**
30
     * @var callable
31
     */
32
    protected $dumper;
33
34
    /**
35
     * @var bool
36
     */
37
    private $addTraceToOutput = true;
38
39
    /**
40
     * @var bool|integer
41
     */
42
    private $addTraceFunctionArgsToOutput = false;
43
44
    /**
45
     * @var integer
46
     */
47
    private $traceFunctionArgsOutputLimit = 1024;
48
49
    /**
50
     * @var bool
51
     */
52
    private $loggerOnly = false;
53
54
    /**
55
     * Constructor.
56
     * @throws InvalidArgumentException     If argument is not null or a LoggerInterface
57
     * @param  \Psr\Log\LoggerInterface|null $logger
58
     */
59 1
    public function __construct($logger = null)
60
    {
61 1
        $this->setLogger($logger);
62
    }
63
64
    /**
65
     * Set the output logger interface.
66
     * @throws InvalidArgumentException     If argument is not null or a LoggerInterface
67
     * @param  \Psr\Log\LoggerInterface|null $logger
68
     */
69 2
    public function setLogger($logger = null)
70
    {
71 2
        if (! (is_null($logger)
72 2
            || $logger instanceof LoggerInterface)) {
73 2
            throw new InvalidArgumentException(
74 2
                'Argument to ' . __METHOD__ .
75 2
                " must be a valid Logger Interface (aka. Monolog), " .
76 2
                get_class($logger) . ' given.'
77 2
            );
78
        }
79
80 1
        $this->logger = $logger;
81 1
    }
82
83
    /**
84
     * @return \Psr\Log\LoggerInterface|null
85
     */
86
    public function getLogger()
87
    {
88
        return $this->logger;
89
    }
90
91
    /**
92
     * Set var dumper callback function.
93
     *
94
     * @param  callable $dumper
95
     * @return void
96
     */
97
    public function setDumper(callable $dumper)
98
    {
99
        $this->dumper = $dumper;
100
    }
101
102
    /**
103
     * Add error trace to output.
104
     * @param  bool|null  $addTraceToOutput
105
     * @return bool|$this
106
     */
107 4
    public function addTraceToOutput($addTraceToOutput = null)
108
    {
109 4
        if (func_num_args() == 0) {
110 4
            return $this->addTraceToOutput;
111
        }
112
113 4
        $this->addTraceToOutput = (bool) $addTraceToOutput;
114 4
        return $this;
115
    }
116
117
    /**
118
     * Add error trace function arguments to output.
119
     * Set to True for all frame args, or integer for the n first frame args.
120
     * @param  bool|integer|null $addTraceFunctionArgsToOutput
121
     * @return null|bool|integer
122
     */
123 2
    public function addTraceFunctionArgsToOutput($addTraceFunctionArgsToOutput = null)
124
    {
125 2
        if (func_num_args() == 0) {
126 2
            return $this->addTraceFunctionArgsToOutput;
127
        }
128
129 2
        if (! is_integer($addTraceFunctionArgsToOutput)) {
130 1
            $this->addTraceFunctionArgsToOutput = (bool) $addTraceFunctionArgsToOutput;
131 1
        } else {
132 2
            $this->addTraceFunctionArgsToOutput = $addTraceFunctionArgsToOutput;
133
        }
134 2
    }
135
136
    /**
137
     * Set the size limit in bytes of frame arguments var_dump output.
138
     * If the limit is reached, the var_dump output is discarded.
139
     * Prevent memory limit errors.
140
     * @var integer
141
     */
142 1
    public function setTraceFunctionArgsOutputLimit($traceFunctionArgsOutputLimit)
143
    {
144 1
        $this->traceFunctionArgsOutputLimit = (integer) $traceFunctionArgsOutputLimit;
145 1
    }
146
147
    /**
148
     * Create plain text response and return it as a string
149
     * @return string
150
     */
151
    public function generateResponse()
152
    {
153
        $exception = $this->getException();
154
        return sprintf("%s: %s in file %s on line %d%s\n",
155
            get_class($exception),
156
            $exception->getMessage(),
157
            $exception->getFile(),
158
            $exception->getLine(),
159
            $this->getTraceOutput()
160
        );
161
    }
162
163
    /**
164
     * Get the size limit in bytes of frame arguments var_dump output.
165
     * If the limit is reached, the var_dump output is discarded.
166
     * Prevent memory limit errors.
167
     * @return integer
168
     */
169 1
    public function getTraceFunctionArgsOutputLimit()
170
    {
171 1
        return $this->traceFunctionArgsOutputLimit;
172
    }
173
174
    /**
175
     * Only output to logger.
176
     * @param  bool|null $loggerOnly
177
     * @return null|bool
178
     */
179 1
    public function loggerOnly($loggerOnly = null)
180
    {
181 1
        if (func_num_args() == 0) {
182 1
            return $this->loggerOnly;
183
        }
184
185 1
        $this->loggerOnly = (bool) $loggerOnly;
186 1
    }
187
188
    /**
189
     * Test if handler can output to stdout.
190
     * @return bool
191
     */
192 2
    private function canOutput()
193
    {
194 2
        return !$this->loggerOnly();
195
    }
196
197
    /**
198
     * Get the frame args var_dump.
199
     * @param  \Whoops\Exception\Frame $frame [description]
200
     * @param  integer                 $line  [description]
201
     * @return string
202
     */
203 1
    private function getFrameArgsOutput(Frame $frame, $line)
204
    {
205 1
        if ($this->addTraceFunctionArgsToOutput() === false
206 1
            || $this->addTraceFunctionArgsToOutput() < $line) {
207 1
            return '';
208
        }
209
210
        // Dump the arguments:
211 1
        ob_start();
212 1
        $this->dump($frame->getArgs());
213 1
        if (ob_get_length() > $this->getTraceFunctionArgsOutputLimit()) {
214
            // The argument var_dump is to big.
215
            // Discarded to limit memory usage.
216
            ob_clean();
217
            return sprintf(
218
                "\n%sArguments dump length greater than %d Bytes. Discarded.",
219
                self::VAR_DUMP_PREFIX,
220
                $this->getTraceFunctionArgsOutputLimit()
221
            );
222
        }
223
224 1
        return sprintf("\n%s",
225 1
            preg_replace('/^/m', self::VAR_DUMP_PREFIX, ob_get_clean())
226 1
        );
227
    }
228
229
    /**
230
     * Dump variable.
231
     *
232
     * @param mixed $var
233
     * @return void
234
     */
235
    protected function dump($var)
236
    {
237
        if ($this->dumper) {
238
            call_user_func($this->dumper, $var);
239
        } else {
240
            var_dump($var);
0 ignored issues
show
Security Debugging Code introduced by
var_dump($var); looks like debug code. Are you sure you do not want to remove it? This might expose sensitive data.
Loading history...
241
        }
242
    }
243
244
    /**
245
     * Get the exception trace as plain text.
246
     * @return string
247
     */
248 2
    private function getTraceOutput()
249
    {
250 2
        if (! $this->addTraceToOutput()) {
251
            return '';
252
        }
253 2
        $inspector = $this->getInspector();
254 2
        $frames = $inspector->getFrames();
255
256 2
        $response = "\nStack trace:";
257
258 2
        $line = 1;
259 2
        foreach ($frames as $frame) {
260
            /** @var Frame $frame */
261 2
            $class = $frame->getClass();
262
263 2
            $template = "\n%3d. %s->%s() %s:%d%s";
264 2
            if (! $class) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $class of type string|null is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
265
                // Remove method arrow (->) from output.
266
                $template = "\n%3d. %s%s() %s:%d%s";
267
            }
268
269 2
            $response .= sprintf(
270 2
                $template,
271 2
                $line,
272 2
                $class,
273 2
                $frame->getFunction(),
274 2
                $frame->getFile(),
275 2
                $frame->getLine(),
276 2
                $this->getFrameArgsOutput($frame, $line)
277 2
            );
278
279 2
            $line++;
280 2
        }
281
282 2
        return $response;
283
    }
284
285
    /**
286
     * @return int
287
     */
288 3
    public function handle()
289
    {
290 3
        $response = $this->generateResponse();
291
292 3
        if ($this->getLogger()) {
293
            $this->getLogger()->error($response);
294
        }
295
296 3
        if (! $this->canOutput()) {
297
            return Handler::DONE;
298
        }
299
300 3
        echo $response;
301
302 3
        return Handler::QUIT;
303
    }
304
305
    /**
306
     * @return string
307
     */
308
    public function contentType()
309
    {
310
        return 'text/plain';
311
    }
312
}
313