Completed
Push — master ( 2cc253...afab26 )
by Denis
02:41
created

PrettyPageHandler::handle()   C

Complexity

Conditions 12
Paths 66

Size

Total Lines 116
Code Lines 68

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 128.0517

Importance

Changes 3
Bugs 1 Features 0
Metric Value
c 3
b 1
f 0
dl 0
loc 116
ccs 5
cts 72
cp 0.0694
rs 5.034
cc 12
eloc 68
nc 66
nop 0
crap 128.0517

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