Completed
Push — master ( 39fad4...43b9bd )
by Denis
02:13
created

PrettyPageHandler::handle()   D

Complexity

Conditions 9
Paths 34

Size

Total Lines 95
Code Lines 57

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 71.112

Importance

Changes 6
Bugs 3 Features 1
Metric Value
c 6
b 3
f 1
dl 0
loc 95
ccs 5
cts 59
cp 0.0847
rs 4.9932
cc 9
eloc 57
nc 34
nop 0
crap 71.112

How to fix   Long Method   

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 UnexpectedValueException;
12
use Whoops\Exception\Formatter;
13
use Whoops\Util\Misc;
14
use Whoops\Util\TemplateHelper;
15
16
class PrettyPageHandler extends Handler
17
{
18
    /**
19
     * Search paths to be scanned for resources, in the reverse
20
     * order they're declared.
21
     *
22
     * @var array
23
     */
24
    private $searchPaths = array();
25
26
    /**
27
     * Fast lookup cache for known resource locations.
28
     *
29
     * @var array
30
     */
31
    private $resourceCache = array();
32
33
    /**
34
     * The name of the custom css file.
35
     *
36
     * @var string
37
     */
38
    private $customCss = null;
39
40
    /**
41
     * @var array[]
42
     */
43
    private $extraTables = array();
44
45
    /**
46
     * @var bool
47
     */
48
    private $handleUnconditionally = false;
49
50
    /**
51
     * @var string
52
     */
53
    private $pageTitle = "Whoops! There was an error.";
54
55
    /**
56
     * A string identifier for a known IDE/text editor, or a closure
57
     * that resolves a string that can be used to open a given file
58
     * in an editor. If the string contains the special substrings
59
     * %file or %line, they will be replaced with the correct data.
60
     *
61
     * @example
62
     *  "txmt://open?url=%file&line=%line"
63
     * @var mixed $editor
64
     */
65
    protected $editor;
66
67
    /**
68
     * A list of known editor strings
69
     * @var array
70
     */
71
    protected $editors = array(
72
        "sublime"  => "subl://open?url=file://%file&line=%line",
73
        "textmate" => "txmt://open?url=file://%file&line=%line",
74
        "emacs"    => "emacs://open?url=file://%file&line=%line",
75
        "macvim"   => "mvim://open/?url=file://%file&line=%line",
76
        "phpstorm" => "phpstorm://open?file=%file&line=%line",
77
    );
78
79
    /**
80
     * Constructor.
81
     */
82 1
    public function __construct()
83
    {
84 1
        if (ini_get('xdebug.file_link_format') || extension_loaded('xdebug')) {
85
            // Register editor using xdebug's file_link_format option.
86
            $this->editors['xdebug'] = function ($file, $line) {
87 1
                return str_replace(array('%f', '%l'), array($file, $line), ini_get('xdebug.file_link_format'));
88
            };
89 1
        }
90
91
        // Add the default, local resource search path:
92 1
        $this->searchPaths[] = __DIR__ . "/../Resources";
93 1
    }
94
95
    /**
96
     * @return int|null
97
     */
98 1
    public function handle()
99
    {
100 1
        if (!$this->handleUnconditionally()) {
101
            // Check conditions for outputting HTML:
102
            // @todo: Make this more robust
103 1
            if (php_sapi_name() === 'cli') {
104
                // Help users who have been relying on an internal test value
105
                // fix their code to the proper method
106 1
                if (isset($_ENV['whoops-test'])) {
107
                    throw new \Exception(
108
                        'Use handleUnconditionally instead of whoops-test'
109
                        .' environment variable'
110
                    );
111
                }
112
113 1
                return Handler::DONE;
114
            }
115
        }
116
117
        // @todo: Make this more dynamic
118
        $helper = new TemplateHelper();
119
120
        $templateFile = $this->getResource("views/layout.html.php");
121
        $cssFile      = $this->getResource("css/whoops.base.css");
122
        $zeptoFile    = $this->getResource("js/zepto.min.js");
123
        $clipboard    = $this->getResource("js/clipboard.min.js");
124
        $jsFile       = $this->getResource("js/whoops.base.js");
125
126
        if ($this->customCss) {
127
            $customCssFile = $this->getResource($this->customCss);
128
        }
129
130
        $inspector = $this->getInspector();
131
        $frames    = $inspector->getFrames();
132
133
        $code = $inspector->getException()->getCode();
134
135
        if ($inspector->getException() instanceof \ErrorException) {
136
            // ErrorExceptions wrap the php-error types within the "severity" property
137
            $code = Misc::translateErrorCode($inspector->getException()->getSeverity());
138
        }
139
140
        // List of variables that will be passed to the layout template.
141
        $vars = array(
142
            "page_title" => $this->getPageTitle(),
143
144
            // @todo: Asset compiler
145
            "stylesheet" => file_get_contents($cssFile),
146
            "zepto"      => file_get_contents($zeptoFile),
147
            "clipboard"  => file_get_contents($clipboard),
148
            "javascript" => file_get_contents($jsFile),
149
150
            // Template paths:
151
            "header"      => $this->getResource("views/header.html.php"),
152
            "frame_list"  => $this->getResource("views/frame_list.html.php"),
153
            "frame_code"  => $this->getResource("views/frame_code.html.php"),
154
            "env_details" => $this->getResource("views/env_details.html.php"),
155
156
            "title"          => $this->getPageTitle(),
157
            "name"           => explode("\\", $inspector->getExceptionName()),
158
            "message"        => $inspector->getException()->getMessage(),
159
            "code"           => $code,
160
            "plain_exception" => Formatter::formatExceptionPlain($inspector),
161
            "frames"         => $frames,
162
            "has_frames"     => !!count($frames),
163
            "handler"        => $this,
164
            "handlers"       => $this->getRun()->getHandlers(),
165
166
            "tables"      => array(
167
                "GET Data"              => $_GET,
168
                "POST Data"             => $_POST,
169
                "Files"                 => $_FILES,
170
                "Cookies"               => $_COOKIE,
171
                "Session"               => isset($_SESSION) ? $_SESSION :  array(),
172
                "Server/Request Data"   => $_SERVER,
173
                "Environment Variables" => $_ENV,
174
            ),
175
        );
176
177
        if (isset($customCssFile)) {
178
            $vars["stylesheet"] .= file_get_contents($customCssFile);
179
        }
180
181
        // Add extra entries list of data tables:
182
        // @todo: Consolidate addDataTable and addDataTableCallback
183
        $extraTables = array_map(function ($table) {
184
            return $table instanceof \Closure ? $table() : $table;
185
        }, $this->getDataTables());
186
        $vars["tables"] = array_merge($extraTables, $vars["tables"]);
187
188
        $helper->setVariables($vars);
189
        $helper->render($templateFile);
190
191
        return Handler::QUIT;
192
    }
193
194
    /**
195
     * Adds an entry to the list of tables displayed in the template.
196
     * The expected data is a simple associative array. Any nested arrays
197
     * will be flattened with print_r
198
     * @param string $label
199
     * @param array  $data
200
     */
201 1
    public function addDataTable($label, array $data)
202
    {
203 1
        $this->extraTables[$label] = $data;
204 1
    }
205
206
    /**
207
     * Lazily adds an entry to the list of tables displayed in the table.
208
     * The supplied callback argument will be called when the error is rendered,
209
     * it should produce a simple associative array. Any nested arrays will
210
     * be flattened with print_r.
211
     *
212
     * @throws InvalidArgumentException If $callback is not callable
213
     * @param  string                   $label
214
     * @param  callable                 $callback Callable returning an associative array
215
     */
216 1
    public function addDataTableCallback($label, /* callable */ $callback)
217
    {
218 1
        if (!is_callable($callback)) {
219
            throw new InvalidArgumentException('Expecting callback argument to be callable');
220
        }
221
222 1
        $this->extraTables[$label] = function () use ($callback) {
223
            try {
224 1
                $result = call_user_func($callback);
225
226
                // Only return the result if it can be iterated over by foreach().
227 1
                return is_array($result) || $result instanceof \Traversable ? $result : array();
228
            } catch (\Exception $e) {
229
                // Don't allow failure to break the rendering of the original exception.
230
                return array();
231
            }
232
        };
233 1
    }
234
235
    /**
236
     * Returns all the extra data tables registered with this handler.
237
     * Optionally accepts a 'label' parameter, to only return the data
238
     * table under that label.
239
     * @param  string|null      $label
240
     * @return array[]|callable
241
     */
242 2
    public function getDataTables($label = null)
243
    {
244 2
        if ($label !== null) {
245 2
            return isset($this->extraTables[$label]) ?
246 2
                   $this->extraTables[$label] : array();
247
        }
248
249 2
        return $this->extraTables;
250
    }
251
252
    /**
253
     * Allows to disable all attempts to dynamically decide whether to
254
     * handle or return prematurely.
255
     * Set this to ensure that the handler will perform no matter what.
256
     * @param  bool|null $value
257
     * @return bool|null
258
     */
259 1
    public function handleUnconditionally($value = null)
260
    {
261 1
        if (func_num_args() == 0) {
262 1
            return $this->handleUnconditionally;
263
        }
264
265
        $this->handleUnconditionally = (bool) $value;
266
    }
267
268
    /**
269
     * Adds an editor resolver, identified by a string
270
     * name, and that may be a string path, or a callable
271
     * resolver. If the callable returns a string, it will
272
     * be set as the file reference's href attribute.
273
     *
274
     * @example
275
     *  $run->addEditor('macvim', "mvim://open?url=file://%file&line=%line")
276
     * @example
277
     *   $run->addEditor('remove-it', function($file, $line) {
278
     *       unlink($file);
279
     *       return "http://stackoverflow.com";
280
     *   });
281
     * @param string $identifier
282
     * @param string $resolver
283
     */
284 1
    public function addEditor($identifier, $resolver)
285
    {
286 1
        $this->editors[$identifier] = $resolver;
287 1
    }
288
289
    /**
290
     * Set the editor to use to open referenced files, by a string
291
     * identifier, or a callable that will be executed for every
292
     * file reference, with a $file and $line argument, and should
293
     * return a string.
294
     *
295
     * @example
296
     *   $run->setEditor(function($file, $line) { return "file:///{$file}"; });
297
     * @example
298
     *   $run->setEditor('sublime');
299
     *
300
     * @throws InvalidArgumentException If invalid argument identifier provided
301
     * @param  string|callable          $editor
302
     */
303 4
    public function setEditor($editor)
304
    {
305 4
        if (!is_callable($editor) && !isset($this->editors[$editor])) {
306
            throw new InvalidArgumentException(
307
                "Unknown editor identifier: $editor. Known editors:" .
308
                implode(",", array_keys($this->editors))
309
            );
310
        }
311
312 4
        $this->editor = $editor;
313 4
    }
314
315
    /**
316
     * Given a string file path, and an integer file line,
317
     * executes the editor resolver and returns, if available,
318
     * a string that may be used as the href property for that
319
     * file reference.
320
     *
321
     * @throws InvalidArgumentException If editor resolver does not return a string
322
     * @param  string                   $filePath
323
     * @param  int                      $line
324
     * @return string|bool
325
     */
326 4
    public function getEditorHref($filePath, $line)
327
    {
328 4
        $editor = $this->getEditor($filePath, $line);
329
330 4
        if (!$editor) {
331
            return false;
332
        }
333
334
        // Check that the editor is a string, and replace the
335
        // %line and %file placeholders:
336 4
        if (!isset($editor['url']) || !is_string($editor['url'])) {
337
            throw new UnexpectedValueException(
338
                __METHOD__ . " should always resolve to a string or a valid editor array; got something else instead."
339
            );
340
        }
341
342 4
        $editor['url'] = str_replace("%line", rawurlencode($line), $editor['url']);
343 4
        $editor['url'] = str_replace("%file", rawurlencode($filePath), $editor['url']);
344
345 4
        return $editor['url'];
346
    }
347
348
    /**
349
     * Given a boolean if the editor link should
350
     * act as an Ajax request. The editor must be a
351
     * valid callable function/closure
352
     *
353
     * @throws UnexpectedValueException  If editor resolver does not return a boolean
354
     * @param  string                   $filePath
355
     * @param  int                      $line
356
     * @return bool
357
     */
358 1
    public function getEditorAjax($filePath, $line)
359
    {
360 1
        $editor = $this->getEditor($filePath, $line);
361
362
        // Check that the ajax is a bool
363 1
        if (!isset($editor['ajax']) || !is_bool($editor['ajax'])) {
364
            throw new UnexpectedValueException(
365
                __METHOD__ . " should always resolve to a bool; got something else instead."
366
            );
367
        }
368 1
        return $editor['ajax'];
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 mixed
380
     */
381 1
    protected function getEditor($filePath, $line)
382
    {
383 1
        if ($this->editor === null && !is_string($this->editor) && !is_callable($this->editor))
384 1
        {
385
            return false;
386
        }
387 1
        else if(is_string($this->editor) && isset($this->editors[$this->editor]) && !is_callable($this->editors[$this->editor]))
388 1
        {
389
           return array(
390
                'ajax' => false,
391
                'url' => $this->editors[$this->editor],
392
            );
393
        }
394 1
        else if(is_callable($this->editor) || (isset($this->editors[$this->editor]) && is_callable($this->editors[$this->editor])))
395 1
        {
396 1
            if(is_callable($this->editor))
397 1
            {
398
                $callback = call_user_func($this->editor, $filePath, $line);
399
            }
400
            else
401
            {
402 1
                $callback = call_user_func($this->editors[$this->editor], $filePath, $line);
403
            }
404
405
            return array(
406 1
                'ajax' => isset($callback['ajax']) ? $callback['ajax'] : false,
407 1
                'url' => (is_array($callback) ? $callback['url'] : $callback),
408 1
            );
409
        }
410
411
        return false;
412
    }
413
414
    /**
415
     * @param  string $title
416
     * @return void
417
     */
418 1
    public function setPageTitle($title)
419
    {
420 1
        $this->pageTitle = (string) $title;
421 1
    }
422
423
    /**
424
     * @return string
425
     */
426 1
    public function getPageTitle()
427
    {
428 1
        return $this->pageTitle;
429
    }
430
431
    /**
432
     * Adds a path to the list of paths to be searched for
433
     * resources.
434
     *
435
     * @throws InvalidArgumnetException If $path is not a valid directory
436
     *
437
     * @param  string $path
438
     * @return void
439
     */
440 2
    public function addResourcePath($path)
441
    {
442 2
        if (!is_dir($path)) {
443 1
            throw new InvalidArgumentException(
444 1
                "'$path' is not a valid directory"
445 1
            );
446
        }
447
448 1
        array_unshift($this->searchPaths, $path);
449 1
    }
450
451
    /**
452
     * Adds a custom css file to be loaded.
453
     *
454
     * @param  string $name
455
     * @return void
456
     */
457
    public function addCustomCss($name)
458
    {
459
        $this->customCss = $name;
460
    }
461
462
    /**
463
     * @return array
464
     */
465 1
    public function getResourcePaths()
466
    {
467 1
        return $this->searchPaths;
468
    }
469
470
    /**
471
     * Finds a resource, by its relative path, in all available search paths.
472
     * The search is performed starting at the last search path, and all the
473
     * way back to the first, enabling a cascading-type system of overrides
474
     * for all resources.
475
     *
476
     * @throws RuntimeException If resource cannot be found in any of the available paths
477
     *
478
     * @param  string $resource
479
     * @return string
480
     */
481
    protected function getResource($resource)
482
    {
483
        // If the resource was found before, we can speed things up
484
        // by caching its absolute, resolved path:
485
        if (isset($this->resourceCache[$resource])) {
486
            return $this->resourceCache[$resource];
487
        }
488
489
        // Search through available search paths, until we find the
490
        // resource we're after:
491
        foreach ($this->searchPaths as $path) {
492
            $fullPath = $path . "/$resource";
493
494
            if (is_file($fullPath)) {
495
                // Cache the result:
496
                $this->resourceCache[$resource] = $fullPath;
497
                return $fullPath;
498
            }
499
        }
500
501
        // If we got this far, nothing was found.
502
        throw new RuntimeException(
503
            "Could not find resource '$resource' in any resource paths."
504
            . "(searched: " . join(", ", $this->searchPaths). ")"
505
        );
506
    }
507
508
    /**
509
     * @deprecated
510
     *
511
     * @return string
512
     */
513
    public function getResourcesPath()
514
    {
515
        $allPaths = $this->getResourcePaths();
516
517
        // Compat: return only the first path added
518
        return end($allPaths) ?: null;
519
    }
520
521
    /**
522
     * @deprecated
523
     *
524
     * @param  string $resourcesPath
525
     * @return void
526
     */
527
    public function setResourcesPath($resourcesPath)
528
    {
529
        $this->addResourcePath($resourcesPath);
530
    }
531
}
532