Updated from some -dev modules to alpha, beta or full releases
[yaffs-website] / vendor / psy / psysh / src / Formatter / CodeFormatter.php
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 ($fileName = $reflector->getFileName()) {
41             if (!is_file($fileName)) {
42                 throw new RuntimeException('Source code unavailable');
43             }
44
45             $file  = file_get_contents($fileName);
46             $start = $reflector->getStartLine();
47             $end   = $reflector->getEndLine() - $start;
48
49             $factory     = new ConsoleColorFactory($colorMode);
50             $colors      = $factory->getConsoleColor();
51             $highlighter = new Highlighter($colors);
52
53             return $highlighter->getCodeSnippet($file, $start, 0, $end);
54         } else {
55             throw new RuntimeException('Source code unavailable');
56         }
57     }
58
59     /**
60      * Check whether a Reflector instance is reflectable by this formatter.
61      *
62      * @param \Reflector $reflector
63      *
64      * @return bool
65      */
66     private static function isReflectable(\Reflector $reflector)
67     {
68         return $reflector instanceof \ReflectionClass ||
69             $reflector instanceof \ReflectionFunctionAbstract;
70     }
71 }