Completed
Push — master ( afab26...d13505 )
by Denis
8s
created

PrettyPageHandler::handle()   D

Complexity

Conditions 13
Paths 130

Size

Total Lines 118
Code Lines 69

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 149.9914

Importance

Changes 4
Bugs 1 Features 0
Metric Value
c 4
b 1
f 0
dl 0
loc 118
ccs 5
cts 74
cp 0.0675
rs 4.6605
cc 13
eloc 69
nc 130
nop 0
crap 149.9914

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Whoops - php errors for cool kids
4
 * @author Filipe Dobreira <http://github.com/filp>
5
 */
6
7
namespace Whoops\Handler;
8
9
use InvalidArgumentException;
10
use RuntimeException;
11
use Symfony\Component\VarDumper\Cloner\AbstractCloner;
12
use Symfony\Component\VarDumper\Cloner\VarCloner;
13
use UnexpectedValueException;
14
use Whoops\Exception\Formatter;
15
use Whoops\Util\Misc;
16
use Whoops\Util\TemplateHelper;
17
18
class PrettyPageHandler extends Handler
19
{
20
    /**
21
     * Search paths to be scanned for resources, in the reverse
22
     * order they're declared.
23
     *
24
     * @var array
25
     */
26
    private $searchPaths = array();
27
28
    /**
29
     * Fast lookup cache for known resource locations.
30
     *
31
     * @var array
32
     */
33
    private $resourceCache = array();
34
35
    /**
36
     * The name of the custom css file.
37
     *
38
     * @var string
39
     */
40
    private $customCss = null;
41
42
    /**
43
     * @var array[]
44
     */
45
    private $extraTables = array();
46
47
    /**
48
     * @var bool
49
     */
50
    private $handleUnconditionally = false;
51
52
    /**
53
     * @var string
54
     */
55
    private $pageTitle = "Whoops! There was an error.";
56
57
    /**
58
     * A string identifier for a known IDE/text editor, or a closure
59
     * that resolves a string that can be used to open a given file
60
     * in an editor. If the string contains the special substrings
61
     * %file or %line, they will be replaced with the correct data.
62
     *
63
     * @example
64
     *  "txmt://open?url=%file&line=%line"
65
     * @var mixed $editor
66
     */
67
    protected $editor;
68
69
    /**
70
     * A list of known editor strings
71
     * @var array
72
     */
73
    protected $editors = array(
74
        "sublime"  => "subl://open?url=file://%file&line=%line",
75
        "textmate" => "txmt://open?url=file://%file&line=%line",
76
        "emacs"    => "emacs://open?url=file://%file&line=%line",
77
        "macvim"   => "mvim://open/?url=file://%file&line=%line",
78
        "phpstorm" => "phpstorm://open?file=%file&line=%line",
79
    );
80
81
    /**
82
     * Constructor.
83
     */
84 1
    public function __construct()
85
    {
86 1
        if (ini_get('xdebug.file_link_format') || extension_loaded('xdebug')) {
87
            // Register editor using xdebug's file_link_format option.
88
            $this->editors['xdebug'] = function ($file, $line) {
89 1
                return str_replace(array('%f', '%l'), array($file, $line), ini_get('xdebug.file_link_format'));
90
            };
91 1
        }
92
93
        // Add the default, local resource search path:
94 1
        $this->searchPaths[] = __DIR__ . "/../Resources";
95 1
    }
96
97
    /**
98
     * @return int|null
99
     */
100 1
    public function handle()
101
    {
102 1
        if (!$this->handleUnconditionally()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->handleUnconditionally() of type boolean|null is loosely compared to false; this is ambiguous if the boolean can be false. You might want to explicitly use !== null instead.

If an expression can have both false, and null as possible values. It is generally a good practice to always use strict comparison to clearly distinguish between those two values.

$a = canBeFalseAndNull();

// Instead of
if ( ! $a) { }

// Better use one of the explicit versions:
if ($a !== null) { }
if ($a !== false) { }
if ($a !== null && $a !== false) { }
Loading history...
103
            // Check conditions for outputting HTML:
104
            // @todo: Make this more robust
105 1
            if (php_sapi_name() === 'cli') {
106
                // Help users who have been relying on an internal test value
107
                // fix their code to the proper method
108 1
                if (isset($_ENV['whoops-test'])) {
109
                    throw new \Exception(
110
                        'Use handleUnconditionally instead of whoops-test'
111
                        .' environment variable'
112
                    );
113
                }
114
115 1
                return Handler::DONE;
116
            }
117
        }
118
119
        // @todo: Make this more dynamic
120
        $helper = new TemplateHelper();
121
122
        if (class_exists('Symfony\Component\VarDumper\Cloner\VarCloner')) {
123
            $cloner = new VarCloner();
124
            // Only dump object internals if a custom caster exists.
125
            $cloner->addCasters(['*' => function ($obj, $a, $stub, $isNested, $filter = 0) {
0 ignored issues
show
Unused Code introduced by
The parameter $isNested is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $filter is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
126
                $class = $stub->class;
127
                $classes = [$class => $class] + class_parents($class) + class_implements($class);
128
129
                foreach ($classes as $class) {
130
                    if (isset(AbstractCloner::$defaultCasters[$class])) {
131
                        return $a;
132
                    }
133
                }
134
135
                // Remove all internals
136
                return [];
137
            }]);
138
            $helper->setCloner($cloner);
139
        }
140
141
        $templateFile = $this->getResource("views/layout.html.php");
142
        $cssFile      = $this->getResource("css/whoops.base.css");
143
        $zeptoFile    = $this->getResource("js/zepto.min.js");
144
        $clipboard    = $this->getResource("js/clipboard.min.js");
145
        $jsFile       = $this->getResource("js/whoops.base.js");
146
147
        if ($this->customCss) {
148
            $customCssFile = $this->getResource($this->customCss);
149
        }
150
151
        $inspector = $this->getInspector();
152
        $frames    = $inspector->getFrames();
153
154
        $code = $inspector->getException()->getCode();
155
156
        if ($inspector->getException() instanceof \ErrorException) {
157
            // ErrorExceptions wrap the php-error types within the "severity" property
158
            $code = Misc::translateErrorCode($inspector->getException()->getSeverity());
159
        }
160
161
        // List of variables that will be passed to the layout template.
162
        $vars = array(
163
            "page_title" => $this->getPageTitle(),
164
165
            // @todo: Asset compiler
166
            "stylesheet" => file_get_contents($cssFile),
167
            "zepto"      => file_get_contents($zeptoFile),
168
            "clipboard"  => file_get_contents($clipboard),
169
            "javascript" => file_get_contents($jsFile),
170
171
            // Template paths:
172
            "header"      => $this->getResource("views/header.html.php"),
173
            "frame_list"  => $this->getResource("views/frame_list.html.php"),
174
            "frame_code"  => $this->getResource("views/frame_code.html.php"),
175
            "env_details" => $this->getResource("views/env_details.html.php"),
176
177
            "title"          => $this->getPageTitle(),
178
            "name"           => explode("\\", $inspector->getExceptionName()),
179
            "message"        => $inspector->getException()->getMessage(),
180
            "code"           => $code,
181
            "plain_exception" => Formatter::formatExceptionPlain($inspector),
182
            "frames"         => $frames,
183
            "has_frames"     => !!count($frames),
184
            "handler"        => $this,
185
            "handlers"       => $this->getRun()->getHandlers(),
186
187
            "tables"      => array(
188
                "GET Data"              => $_GET,
189
                "POST Data"             => $_POST,
190
                "Files"                 => $_FILES,
191
                "Cookies"               => $_COOKIE,
192
                "Session"               => isset($_SESSION) ? $_SESSION :  array(),
193
                "Server/Request Data"   => $_SERVER,
194
                "Environment Variables" => $_ENV,
195
            ),
196
        );
197
198
        if (isset($customCssFile)) {
199
            $vars["stylesheet"] .= file_get_contents($customCssFile);
200
        }
201
202
        // Add extra entries list of data tables:
203
        // @todo: Consolidate addDataTable and addDataTableCallback
204
        $extraTables = array_map(function ($table) {
205
            return $table instanceof \Closure ? $table() : $table;
206
        }, $this->getDataTables());
207
        $vars["tables"] = array_merge($extraTables, $vars["tables"]);
208
209
        if (\Whoops\Util\Misc::canSendHeaders()) {
210
            header('Content-Type: text/html');
211
        }
212
213
        $helper->setVariables($vars);
214
        $helper->render($templateFile);
215
216
        return Handler::QUIT;
217
    }
218
219
    /**
220
     * Adds an entry to the list of tables displayed in the template.
221
     * The expected data is a simple associative array. Any nested arrays
222
     * will be flattened with print_r
223
     * @param string $label
224
     * @param array  $data
225
     */
226 1
    public function addDataTable($label, array $data)
227
    {
228 1
        $this->extraTables[$label] = $data;
229 1
    }
230
231
    /**
232
     * Lazily adds an entry to the list of tables displayed in the table.
233
     * The supplied callback argument will be called when the error is rendered,
234
     * it should produce a simple associative array. Any nested arrays will
235
     * be flattened with print_r.
236
     *
237
     * @throws InvalidArgumentException If $callback is not callable
238
     * @param  string                   $label
239
     * @param  callable                 $callback Callable returning an associative array
240
     */
241 1
    public function addDataTableCallback($label, /* callable */ $callback)
242
    {
243 1
        if (!is_callable($callback)) {
244
            throw new InvalidArgumentException('Expecting callback argument to be callable');
245
        }
246
247 1
        $this->extraTables[$label] = function () use ($callback) {
248
            try {
249 1
                $result = call_user_func($callback);
250
251
                // Only return the result if it can be iterated over by foreach().
252 1
                return is_array($result) || $result instanceof \Traversable ? $result : array();
253
            } catch (\Exception $e) {
254
                // Don't allow failure to break the rendering of the original exception.
255
                return array();
256
            }
257
        };
258 1
    }
259
260
    /**
261
     * Returns all the extra data tables registered with this handler.
262
     * Optionally accepts a 'label' parameter, to only return the data
263
     * table under that label.
264
     * @param  string|null      $label
265
     * @return array[]|callable
266
     */
267 2
    public function getDataTables($label = null)
268
    {
269 2
        if ($label !== null) {
270 2
            return isset($this->extraTables[$label]) ?
271 2
                   $this->extraTables[$label] : array();
272
        }
273
274 2
        return $this->extraTables;
275
    }
276
277
    /**
278
     * Allows to disable all attempts to dynamically decide whether to
279
     * handle or return prematurely.
280
     * Set this to ensure that the handler will perform no matter what.
281
     * @param  bool|null $value
282
     * @return bool|null
283
     */
284 1
    public function handleUnconditionally($value = null)
285
    {
286 1
        if (func_num_args() == 0) {
287 1
            return $this->handleUnconditionally;
288
        }
289
290
        $this->handleUnconditionally = (bool) $value;
291
    }
292
293
    /**
294
     * Adds an editor resolver, identified by a string
295
     * name, and that may be a string path, or a callable
296
     * resolver. If the callable returns a string, it will
297
     * be set as the file reference's href attribute.
298
     *
299
     * @example
300
     *  $run->addEditor('macvim', "mvim://open?url=file://%file&line=%line")
301
     * @example
302
     *   $run->addEditor('remove-it', function($file, $line) {
303
     *       unlink($file);
304
     *       return "http://stackoverflow.com";
305
     *   });
306
     * @param string $identifier
307
     * @param string $resolver
308
     */
309 1
    public function addEditor($identifier, $resolver)
310
    {
311 1
        $this->editors[$identifier] = $resolver;
312 1
    }
313
314
    /**
315
     * Set the editor to use to open referenced files, by a string
316
     * identifier, or a callable that will be executed for every
317
     * file reference, with a $file and $line argument, and should
318
     * return a string.
319
     *
320
     * @example
321
     *   $run->setEditor(function($file, $line) { return "file:///{$file}"; });
322
     * @example
323
     *   $run->setEditor('sublime');
324
     *
325
     * @throws InvalidArgumentException If invalid argument identifier provided
326
     * @param  string|callable          $editor
327
     */
328 4
    public function setEditor($editor)
329
    {
330 4
        if (!is_callable($editor) && !isset($this->editors[$editor])) {
331
            throw new InvalidArgumentException(
332
                "Unknown editor identifier: $editor. Known editors:" .
333
                implode(",", array_keys($this->editors))
334
            );
335
        }
336
337 4
        $this->editor = $editor;
338 4
    }
339
340
    /**
341
     * Given a string file path, and an integer file line,
342
     * executes the editor resolver and returns, if available,
343
     * a string that may be used as the href property for that
344
     * file reference.
345
     *
346
     * @throws InvalidArgumentException If editor resolver does not return a string
347
     * @param  string                   $filePath
348
     * @param  int                      $line
349
     * @return string|bool
350
     */
351 4
    public function getEditorHref($filePath, $line)
352
    {
353 4
        $editor = $this->getEditor($filePath, $line);
354
355 4
        if (!$editor) {
356
            return false;
357
        }
358
359
        // Check that the editor is a string, and replace the
360
        // %line and %file placeholders:
361 4
        if (!isset($editor['url']) || !is_string($editor['url'])) {
362
            throw new UnexpectedValueException(
363
                __METHOD__ . " should always resolve to a string or a valid editor array; got something else instead."
364
            );
365
        }
366
367 4
        $editor['url'] = str_replace("%line", rawurlencode($line), $editor['url']);
368 4
        $editor['url'] = str_replace("%file", rawurlencode($filePath), $editor['url']);
369
370 4
        return $editor['url'];
371
    }
372
373
    /**
374
     * Given a boolean if the editor link should
375
     * act as an Ajax request. The editor must be a
376
     * valid callable function/closure
377
     *
378
     * @throws UnexpectedValueException  If editor resolver does not return a boolean
379
     * @param  string                   $filePath
380
     * @param  int                      $line
381
     * @return bool
382
     */
383 1
    public function getEditorAjax($filePath, $line)
384
    {
385 1
        $editor = $this->getEditor($filePath, $line);
386
387
        // Check that the ajax is a bool
388 1
        if (!isset($editor['ajax']) || !is_bool($editor['ajax'])) {
389
            throw new UnexpectedValueException(
390
                __METHOD__ . " should always resolve to a bool; got something else instead."
391
            );
392
        }
393 1
        return $editor['ajax'];
394
    }
395
396
    /**
397
     * Given a boolean if the editor link should
398
     * act as an Ajax request. The editor must be a
399
     * valid callable function/closure
400
     *
401
     * @throws UnexpectedValueException  If editor resolver does not return a boolean
402
     * @param  string                   $filePath
403
     * @param  int                      $line
404
     * @return mixed
405
     */
406 1
    protected function getEditor($filePath, $line)
407
    {
408 1
        if ($this->editor === null && !is_string($this->editor) && !is_callable($this->editor))
409 1
        {
410
            return false;
411
        }
412 1
        else if(is_string($this->editor) && isset($this->editors[$this->editor]) && !is_callable($this->editors[$this->editor]))
413 1
        {
414
           return array(
415
                'ajax' => false,
416
                'url' => $this->editors[$this->editor],
417
            );
418
        }
419 1
        else if(is_callable($this->editor) || (isset($this->editors[$this->editor]) && is_callable($this->editors[$this->editor])))
420 1
        {
421 1
            if(is_callable($this->editor))
422 1
            {
423
                $callback = call_user_func($this->editor, $filePath, $line);
424
            }
425
            else
426
            {
427 1
                $callback = call_user_func($this->editors[$this->editor], $filePath, $line);
428
            }
429
430
            return array(
431 1
                'ajax' => isset($callback['ajax']) ? $callback['ajax'] : false,
432 1
                'url' => (is_array($callback) ? $callback['url'] : $callback),
433 1
            );
434
        }
435
436
        return false;
437
    }
438
439
    /**
440
     * @param  string $title
441
     * @return void
442
     */
443 1
    public function setPageTitle($title)
444
    {
445 1
        $this->pageTitle = (string) $title;
446 1
    }
447
448
    /**
449
     * @return string
450
     */
451 1
    public function getPageTitle()
452
    {
453 1
        return $this->pageTitle;
454
    }
455
456
    /**
457
     * Adds a path to the list of paths to be searched for
458
     * resources.
459
     *
460
     * @throws InvalidArgumnetException If $path is not a valid directory
461
     *
462
     * @param  string $path
463
     * @return void
464
     */
465 2
    public function addResourcePath($path)
466
    {
467 2
        if (!is_dir($path)) {
468 1
            throw new InvalidArgumentException(
469 1
                "'$path' is not a valid directory"
470 1
            );
471
        }
472
473 1
        array_unshift($this->searchPaths, $path);
474 1
    }
475
476
    /**
477
     * Adds a custom css file to be loaded.
478
     *
479
     * @param  string $name
480
     * @return void
481
     */
482
    public function addCustomCss($name)
483
    {
484
        $this->customCss = $name;
485
    }
486
487
    /**
488
     * @return array
489
     */
490 1
    public function getResourcePaths()
491
    {
492 1
        return $this->searchPaths;
493
    }
494
495
    /**
496
     * Finds a resource, by its relative path, in all available search paths.
497
     * The search is performed starting at the last search path, and all the
498
     * way back to the first, enabling a cascading-type system of overrides
499
     * for all resources.
500
     *
501
     * @throws RuntimeException If resource cannot be found in any of the available paths
502
     *
503
     * @param  string $resource
504
     * @return string
505
     */
506
    protected function getResource($resource)
507
    {
508
        // If the resource was found before, we can speed things up
509
        // by caching its absolute, resolved path:
510
        if (isset($this->resourceCache[$resource])) {
511
            return $this->resourceCache[$resource];
512
        }
513
514
        // Search through available search paths, until we find the
515
        // resource we're after:
516
        foreach ($this->searchPaths as $path) {
517
            $fullPath = $path . "/$resource";
518
519
            if (is_file($fullPath)) {
520
                // Cache the result:
521
                $this->resourceCache[$resource] = $fullPath;
522
                return $fullPath;
523
            }
524
        }
525
526
        // If we got this far, nothing was found.
527
        throw new RuntimeException(
528
            "Could not find resource '$resource' in any resource paths."
529
            . "(searched: " . join(", ", $this->searchPaths). ")"
530
        );
531
    }
532
533
    /**
534
     * @deprecated
535
     *
536
     * @return string
537
     */
538
    public function getResourcesPath()
539
    {
540
        $allPaths = $this->getResourcePaths();
541
542
        // Compat: return only the first path added
543
        return end($allPaths) ?: null;
544
    }
545
546
    /**
547
     * @deprecated
548
     *
549
     * @param  string $resourcesPath
550
     * @return void
551
     */
552
    public function setResourcesPath($resourcesPath)
553
    {
554
        $this->addResourcePath($resourcesPath);
555
    }
556
}
557