Completed
Pull Request — master (#479)
by Gregor
03:07
created

PrettyPageHandler::getApplicationRootPath()   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
dl 0
loc 4
ccs 0
cts 2
cp 0
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 2
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 = [];
27
28
    /**
29
     * Fast lookup cache for known resource locations.
30
     *
31
     * @var array
32
     */
33
    private $resourceCache = [];
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 = [];
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
     * @var array[]
59
     */
60
    private $applicationPaths;
61
62
    /**
63
     * @var string
64
     */
65
    private $applicationRootPath;
66
67
    /**
68
     * A string identifier for a known IDE/text editor, or a closure
69
     * that resolves a string that can be used to open a given file
70
     * in an editor. If the string contains the special substrings
71
     * %file or %line, they will be replaced with the correct data.
72
     *
73
     * @example
74
     *  "txmt://open?url=%file&line=%line"
75
     * @var mixed $editor
76
     */
77
    protected $editor;
78
79
    /**
80
     * A list of known editor strings
81
     * @var array
82
     */
83
    protected $editors = [
84
        "sublime"  => "subl://open?url=file://%file&line=%line",
85
        "textmate" => "txmt://open?url=file://%file&line=%line",
86
        "emacs"    => "emacs://open?url=file://%file&line=%line",
87
        "macvim"   => "mvim://open/?url=file://%file&line=%line",
88
        "phpstorm" => "phpstorm://open?file=%file&line=%line",
89
        "idea"     => "idea://open?file=%file&line=%line",
90
    ];
91
92
    /**
93
     * Constructor.
94
     */
95 1
    public function __construct()
96
    {
97 1
        if (ini_get('xdebug.file_link_format') || extension_loaded('xdebug')) {
98
            // Register editor using xdebug's file_link_format option.
99
            $this->editors['xdebug'] = function ($file, $line) {
100 1
                return str_replace(['%f', '%l'], [$file, $line], ini_get('xdebug.file_link_format'));
101
            };
102 1
        }
103
104
        // Add the default, local resource search path:
105 1
        $this->searchPaths[] = __DIR__ . "/../Resources";
106
107
        // root path for ordinary composer projects
108 1
        $this->applicationRootPath = dirname(dirname(dirname(dirname(dirname(dirname(__DIR__))))));
109 1
    }
110
111
    /**
112
     * @return int|null
113
     */
114 1
    public function handle()
115
    {
116 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...
117
            // Check conditions for outputting HTML:
118
            // @todo: Make this more robust
119 1
            if (php_sapi_name() === 'cli') {
120
                // Help users who have been relying on an internal test value
121
                // fix their code to the proper method
122 1
                if (isset($_ENV['whoops-test'])) {
123
                    throw new \Exception(
124
                        'Use handleUnconditionally instead of whoops-test'
125
                        .' environment variable'
126
                    );
127
                }
128
129 1
                return Handler::DONE;
130
            }
131
        }
132
133
        // @todo: Make this more dynamic
134
        $helper = new TemplateHelper();
135
136
        if (class_exists('Symfony\Component\VarDumper\Cloner\VarCloner')) {
137
            $cloner = new VarCloner();
138
            // Only dump object internals if a custom caster exists.
139
            $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...
140
                $class = $stub->class;
141
                $classes = [$class => $class] + class_parents($class) + class_implements($class);
142
143
                foreach ($classes as $class) {
144
                    if (isset(AbstractCloner::$defaultCasters[$class])) {
145
                        return $a;
146
                    }
147
                }
148
149
                // Remove all internals
150
                return [];
151
            }]);
152
            $helper->setCloner($cloner);
153
        }
154
155
        $helper->setApplicationRootPath($this->applicationRootPath);
156
157
        $templateFile = $this->getResource("views/layout.html.php");
158
        $cssFile      = $this->getResource("css/whoops.base.css");
159
        $zeptoFile    = $this->getResource("js/zepto.min.js");
160
        $clipboard    = $this->getResource("js/clipboard.min.js");
161
        $jsFile       = $this->getResource("js/whoops.base.js");
162
163
        if ($this->customCss) {
164
            $customCssFile = $this->getResource($this->customCss);
165
        }
166
167
        $inspector = $this->getInspector();
168
        $frames    = $inspector->getFrames();
169
170
        $code = $inspector->getException()->getCode();
171
172
        if ($inspector->getException() instanceof \ErrorException) {
173
            // ErrorExceptions wrap the php-error types within the "severity" property
174
            $code = Misc::translateErrorCode($inspector->getException()->getSeverity());
175
        }
176
177
        // Detect frames that belong to the application.
178
        if ($this->applicationPaths) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->applicationPaths of type array[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
179
            /* @var \Whoops\Exception\Frame $frame */
180
            foreach ($frames as $frame) {
181
                foreach ($this->applicationPaths as $path) {
182
                    if (substr($frame->getFile(), 0, strlen($path)) === $path) {
183
                        $frame->setApplication(true);
184
                        break;
185
                    }
186
                }
187
            }
188
        }
189
190
        // List of variables that will be passed to the layout template.
191
        $vars = [
192
            "page_title" => $this->getPageTitle(),
193
194
            // @todo: Asset compiler
195
            "stylesheet" => file_get_contents($cssFile),
196
            "zepto"      => file_get_contents($zeptoFile),
197
            "clipboard"  => file_get_contents($clipboard),
198
            "javascript" => file_get_contents($jsFile),
199
200
            // Template paths:
201
            "header"                     => $this->getResource("views/header.html.php"),
202
            "header_outer"               => $this->getResource("views/header_outer.html.php"),
203
            "frame_list"                 => $this->getResource("views/frame_list.html.php"),
204
            "frames_description"         => $this->getResource("views/frames_description.html.php"),
205
            "frames_container"           => $this->getResource("views/frames_container.html.php"),
206
            "panel_details"              => $this->getResource("views/panel_details.html.php"),
207
            "panel_details_outer"        => $this->getResource("views/panel_details_outer.html.php"),
208
            "panel_left"                 => $this->getResource("views/panel_left.html.php"),
209
            "panel_left_outer"           => $this->getResource("views/panel_left_outer.html.php"),
210
            "frame_code"                 => $this->getResource("views/frame_code.html.php"),
211
            "env_details"                => $this->getResource("views/env_details.html.php"),
212
213
            "title"          => $this->getPageTitle(),
214
            "name"           => explode("\\", $inspector->getExceptionName()),
215
            "message"        => $inspector->getException()->getMessage(),
216
            "code"           => $code,
217
            "plain_exception" => Formatter::formatExceptionPlain($inspector),
218
            "frames"         => $frames,
219
            "has_frames"     => !!count($frames),
220
            "handler"        => $this,
221
            "handlers"       => $this->getRun()->getHandlers(),
222
223
            "active_frames_tab" => count($frames) && $frames->offsetGet(0)->isApplication() ?  'application' : 'all',
0 ignored issues
show
Bug introduced by
The method isApplication cannot be called on $frames->offsetGet(0) (of type array).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
224
            "has_frames_tabs"   => $this->getApplicationPaths(),
225
226
            "tables"      => [
227
                "GET Data"              => $_GET,
228
                "POST Data"             => $_POST,
229
                "Files"                 => $_FILES,
230
                "Cookies"               => $_COOKIE,
231
                "Session"               => isset($_SESSION) ? $_SESSION :  [],
232
                "Server/Request Data"   => $_SERVER,
233
                "Environment Variables" => $_ENV,
234
            ],
235
        ];
236
237
        if (isset($customCssFile)) {
238
            $vars["stylesheet"] .= file_get_contents($customCssFile);
239
        }
240
241
        // Add extra entries list of data tables:
242
        // @todo: Consolidate addDataTable and addDataTableCallback
243
        $extraTables = array_map(function ($table) use ($inspector) {
244
            return $table instanceof \Closure ? $table($inspector) : $table;
245
        }, $this->getDataTables());
246
        $vars["tables"] = array_merge($extraTables, $vars["tables"]);
247
248
        $plainTextHandler = new PlainTextHandler();
249
        $plainTextHandler->setException($this->getException());
250
        $plainTextHandler->setInspector($this->getInspector());
251
        $vars["preface"] = "<!--\n\n\n" . $plainTextHandler->generateResponse() . "\n\n\n\n\n\n\n\n\n\n\n-->";
252
253
        $helper->setVariables($vars);
254
        $helper->render($templateFile);
255
256
        return Handler::QUIT;
257
    }
258
259
    /**
260
     * @return string
261
     */
262
    public function contentType()
263
    {
264
        return 'text/html';
265
    }
266
267
    /**
268
     * Adds an entry to the list of tables displayed in the template.
269
     * The expected data is a simple associative array. Any nested arrays
270
     * will be flattened with print_r
271
     * @param string $label
272
     * @param array  $data
273
     */
274 1
    public function addDataTable($label, array $data)
275
    {
276 1
        $this->extraTables[$label] = $data;
277 1
    }
278
279
    /**
280
     * Lazily adds an entry to the list of tables displayed in the table.
281
     * The supplied callback argument will be called when the error is rendered,
282
     * it should produce a simple associative array. Any nested arrays will
283
     * be flattened with print_r.
284
     *
285
     * @throws InvalidArgumentException If $callback is not callable
286
     * @param  string                   $label
287
     * @param  callable                 $callback Callable returning an associative array
288
     */
289 1
    public function addDataTableCallback($label, /* callable */ $callback)
290
    {
291 1
        if (!is_callable($callback)) {
292
            throw new InvalidArgumentException('Expecting callback argument to be callable');
293
        }
294
295 1
        $this->extraTables[$label] = function (\Whoops\Exception\Inspector $inspector = null) use ($callback) {
296
            try {
297 1
                $result = call_user_func($callback, $inspector);
298
299
                // Only return the result if it can be iterated over by foreach().
300 1
                return is_array($result) || $result instanceof \Traversable ? $result : [];
301
            } catch (\Exception $e) {
302
                // Don't allow failure to break the rendering of the original exception.
303
                return [];
304
            }
305
        };
306 1
    }
307
308
    /**
309
     * Returns all the extra data tables registered with this handler.
310
     * Optionally accepts a 'label' parameter, to only return the data
311
     * table under that label.
312
     * @param  string|null      $label
313
     * @return array[]|callable
314
     */
315 2
    public function getDataTables($label = null)
316
    {
317 2
        if ($label !== null) {
318 2
            return isset($this->extraTables[$label]) ?
319 2
                   $this->extraTables[$label] : [];
320
        }
321
322 2
        return $this->extraTables;
323
    }
324
325
    /**
326
     * Allows to disable all attempts to dynamically decide whether to
327
     * handle or return prematurely.
328
     * Set this to ensure that the handler will perform no matter what.
329
     * @param  bool|null $value
330
     * @return bool|null
331
     */
332 1
    public function handleUnconditionally($value = null)
333
    {
334 1
        if (func_num_args() == 0) {
335 1
            return $this->handleUnconditionally;
336
        }
337
338
        $this->handleUnconditionally = (bool) $value;
339
    }
340
341
    /**
342
     * Adds an editor resolver, identified by a string
343
     * name, and that may be a string path, or a callable
344
     * resolver. If the callable returns a string, it will
345
     * be set as the file reference's href attribute.
346
     *
347
     * @example
348
     *  $run->addEditor('macvim', "mvim://open?url=file://%file&line=%line")
349
     * @example
350
     *   $run->addEditor('remove-it', function($file, $line) {
351
     *       unlink($file);
352
     *       return "http://stackoverflow.com";
353
     *   });
354
     * @param string $identifier
355
     * @param string $resolver
356
     */
357 1
    public function addEditor($identifier, $resolver)
358
    {
359 1
        $this->editors[$identifier] = $resolver;
360 1
    }
361
362
    /**
363
     * Set the editor to use to open referenced files, by a string
364
     * identifier, or a callable that will be executed for every
365
     * file reference, with a $file and $line argument, and should
366
     * return a string.
367
     *
368
     * @example
369
     *   $run->setEditor(function($file, $line) { return "file:///{$file}"; });
370
     * @example
371
     *   $run->setEditor('sublime');
372
     *
373
     * @throws InvalidArgumentException If invalid argument identifier provided
374
     * @param  string|callable          $editor
375
     */
376 4
    public function setEditor($editor)
377
    {
378 4
        if (!is_callable($editor) && !isset($this->editors[$editor])) {
379
            throw new InvalidArgumentException(
380
                "Unknown editor identifier: $editor. Known editors:" .
381
                implode(",", array_keys($this->editors))
382
            );
383
        }
384
385 4
        $this->editor = $editor;
386 4
    }
387
388
    /**
389
     * Given a string file path, and an integer file line,
390
     * executes the editor resolver and returns, if available,
391
     * a string that may be used as the href property for that
392
     * file reference.
393
     *
394
     * @throws InvalidArgumentException If editor resolver does not return a string
395
     * @param  string                   $filePath
396
     * @param  int                      $line
397
     * @return string|bool
398
     */
399 4
    public function getEditorHref($filePath, $line)
400
    {
401 4
        $editor = $this->getEditor($filePath, $line);
402
403 4
        if (empty($editor)) {
404
            return false;
405
        }
406
407
        // Check that the editor is a string, and replace the
408
        // %line and %file placeholders:
409 4
        if (!isset($editor['url']) || !is_string($editor['url'])) {
410
            throw new UnexpectedValueException(
411
                __METHOD__ . " should always resolve to a string or a valid editor array; got something else instead."
412
            );
413
        }
414
415 4
        $editor['url'] = str_replace("%line", rawurlencode($line), $editor['url']);
416 4
        $editor['url'] = str_replace("%file", rawurlencode($filePath), $editor['url']);
417
418 4
        return $editor['url'];
419
    }
420
421
    /**
422
     * Given a boolean if the editor link should
423
     * act as an Ajax request. The editor must be a
424
     * valid callable function/closure
425
     *
426
     * @throws UnexpectedValueException  If editor resolver does not return a boolean
427
     * @param  string                   $filePath
428
     * @param  int                      $line
429
     * @return bool
430
     */
431 1
    public function getEditorAjax($filePath, $line)
432
    {
433 1
        $editor = $this->getEditor($filePath, $line);
434
435
        // Check that the ajax is a bool
436 1
        if (!isset($editor['ajax']) || !is_bool($editor['ajax'])) {
437
            throw new UnexpectedValueException(
438
                __METHOD__ . " should always resolve to a bool; got something else instead."
439
            );
440
        }
441 1
        return $editor['ajax'];
442
    }
443
444
    /**
445
     * Given a boolean if the editor link should
446
     * act as an Ajax request. The editor must be a
447
     * valid callable function/closure
448
     *
449
     * @param  string $filePath
450
     * @param  int    $line
451
     * @return array
452
     */
453 1
    protected function getEditor($filePath, $line)
454
    {
455 1
        if (!$this->editor || (!is_string($this->editor) && !is_callable($this->editor))) {
456
            return [];
457
        }
458
459 1
        if (is_string($this->editor) && isset($this->editors[$this->editor]) && !is_callable($this->editors[$this->editor])) {
460
           return [
461
                'ajax' => false,
462
                'url' => $this->editors[$this->editor],
463
            ];
464
        }
465
466 1
        if (is_callable($this->editor) || (isset($this->editors[$this->editor]) && is_callable($this->editors[$this->editor]))) {
467 1
            if (is_callable($this->editor)) {
468
                $callback = call_user_func($this->editor, $filePath, $line);
469
            } else {
470 1
                $callback = call_user_func($this->editors[$this->editor], $filePath, $line);
471
            }
472
473 1
            if (is_string($callback)) {
474
                return [
475 1
                    'ajax' => false,
476 1
                    'url' => $callback,
477 1
                ];
478
            }
479
480
            return [
481
                'ajax' => isset($callback['ajax']) ? $callback['ajax'] : false,
482
                'url' => isset($callback['url']) ? $callback['url'] : $callback,
483
            ];
484
        }
485
486
        return [];
487
    }
488
489
    /**
490
     * @param  string $title
491
     * @return void
492
     */
493 1
    public function setPageTitle($title)
494
    {
495 1
        $this->pageTitle = (string) $title;
496 1
    }
497
498
    /**
499
     * @return string
500
     */
501 1
    public function getPageTitle()
502
    {
503 1
        return $this->pageTitle;
504
    }
505
506
    /**
507
     * Adds a path to the list of paths to be searched for
508
     * resources.
509
     *
510
     * @throws InvalidArgumentException If $path is not a valid directory
511
     *
512
     * @param  string $path
513
     * @return void
514
     */
515 2
    public function addResourcePath($path)
516
    {
517 2
        if (!is_dir($path)) {
518 1
            throw new InvalidArgumentException(
519 1
                "'$path' is not a valid directory"
520 1
            );
521
        }
522
523 1
        array_unshift($this->searchPaths, $path);
524 1
    }
525
526
    /**
527
     * Adds a custom css file to be loaded.
528
     *
529
     * @param  string $name
530
     * @return void
531
     */
532
    public function addCustomCss($name)
533
    {
534
        $this->customCss = $name;
535
    }
536
537
    /**
538
     * @return array
539
     */
540 1
    public function getResourcePaths()
541
    {
542 1
        return $this->searchPaths;
543
    }
544
545
    /**
546
     * Finds a resource, by its relative path, in all available search paths.
547
     * The search is performed starting at the last search path, and all the
548
     * way back to the first, enabling a cascading-type system of overrides
549
     * for all resources.
550
     *
551
     * @throws RuntimeException If resource cannot be found in any of the available paths
552
     *
553
     * @param  string $resource
554
     * @return string
555
     */
556
    protected function getResource($resource)
557
    {
558
        // If the resource was found before, we can speed things up
559
        // by caching its absolute, resolved path:
560
        if (isset($this->resourceCache[$resource])) {
561
            return $this->resourceCache[$resource];
562
        }
563
564
        // Search through available search paths, until we find the
565
        // resource we're after:
566
        foreach ($this->searchPaths as $path) {
567
            $fullPath = $path . "/$resource";
568
569
            if (is_file($fullPath)) {
570
                // Cache the result:
571
                $this->resourceCache[$resource] = $fullPath;
572
                return $fullPath;
573
            }
574
        }
575
576
        // If we got this far, nothing was found.
577
        throw new RuntimeException(
578
            "Could not find resource '$resource' in any resource paths."
579
            . "(searched: " . join(", ", $this->searchPaths). ")"
580
        );
581
    }
582
583
    /**
584
     * @deprecated
585
     *
586
     * @return string
587
     */
588
    public function getResourcesPath()
589
    {
590
        $allPaths = $this->getResourcePaths();
591
592
        // Compat: return only the first path added
593
        return end($allPaths) ?: null;
594
    }
595
596
    /**
597
     * @deprecated
598
     *
599
     * @param  string $resourcesPath
600
     * @return void
601
     */
602
    public function setResourcesPath($resourcesPath)
603
    {
604
        $this->addResourcePath($resourcesPath);
605
    }
606
607
    /**
608
     * Return the application paths.
609
     *
610
     * @return array
611
     */
612
    public function getApplicationPaths()
613
    {
614
        return $this->applicationPaths;
615
    }
616
617
    /**
618
     * Set the application paths.
619
     *
620
     * @param array $applicationPaths
621
     */
622
    public function setApplicationPaths($applicationPaths)
623
    {
624
        $this->applicationPaths = $applicationPaths;
625
    }
626
627
    /**
628
     * Return the application root path.
629
     *
630
     * @return string
631
     */
632
    public function getApplicationRootPath()
633
    {
634
        return $this->applicationRootPath;
635
    }
636
637
    /**
638
     * Set the application root path.
639
     *
640
     * @param string $applicationRootPath
641
     */
642
    public function setApplicationRootPath($applicationRootPath)
643
    {
644
        $this->applicationRootPath = $applicationRootPath;
645
    }
646
}
647