4 * This file is part of Psy Shell.
6 * (c) 2012-2017 Justin Hileman
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Psy\Formatter;
14 use JakubOnderka\PhpConsoleHighlighter\Highlighter;
15 use Psy\Configuration;
16 use Psy\ConsoleColorFactory;
17 use Psy\Exception\RuntimeException;
20 * A pretty-printer for code.
22 class CodeFormatter implements Formatter
25 * Format the code represented by $reflector.
27 * @param \Reflector $reflector
28 * @param null|string $colorMode (default: null)
30 * @return string formatted code
32 public static function format(\Reflector $reflector, $colorMode = null)
34 if (!self::isReflectable($reflector)) {
35 throw new RuntimeException('Source code unavailable.');
38 $colorMode = $colorMode ?: Configuration::COLOR_MODE_AUTO;
40 if ($reflector instanceof \ReflectionGenerator) {
41 $reflector = $reflector->getFunction();
44 if ($fileName = $reflector->getFileName()) {
45 if (!is_file($fileName)) {
46 throw new RuntimeException('Source code unavailable.');
49 $file = file_get_contents($fileName);
50 $start = $reflector->getStartLine();
51 $end = $reflector->getEndLine() - $start;
53 $factory = new ConsoleColorFactory($colorMode);
54 $colors = $factory->getConsoleColor();
55 $highlighter = new Highlighter($colors);
57 return $highlighter->getCodeSnippet($file, $start, 0, $end);
59 throw new RuntimeException('Source code unavailable.');
64 * Check whether a Reflector instance is reflectable by this formatter.
66 * @param \Reflector $reflector
70 private static function isReflectable(\Reflector $reflector)
72 return $reflector instanceof \ReflectionClass ||
73 $reflector instanceof \ReflectionFunctionAbstract ||
74 $reflector instanceof \ReflectionGenerator;