Mercurial > hg > isophonics-drupal-site
comparison vendor/psy/psysh/src/Psy/Formatter/CodeFormatter.php @ 0:4c8ae668cc8c
Initial import (non-working)
author | Chris Cannam |
---|---|
date | Wed, 29 Nov 2017 16:09:58 +0000 |
parents | |
children | 7a779792577d |
comparison
equal
deleted
inserted
replaced
-1:000000000000 | 0:4c8ae668cc8c |
---|---|
1 <?php | |
2 | |
3 /* | |
4 * This file is part of Psy Shell. | |
5 * | |
6 * (c) 2012-2017 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 } |