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\Command;
14 use JakubOnderka\PhpConsoleHighlighter\Highlighter;
15 use Psy\Configuration;
16 use Psy\ConsoleColorFactory;
17 use Psy\Output\ShellOutput;
18 use Symfony\Component\Console\Input\InputInterface;
19 use Symfony\Component\Console\Input\InputOption;
20 use Symfony\Component\Console\Output\OutputInterface;
23 * Show the context of where you opened the debugger.
25 class WhereamiCommand extends Command
30 * @param null|string $colorMode (default: null)
32 public function __construct($colorMode = null)
34 $this->colorMode = $colorMode ?: Configuration::COLOR_MODE_AUTO;
36 if (version_compare(PHP_VERSION, '5.3.6', '>=')) {
37 $this->backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
39 $this->backtrace = debug_backtrace();
42 return parent::__construct();
48 protected function configure()
52 ->setDefinition(array(
53 new InputOption('num', 'n', InputOption::VALUE_OPTIONAL, 'Number of lines before and after.', '5'),
55 ->setDescription('Show where you are in the code.')
58 Show where you are in the code.
60 Optionally, include how many lines before and after you want to display.
63 <return>> whereami </return>
64 <return>> whereami -n10</return>
70 * Obtains the correct trace in the full backtrace.
74 protected function trace()
76 foreach ($this->backtrace as $i => $backtrace) {
77 if (!isset($backtrace['class'], $backtrace['function'])) {
80 $correctClass = $backtrace['class'] === 'Psy\Shell';
81 $correctFunction = $backtrace['function'] === 'debug';
82 if ($correctClass && $correctFunction) {
87 return end($this->backtrace);
91 * Determine the file and line based on the specific backtrace.
95 protected function fileInfo()
97 $backtrace = $this->trace();
98 if (preg_match('/eval\(/', $backtrace['file'])) {
99 preg_match_all('/([^\(]+)\((\d+)/', $backtrace['file'], $matches);
100 $file = $matches[1][0];
101 $line = (int) $matches[2][0];
103 $file = $backtrace['file'];
104 $line = $backtrace['line'];
107 return compact('file', 'line');
113 protected function execute(InputInterface $input, OutputInterface $output)
115 $info = $this->fileInfo();
116 $num = $input->getOption('num');
117 $factory = new ConsoleColorFactory($this->colorMode);
118 $colors = $factory->getConsoleColor();
119 $highlighter = new Highlighter($colors);
120 $contents = file_get_contents($info['file']);
121 $output->page($highlighter->getCodeSnippet($contents, $info['line'], $num, $num), ShellOutput::OUTPUT_RAW);