annotate vendor/psy/psysh/src/Psy/Formatter/CodeFormatter.php @ 7:848c88cfe644

More layout
author Chris Cannam
date Fri, 05 Jan 2018 13:59:44 +0000
parents 4c8ae668cc8c
children 7a779792577d
rev   line source
Chris@0 1 <?php
Chris@0 2
Chris@0 3 /*
Chris@0 4 * This file is part of Psy Shell.
Chris@0 5 *
Chris@0 6 * (c) 2012-2017 Justin Hileman
Chris@0 7 *
Chris@0 8 * For the full copyright and license information, please view the LICENSE
Chris@0 9 * file that was distributed with this source code.
Chris@0 10 */
Chris@0 11
Chris@0 12 namespace Psy\Formatter;
Chris@0 13
Chris@0 14 use JakubOnderka\PhpConsoleHighlighter\Highlighter;
Chris@0 15 use Psy\Configuration;
Chris@0 16 use Psy\ConsoleColorFactory;
Chris@0 17 use Psy\Exception\RuntimeException;
Chris@0 18
Chris@0 19 /**
Chris@0 20 * A pretty-printer for code.
Chris@0 21 */
Chris@0 22 class CodeFormatter implements Formatter
Chris@0 23 {
Chris@0 24 /**
Chris@0 25 * Format the code represented by $reflector.
Chris@0 26 *
Chris@0 27 * @param \Reflector $reflector
Chris@0 28 * @param null|string $colorMode (default: null)
Chris@0 29 *
Chris@0 30 * @return string formatted code
Chris@0 31 */
Chris@0 32 public static function format(\Reflector $reflector, $colorMode = null)
Chris@0 33 {
Chris@0 34 if (!self::isReflectable($reflector)) {
Chris@0 35 throw new RuntimeException('Source code unavailable.');
Chris@0 36 }
Chris@0 37
Chris@0 38 $colorMode = $colorMode ?: Configuration::COLOR_MODE_AUTO;
Chris@0 39
Chris@0 40 if ($reflector instanceof \ReflectionGenerator) {
Chris@0 41 $reflector = $reflector->getFunction();
Chris@0 42 }
Chris@0 43
Chris@0 44 if ($fileName = $reflector->getFileName()) {
Chris@0 45 if (!is_file($fileName)) {
Chris@0 46 throw new RuntimeException('Source code unavailable.');
Chris@0 47 }
Chris@0 48
Chris@0 49 $file = file_get_contents($fileName);
Chris@0 50 $start = $reflector->getStartLine();
Chris@0 51 $end = $reflector->getEndLine() - $start;
Chris@0 52
Chris@0 53 $factory = new ConsoleColorFactory($colorMode);
Chris@0 54 $colors = $factory->getConsoleColor();
Chris@0 55 $highlighter = new Highlighter($colors);
Chris@0 56
Chris@0 57 return $highlighter->getCodeSnippet($file, $start, 0, $end);
Chris@0 58 } else {
Chris@0 59 throw new RuntimeException('Source code unavailable.');
Chris@0 60 }
Chris@0 61 }
Chris@0 62
Chris@0 63 /**
Chris@0 64 * Check whether a Reflector instance is reflectable by this formatter.
Chris@0 65 *
Chris@0 66 * @param \Reflector $reflector
Chris@0 67 *
Chris@0 68 * @return bool
Chris@0 69 */
Chris@0 70 private static function isReflectable(\Reflector $reflector)
Chris@0 71 {
Chris@0 72 return $reflector instanceof \ReflectionClass ||
Chris@0 73 $reflector instanceof \ReflectionFunctionAbstract ||
Chris@0 74 $reflector instanceof \ReflectionGenerator;
Chris@0 75 }
Chris@0 76 }