comparison vendor/psy/psysh/src/Formatter/CodeFormatter.php @ 13:5fb285c0d0e3

Update Drupal core to 8.4.7 via Composer. Security update; I *think* we've been lucky to get away with this so far, as we don't support self-registration which seems to be used by the so-called "drupalgeddon 2" attack that 8.4.5 was vulnerable to.
author Chris Cannam
date Mon, 23 Apr 2018 09:33:26 +0100
parents
children c2387f117808
comparison
equal deleted inserted replaced
12:7a779792577d 13:5fb285c0d0e3
1 <?php
2
3 /*
4 * This file is part of Psy Shell.
5 *
6 * (c) 2012-2018 Justin Hileman
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Psy\Formatter;
13
14 use JakubOnderka\PhpConsoleHighlighter\Highlighter;
15 use Psy\Configuration;
16 use Psy\ConsoleColorFactory;
17 use Psy\Exception\RuntimeException;
18
19 /**
20 * A pretty-printer for code.
21 */
22 class CodeFormatter implements Formatter
23 {
24 /**
25 * Format the code represented by $reflector.
26 *
27 * @param \Reflector $reflector
28 * @param null|string $colorMode (default: null)
29 *
30 * @return string formatted code
31 */
32 public static function format(\Reflector $reflector, $colorMode = null)
33 {
34 if (!self::isReflectable($reflector)) {
35 throw new RuntimeException('Source code unavailable');
36 }
37
38 $colorMode = $colorMode ?: Configuration::COLOR_MODE_AUTO;
39
40 if ($reflector instanceof \ReflectionGenerator) {
41 $reflector = $reflector->getFunction();
42 }
43
44 if ($fileName = $reflector->getFileName()) {
45 if (!is_file($fileName)) {
46 throw new RuntimeException('Source code unavailable');
47 }
48
49 $file = file_get_contents($fileName);
50 $start = $reflector->getStartLine();
51 $end = $reflector->getEndLine() - $start;
52
53 $factory = new ConsoleColorFactory($colorMode);
54 $colors = $factory->getConsoleColor();
55 $highlighter = new Highlighter($colors);
56
57 return $highlighter->getCodeSnippet($file, $start, 0, $end);
58 } else {
59 throw new RuntimeException('Source code unavailable');
60 }
61 }
62
63 /**
64 * Check whether a Reflector instance is reflectable by this formatter.
65 *
66 * @param \Reflector $reflector
67 *
68 * @return bool
69 */
70 private static function isReflectable(\Reflector $reflector)
71 {
72 return $reflector instanceof \ReflectionClass ||
73 $reflector instanceof \ReflectionFunctionAbstract ||
74 $reflector instanceof \ReflectionGenerator;
75 }
76 }