Debian Codegraph @

vendor/clue/stdio-react/src/Readline.php

raw
1 <?php
2
3 namespace Clue\React\Stdio;
4
5 use Clue\React\Term\ControlCodeParser;
6 use Clue\React\Utf8\Sequencer as Utf8Sequencer;
7 use Evenement\EventEmitter;
8 use Evenement\EventEmitterInterface;
9 use React\Stream\ReadableStreamInterface;
10 use React\Stream\Util;
11 use React\Stream\WritableStreamInterface;
12
13 /**
14 * @deprecated use Stdio instead
15 * @see Stdio
16 */
17 class Readline extends EventEmitter implements ReadableStreamInterface
18 {
19 private $prompt = '';
20 private $linebuffer = '';
21 private $linepos = 0;
22 private $echo = true;
23 private $move = true;
24 private $bell = true;
25 private $encoding = 'utf-8';
26
27 private $input;
28 private $output;
29 private $sequencer;
30 private $closed = false;
31
32 private $historyLines = array();
33 private $historyPosition = null;
34 private $historyUnsaved = null;
35 private $historyLimit = 500;
36
37 private $autocomplete = null;
38 private $autocompleteSuggestions = 8;
39
40 public function __construct(ReadableStreamInterface $input, WritableStreamInterface $output, EventEmitterInterface $base = null)
41 {
42 $this->input = $input;
43 $this->output = $output;
44
45 if (!$this->input->isReadable()) {
46 $this->close();
47 return;
48 }
49 // push input through control code parser
50 $parser = new ControlCodeParser($input);
51
52 $that = $this;
53 $codes = array(
54 "\n" => 'onKeyEnter', // ^J
55 "\x7f" => 'onKeyBackspace', // ^?
56 "\t" => 'onKeyTab', // ^I
57 "\x04" => 'handleEnd', // ^D
58
59 "\033[A" => 'onKeyUp',
60 "\033[B" => 'onKeyDown',
61 "\033[C" => 'onKeyRight',
62 "\033[D" => 'onKeyLeft',
63
64 "\033[1~" => 'onKeyHome',
65 // "\033[2~" => 'onKeyInsert',
66 "\033[3~" => 'onKeyDelete',
67 "\033[4~" => 'onKeyEnd',
68
69 // "\033[20~" => 'onKeyF10',
70 );
71 $decode = function ($code) use ($codes, $that, $base) {
72 // The user confirms input with enter key which should usually
73 // generate a NL (`\n`) character. Common terminals also seem to
74 // accept a CR (`\r`) character in place and handle this just like a
75 // NL. Similarly `ext-readline` uses different `icrnl` and `igncr`
76 // TTY settings on some platforms, so we also accept CR as an alias
77 // for NL here. This implies key binding for NL will also trigger.
78 if ($code === "\r") {
79 $code = "\n";
80 }
81
82 // forward compatibility: check if any key binding exists on base Stdio instance
83 if ($base !== null && $base->listeners($code)) {
84 $base->emit($code, array($code));
85 return;
86 }
87
88 // deprecated: check if any key binding exists on this Readline instance
89 if ($that->listeners($code)) {
90 $that->emit($code, array($code));
91 return;
92 }
93
94 if (isset($codes[$code])) {
95 $method = $codes[$code];
96 $that->$method($code);
97 return;
98 }
99 };
100
101 $parser->on('csi', $decode);
102 $parser->on('c0', $decode);
103
104 // push resulting data through utf8 sequencer
105 $utf8 = new Utf8Sequencer($parser);
106 $utf8->on('data', function ($data) use ($that, $base) {
107 $that->onFallback($data, $base);
108 });
109
110 // process all stream events (forwarded from input stream)
111 $utf8->on('end', array($this, 'handleEnd'));
112 $utf8->on('error', array($this, 'handleError'));
113 $utf8->on('close', array($this, 'close'));
114 }
115
116 /**
117 * prompt to prepend to input line
118 *
119 * Will redraw the current input prompt with the current input buffer.
120 *
121 * @param string $prompt
122 * @return self
123 * @uses self::redraw()
124 * @deprecated use Stdio::setPrompt() instead
125 */
126 public function setPrompt($prompt)
127 {
128 if ($prompt === $this->prompt) {
129 return $this;
130 }
131
132 $this->prompt = $prompt;
133
134 return $this->redraw();
135 }
136
137 /**
138 * returns the prompt to prepend to input line
139 *
140 * @return string
141 * @see self::setPrompt()
142 * @deprecated use Stdio::getPrompt() instead
143 */
144 public function getPrompt()
145 {
146 return $this->prompt;
147 }
148
149 /**
150 * sets whether/how to echo text input
151 *
152 * The default setting is `true`, which means that every character will be
153 * echo'ed as-is, i.e. you can see what you're typing.
154 * For example: Typing "test" shows "test".
155 *
156 * You can turn this off by supplying `false`, which means that *nothing*
157 * will be echo'ed while you're typing. This could be a good idea for
158 * password prompts. Note that this could be confusing for users, so using
159 * a character replacement as following is often preferred.
160 * For example: Typing "test" shows "" (nothing).
161 *
162 * Alternative, you can supply a single character replacement character
163 * that will be echo'ed for each character in the text input. This could
164 * be a good idea for password prompts, where an asterisk character ("*")
165 * is often used to indicate typing activity and password length.
166 * For example: Typing "test" shows "****" (with asterisk replacement)
167 *
168 * Changing this setting will redraw the current prompt and echo the current
169 * input buffer according to the new setting.
170 *
171 * @param boolean|string $echo echo can be turned on (boolean true) or off (boolean true), or you can supply a single character replacement string
172 * @return self
173 * @uses self::redraw()
174 * @deprecated use Stdio::setEcho() instead
175 */
176 public function setEcho($echo)
177 {
178 if ($echo === $this->echo) {
179 return $this;
180 }
181
182 $this->echo = $echo;
183
184 // only redraw if there is any input
185 if ($this->linebuffer !== '') {
186 $this->redraw();
187 }
188
189 return $this;
190 }
191
192 /**
193 * whether or not to support moving cursor left and right
194 *
195 * switching cursor support moves the cursor to the end of the current
196 * input buffer (if any).
197 *
198 * @param boolean $move
199 * @return self
200 * @uses self::redraw()
201 * @deprecated use Stdio::setMove() instead
202 */
203 public function setMove($move)
204 {
205 $this->move = !!$move;
206
207 return $this->moveCursorTo($this->strlen($this->linebuffer));
208 }
209
210 /**
211 * Gets current cursor position measured in number of text characters.
212 *
213 * Note that the number of text characters doesn't necessarily reflect the
214 * number of monospace cells occupied by the text characters. If you want
215 * to know the latter, use `self::getCursorCell()` instead.
216 *
217 * @return int
218 * @see self::getCursorCell() to get the position measured in monospace cells
219 * @see self::moveCursorTo() to move the cursor to a given character position
220 * @see self::moveCursorBy() to move the cursor by given number of characters
221 * @see self::setMove() to toggle whether the user can move the cursor position
222 * @deprecated use Stdio::getCursorPosition() instead
223 */
224 public function getCursorPosition()
225 {
226 return $this->linepos;
227 }
228
229 /**
230 * Gets current cursor position measured in monospace cells.
231 *
232 * Note that the cell position doesn't necessarily reflect the number of
233 * text characters. If you want to know the latter, use
234 * `self::getCursorPosition()` instead.
235 *
236 * Most "normal" characters occupy a single monospace cell, i.e. the ASCII
237 * sequence for "A" requires a single cell, as do most UTF-8 sequences
238 * like "Ä".
239 *
240 * However, there are a number of code points that do not require a cell
241 * (i.e. invisible surrogates) or require two cells (e.g. some asian glyphs).
242 *
243 * Also note that this takes the echo mode into account, i.e. the cursor is
244 * always at position zero if echo is off. If using a custom echo character
245 * (like asterisk), it will take its width into account instead of the actual
246 * input characters.
247 *
248 * @return int
249 * @see self::getCursorPosition() to get current cursor position measured in characters
250 * @see self::moveCursorTo() to move the cursor to a given character position
251 * @see self::moveCursorBy() to move the cursor by given number of characters
252 * @see self::setMove() to toggle whether the user can move the cursor position
253 * @see self::setEcho()
254 * @deprecated use Stdio::getCursorCell() instead
255 */
256 public function getCursorCell()
257 {
258 if ($this->echo === false) {
259 return 0;
260 }
261 if ($this->echo !== true) {
262 return $this->strwidth($this->echo) * $this->linepos;
263 }
264 return $this->strwidth($this->substr($this->linebuffer, 0, $this->linepos));
265 }
266
267 /**
268 * Moves cursor to right by $n chars (or left if $n is negative).
269 *
270 * Zero value or values out of range (exceeding current input buffer) are
271 * simply ignored.
272 *
273 * Will redraw() the readline only if the visible cell position changes,
274 * see `self::getCursorCell()` for more details.
275 *
276 * @param int $n
277 * @return self
278 * @uses self::moveCursorTo()
279 * @uses self::redraw()
280 * @deprecated use Stdio::moveCursorBy() instead
281 */
282 public function moveCursorBy($n)
283 {
284 return $this->moveCursorTo($this->linepos + $n);
285 }
286
287 /**
288 * Moves cursor to given position in current line buffer.
289 *
290 * Values out of range (exceeding current input buffer) are simply ignored.
291 *
292 * Will redraw() the readline only if the visible cell position changes,
293 * see `self::getCursorCell()` for more details.
294 *
295 * @param int $n
296 * @return self
297 * @uses self::redraw()
298 * @deprecated use Stdio::moveCursorTo() instead
299 */
300 public function moveCursorTo($n)
301 {
302 if ($n < 0 || $n === $this->linepos || $n > $this->strlen($this->linebuffer)) {
303 return $this;
304 }
305
306 $old = $this->getCursorCell();
307 $this->linepos = $n;
308
309 // only redraw if visible cell position change (implies cursor is actually visible)
310 if ($this->getCursorCell() !== $old) {
311 $this->redraw();
312 }
313
314 return $this;
315 }
316
317 /**
318 * Appends the given input to the current text input buffer at the current position
319 *
320 * This moves the cursor accordingly to the number of characters added.
321 *
322 * @param string $input
323 * @return self
324 * @uses self::redraw()
325 * @deprecated use Stdio::addInput() instead
326 */
327 public function addInput($input)
328 {
329 if ($input === '') {
330 return $this;
331 }
332
333 // read everything up until before current position
334 $pre = $this->substr($this->linebuffer, 0, $this->linepos);
335 $post = $this->substr($this->linebuffer, $this->linepos);
336
337 $this->linebuffer = $pre . $input . $post;
338 $this->linepos += $this->strlen($input);
339
340 // only redraw if input should be echo'ed (i.e. is not hidden anyway)
341 if ($this->echo !== false) {
342 $this->redraw();
343 }
344
345 return $this;
346 }
347
348 /**
349 * set current text input buffer
350 *
351 * this moves the cursor to the end of the current
352 * input buffer (if any).
353 *
354 * @param string $input
355 * @return self
356 * @uses self::redraw()
357 * @deprecated use Stdio::setInput() instead
358 */
359 public function setInput($input)
360 {
361 if ($this->linebuffer === $input) {
362 return $this;
363 }
364
365 // remember old input length if echo replacement is used
366 $oldlen = (is_string($this->echo)) ? $this->strlen($this->linebuffer) : null;
367
368 $this->linebuffer = $input;
369 $this->linepos = $this->strlen($this->linebuffer);
370
371 // only redraw if input should be echo'ed (i.e. is not hidden anyway)
372 // and echo replacement is used, make sure the input length changes
373 if ($this->echo !== false && $this->linepos !== $oldlen) {
374 $this->redraw();
375 }
376
377 return $this;
378 }
379
380 /**
381 * get current text input buffer
382 *
383 * @return string
384 * @deprecated use Stdio::getInput() instead
385 */
386 public function getInput()
387 {
388 return $this->linebuffer;
389 }
390
391 /**
392 * Adds a new line to the (bottom position of the) history list
393 *
394 * @param string $line
395 * @return self
396 * @uses self::limitHistory() to make sure list does not exceed limits
397 * @deprecated use Stdio::addHistory() instead
398 */
399 public function addHistory($line)
400 {
401 $this->historyLines []= $line;
402
403 return $this->limitHistory($this->historyLimit);
404 }
405
406 /**
407 * Clears the complete history list
408 *
409 * @return self
410 * @deprecated use Stdio::clearHistory() instead
411 */
412 public function clearHistory()
413 {
414 $this->historyLines = array();
415 $this->historyPosition = null;
416
417 if ($this->historyUnsaved !== null) {
418 $this->setInput($this->historyUnsaved);
419 $this->historyUnsaved = null;
420 }
421
422 return $this;
423 }
424
425 /**
426 * Returns an array with all lines in the history
427 *
428 * @return string[]
429 * @deprecated use Stdio::listHistory() instead
430 */
431 public function listHistory()
432 {
433 return $this->historyLines;
434 }
435
436 /**
437 * Limits the history to a maximum of N entries and truncates the current history list accordingly
438 *
439 * @param int|null $limit
440 * @return self
441 * @deprecated use Stdio::limitHistory() instead
442 */
443 public function limitHistory($limit)
444 {
445 $this->historyLimit = $limit === null ? null : $limit;
446
447 // limit send and currently exceeded
448 if ($this->historyLimit !== null && isset($this->historyLines[$this->historyLimit])) {
449 // adjust position in history according to new position after applying limit
450 if ($this->historyPosition !== null) {
451 $this->historyPosition -= count($this->historyLines) - $this->historyLimit;
452
453 // current position will drop off from list => restore original
454 if ($this->historyPosition < 0) {
455 $this->setInput($this->historyUnsaved);
456 $this->historyPosition = null;
457 $this->historyUnsaved = null;
458 }
459 }
460
461 $this->historyLines = array_slice($this->historyLines, -$this->historyLimit, $this->historyLimit);
462 }
463
464 return $this;
465 }
466
467 /**
468 * set autocompletion handler to use
469 *
470 * The autocomplete handler will be called whenever the user hits the TAB
471 * key.
472 *
473 * @param callable|null $autocomplete
474 * @return self
475 * @throws \InvalidArgumentException if the given callable is invalid
476 * @deprecated use Stdio::setAutocomplete() instead
477 */
478 public function setAutocomplete($autocomplete)
479 {
480 if ($autocomplete !== null && !is_callable($autocomplete)) {
481 throw new \InvalidArgumentException('Invalid autocomplete function given');
482 }
483
484 $this->autocomplete = $autocomplete;
485
486 return $this;
487 }
488
489 /**
490 * Whether or not to emit a audible/visible BELL signal when using a disabled function
491 *
492 * By default, this class will emit a BELL signal when using a disable function,
493 * such as using the <kbd>left</kbd> or <kbd>backspace</kbd> keys when
494 * already at the beginning of the line.
495 *
496 * Whether or not the BELL is audible/visible depends on the termin and its
497 * settings, i.e. some terminals may "beep" or flash the screen or emit a
498 * short vibration.
499 *
500 * @param bool $bell
501 * @return void
502 * @internal use Stdio::setBell() instead
503 */
504 public function setBell($bell)
505 {
506 $this->bell = (bool)$bell;
507 }
508
509 /**
510 * redraw the current input prompt
511 *
512 * Usually, there should be no need to call this method manually. It will
513 * be invoked automatically whenever we detect the readline input needs to
514 * be (re)written to the output.
515 *
516 * Clear the current line and draw the input prompt. If input echo is
517 * enabled, will also draw the current input buffer and move to the current
518 * input buffer position.
519 *
520 * @return self
521 * @internal
522 */
523 public function redraw()
524 {
525 // Erase characters from cursor to end of line and then redraw actual input
526 $this->output->write("\r\033[K" . $this->getDrawString());
527
528 return $this;
529 }
530
531 /**
532 * Returns the string that is used to draw the input prompt
533 *
534 * @return string
535 * @internal
536 */
537 public function getDrawString()
538 {
539 $output = $this->prompt;
540 if ($this->echo !== false) {
541 if ($this->echo === true) {
542 $buffer = $this->linebuffer;
543 } else {
544 $buffer = str_repeat($this->echo, $this->strlen($this->linebuffer));
545 }
546
547 // write output, then move back $reverse chars (by sending backspace)
548 $output .= $buffer . str_repeat("\x08", $this->strwidth($buffer) - $this->getCursorCell());
549 }
550
551 return $output;
552 }
553
554 /** @internal */
555 public function onKeyBackspace()
556 {
557 // left delete only if not at the beginning
558 if ($this->linepos === 0) {
559 $this->bell();
560 } else {
561 $this->deleteChar($this->linepos - 1);
562 }
563 }
564
565 /** @internal */
566 public function onKeyDelete()
567 {
568 // right delete only if not at the end
569 if ($this->isEol()) {
570 $this->bell();
571 } else {
572 $this->deleteChar($this->linepos);
573 }
574 }
575
576 /** @internal */
577 public function onKeyHome()
578 {
579 if ($this->move && $this->linepos !== 0) {
580 $this->moveCursorTo(0);
581 } else {
582 $this->bell();
583 }
584 }
585
586 /** @internal */
587 public function onKeyEnd()
588 {
589 if ($this->move && !$this->isEol()) {
590 $this->moveCursorTo($this->strlen($this->linebuffer));
591 } else {
592 $this->bell();
593 }
594 }
595
596 /** @internal */
597 public function onKeyTab()
598 {
599 if ($this->autocomplete === null) {
600 $this->bell();
601 return;
602 }
603
604 // current word prefix and offset for start of word in input buffer
605 // "echo foo|bar world" will return just "foo" with word offset 5
606 $word = $this->substr($this->linebuffer, 0, $this->linepos);
607 $start = 0;
608 $end = $this->linepos;
609
610 // buffer prefix and postfix for everything that will *not* be matched
611 // above example will return "echo " and "bar world"
612 $prefix = '';
613 $postfix = $this->substr($this->linebuffer, $this->linepos);
614
615 // skip everything before last space
616 $pos = strrpos($word, ' ');
617 if ($pos !== false) {
618 $prefix = (string)substr($word, 0, $pos + 1);
619 $word = (string)substr($word, $pos + 1);
620 $start = $this->strlen($prefix);
621 }
622
623 // skip double quote (") or single quote (') from argument
624 $quote = null;
625 if (isset($word[0]) && ($word[0] === '"' || $word[0] === '\'')) {
626 $quote = $word[0];
627 ++$start;
628 $prefix .= $word[0];
629 $word = (string)substr($word, 1);
630 }
631
632 // invoke autocomplete callback
633 $words = call_user_func($this->autocomplete, $word, $start, $end);
634
635 // return early if autocomplete does not return anything
636 if ($words === null) {
637 return;
638 }
639
640 // remove from list of possible words that do not start with $word or are duplicates
641 $words = array_unique($words);
642 if ($word !== '' && $words) {
643 $words = array_filter($words, function ($w) use ($word) {
644 return strpos($w, $word) === 0;
645 });
646 }
647
648 // return if neither of the possible words match
649 if (!$words) {
650 $this->bell();
651 return;
652 }
653
654 // search longest common prefix among all possible matches
655 $found = reset($words);
656 $all = count($words);
657 if ($all > 1) {
658 while ($found !== '') {
659 // count all words that start with $found
660 $matches = count(array_filter($words, function ($w) use ($found) {
661 return strpos($w, $found) === 0;
662 }));
663
664 // ALL words match $found => common substring found
665 if ($all === $matches) {
666 break;
667 }
668
669 // remove last letter from $found and try again
670 $found = $this->substr($found, 0, -1);
671 }
672
673 // found more than one possible match with this prefix => print options
674 if ($found === $word || $found === '') {
675 // limit number of possible matches
676 if (count($words) > $this->autocompleteSuggestions) {
677 $more = count($words) - ($this->autocompleteSuggestions - 1);
678 $words = array_slice($words, 0, $this->autocompleteSuggestions - 1);
679 $words []= '(+' . $more . ' others)';
680 }
681
682 $this->output->write("\n" . implode(' ', $words) . "\n");
683 $this->redraw();
684
685 return;
686 }
687 }
688
689 if ($quote !== null && $all === 1 && (strpos($postfix, $quote) === false || strpos($postfix, $quote) > strpos($postfix, ' '))) {
690 // add closing quote if word started in quotes and postfix does not already contain closing quote before next space
691 $found .= $quote;
692 } elseif ($found === '') {
693 // add single quotes around empty match
694 $found = '\'\'';
695 }
696
697 if ($postfix === '' && $all === 1) {
698 // append single space after match unless there's a postfix or there are multiple completions
699 $found .= ' ';
700 }
701
702 // replace word in input with best match and adjust cursor
703 $this->linebuffer = $prefix . $found . $postfix;
704 $this->moveCursorBy($this->strlen($found) - $this->strlen($word));
705 }
706
707 /** @internal */
708 public function onKeyEnter()
709 {
710 if ($this->echo !== false) {
711 $this->output->write("\n");
712 }
713 $this->processLine("\n");
714 }
715
716 /** @internal */
717 public function onKeyLeft()
718 {
719 if ($this->move && $this->linepos !== 0) {
720 $this->moveCursorBy(-1);
721 } else {
722 $this->bell();
723 }
724 }
725
726 /** @internal */
727 public function onKeyRight()
728 {
729 if ($this->move && !$this->isEol()) {
730 $this->moveCursorBy(1);
731 } else {
732 $this->bell();
733 }
734 }
735
736 /** @internal */
737 public function onKeyUp()
738 {
739 // ignore if already at top or history is empty
740 if ($this->historyPosition === 0 || !$this->historyLines) {
741 $this->bell();
742 return;
743 }
744
745 if ($this->historyPosition === null) {
746 // first time up => move to last entry
747 $this->historyPosition = count($this->historyLines) - 1;
748 $this->historyUnsaved = $this->getInput();
749 } else {
750 // somewhere in the list => move by one
751 $this->historyPosition--;
752 }
753
754 $this->setInput($this->historyLines[$this->historyPosition]);
755 }
756
757 /** @internal */
758 public function onKeyDown()
759 {
760 // ignore if not currently cycling through history
761 if ($this->historyPosition === null) {
762 $this->bell();
763 return;
764 }
765
766 if (isset($this->historyLines[$this->historyPosition + 1])) {
767 // this is still a valid position => advance by one and apply
768 $this->historyPosition++;
769 $this->setInput($this->historyLines[$this->historyPosition]);
770 } else {
771 // moved beyond bottom => restore original unsaved input
772 $this->setInput($this->historyUnsaved);
773 $this->historyPosition = null;
774 $this->historyUnsaved = null;
775 }
776 }
777
778 /**
779 * Will be invoked for character(s) that could not otherwise be processed by the sequencer
780 *
781 * @internal
782 */
783 public function onFallback($chars, EventEmitterInterface $base = null)
784 {
785 // check if there's any special key binding for any of the chars
786 $buffer = '';
787 foreach ($this->strsplit($chars) as $char) {
788 // forward compatibility: check if any key binding exists on base Stdio instance
789 // deprecated: check if any key binding exists on this Readline instance
790 $emit = null;
791 if ($base !== null && $base->listeners($char)) {
792 $emit = $base;
793 } else if ($this->listeners($char)) {
794 $emit = $this;
795 }
796
797 if ($emit !== null) {
798 // special key binding for this character found
799 // process all characters before this one before invoking function
800 if ($buffer !== '') {
801 $this->addInput($buffer);
802 $buffer = '';
803 }
804 $emit->emit($char, array($char));
805 } else {
806 $buffer .= $char;
807 }
808 }
809
810 // process remaining input characters after last special key binding
811 if ($buffer !== '') {
812 $this->addInput($buffer);
813 }
814 }
815
816 /**
817 * delete a character at the given position
818 *
819 * Removing a character left to the current cursor will also move the cursor
820 * to the left.
821 *
822 * @param int $n
823 */
824 private function deleteChar($n)
825 {
826 // read everything up until before current position
827 $pre = $this->substr($this->linebuffer, 0, $n);
828 $post = $this->substr($this->linebuffer, $n + 1);
829
830 $this->linebuffer = $pre . $post;
831
832 // move cursor one cell to the left if we're deleting in front of the cursor
833 if ($n < $this->linepos) {
834 --$this->linepos;
835 }
836
837 $this->redraw();
838 }
839
840 /**
841 * process the current line buffer, emit event and redraw empty line
842 *
843 * @uses self::setInput()
844 */
845 protected function processLine($eol)
846 {
847 // reset history cycle position
848 $this->historyPosition = null;
849 $this->historyUnsaved = null;
850
851 // store and reset/clear/redraw current input
852 $line = $this->linebuffer;
853 if ($line !== '') {
854 // the line is not empty, reset it (and implicitly redraw prompt)
855 $this->setInput('');
856 } elseif ($this->echo !== false) {
857 // explicitly redraw prompt after empty line
858 $this->redraw();
859 }
860
861 // process stored input buffer
862 $this->emit('data', array($line . $eol));
863 }
864
865 /**
866 * @param string $str
867 * @return int
868 * @codeCoverageIgnore
869 */
870 private function strlen($str)
871 {
872 // prefer mb_strlen() if available
873 if (function_exists('mb_strlen')) {
874 return mb_strlen($str, $this->encoding);
875 }
876
877 // otherwise replace all unicode chars with dots and count dots
878 return strlen(preg_replace('/./us', '.', $str));
879 }
880
881 /**
882 * @param string $str
883 * @param int $start
884 * @param ?int $len
885 * @return string
886 * @codeCoverageIgnore
887 */
888 private function substr($str, $start = 0, $len = null)
889 {
890 if ($len === null) {
891 $len = $this->strlen($str) - $start;
892 }
893
894 // prefer mb_substr() if available
895 if (function_exists('mb_substr')) {
896 return (string)mb_substr($str, $start, $len, $this->encoding);
897 }
898
899 // otherwise build array with all unicode chars and slice array
900 preg_match_all('/./us', $str, $matches);
901
902 return implode('', array_slice($matches[0], $start, $len));
903 }
904
905 /**
906 * @internal
907 * @param string $str
908 * @return int
909 * @codeCoverageIgnore
910 */
911 public function strwidth($str)
912 {
913 // prefer mb_strwidth() if available
914 if (function_exists('mb_strwidth')) {
915 return mb_strwidth($str, $this->encoding);
916 }
917
918 // otherwise replace each double-width unicode graphemes with two dots, all others with single dot and count number of dots
919 // mbstring's list of double-width graphemes is *very* long: https://3v4l.org/GEg3u
920 // let's use symfony's list from https://github.com/symfony/polyfill-mbstring/blob/e79d363049d1c2128f133a2667e4f4190904f7f4/Mbstring.php#L523
921 // which looks like they originally came from http://www.cl.cam.ac.uk/~mgk25/ucs/wcwidth.c
922 return strlen(preg_replace(
923 array(
924 '/[\x{1100}-\x{115F}\x{2329}\x{232A}\x{2E80}-\x{303E}\x{3040}-\x{A4CF}\x{AC00}-\x{D7A3}\x{F900}-\x{FAFF}\x{FE10}-\x{FE19}\x{FE30}-\x{FE6F}\x{FF00}-\x{FF60}\x{FFE0}-\x{FFE6}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}]/u',
925 '/./us',
926 ),
927 array(
928 '..',
929 '.',
930 ),
931 $str
932 ));
933 }
934
935 /**
936 * @param string $str
937 * @return string[]
938 */
939 private function strsplit($str)
940 {
941 return preg_split('//u', $str, null, PREG_SPLIT_NO_EMPTY);
942 }
943
944 /**
945 * @return bool
946 */
947 private function isEol()
948 {
949 return $this->linepos === $this->strlen($this->linebuffer);
950 }
951
952 /**
953 * @return void
954 */
955 private function bell()
956 {
957 if ($this->bell) {
958 $this->output->write("\x07"); // BEL a.k.a. \a
959 }
960 }
961
962 /** @internal */
963 public function handleEnd()
964 {
965 if ($this->linebuffer !== '') {
966 $this->processLine('');
967 }
968
969 if (!$this->closed) {
970 $this->emit('end');
971 $this->close();
972 }
973 }
974
975 /** @internal */
976 public function handleError(\Exception $error)
977 {
978 $this->emit('error', array($error));
979 $this->close();
980 }
981
982 public function isReadable()
983 {
984 return !$this->closed && $this->input->isReadable();
985 }
986
987 public function pause()
988 {
989 $this->input->pause();
990 }
991
992 public function resume()
993 {
994 $this->input->resume();
995 }
996
997 public function pipe(WritableStreamInterface $dest, array $options = array())
998 {
999 Util::pipe($this, $dest, $options);
1000
1001 return $dest;
1002 }
1003
1004 public function close()
1005 {
1006 if ($this->closed) {
1007 return;
1008 }
1009
1010 $this->closed = true;
1011
1012 $this->input->close();
1013
1014 $this->emit('close');
1015 $this->removeAllListeners();
1016 }
1017 }