Version 1
[yaffs-website] / vendor / psy / psysh / src / Psy / TabCompletion / AutoCompleter.php
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\TabCompletion;
13
14 use Psy\TabCompletion\Matcher\AbstractMatcher;
15
16 /**
17  * A readline tab completion service.
18  *
19  * @author Marc Garcia <markcial@gmail.com>
20  */
21 class AutoCompleter
22 {
23     /** @var Matcher\AbstractMatcher[] */
24     protected $matchers;
25
26     /**
27      * Register a tab completion Matcher.
28      *
29      * @param AbstractMatcher $matcher
30      */
31     public function addMatcher(AbstractMatcher $matcher)
32     {
33         $this->matchers[] = $matcher;
34     }
35
36     /**
37      * Activate readline tab completion.
38      */
39     public function activate()
40     {
41         readline_completion_function(array(&$this, 'callback'));
42     }
43
44     /**
45      * Handle readline completion.
46      *
47      * @param string $input Readline current word
48      * @param int    $index Current word index
49      * @param array  $info  readline_info() data
50      *
51      * @return array
52      */
53     public function processCallback($input, $index, $info = array())
54     {
55         $line = substr($info['line_buffer'], 0, $info['end']);
56         $tokens = token_get_all('<?php ' . $line);
57         // remove whitespaces
58         $tokens = array_filter($tokens, function ($token) {
59             return !AbstractMatcher::tokenIs($token, AbstractMatcher::T_WHITESPACE);
60         });
61
62         $matches = array();
63         foreach ($this->matchers as $matcher) {
64             if ($matcher->hasMatched($tokens)) {
65                 $matches = array_merge($matcher->getMatches($tokens), $matches);
66             }
67         }
68
69         $matches = array_unique($matches);
70
71         return !empty($matches) ? $matches : array('');
72     }
73
74     /**
75      * The readline_completion_function callback handler.
76      *
77      * @see processCallback
78      *
79      * @param $input
80      * @param $index
81      *
82      * @return array
83      */
84     public function callback($input, $index)
85     {
86         return $this->processCallback($input, $index, readline_info());
87     }
88
89     /**
90      * Remove readline callback handler on destruct.
91      */
92     public function __destruct()
93     {
94         // PHP didn't implement the whole readline API when they first switched
95         // to libedit. And they still haven't.
96         //
97         // So this is a thing to make PsySH work on 5.3.x:
98         if (function_exists('readline_callback_handler_remove')) {
99             readline_callback_handler_remove();
100         }
101     }
102 }