Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 90 additions & 0 deletions system/CLI/KeyReader.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
<?php

declare(strict_types=1);

/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/

namespace CodeIgniter\CLI;

/**
* Reader of single keypresses from a stream.
*
* @internal
*/
final class KeyReader
{
private const KEY_PATTERN = '/\e\[[0-9;]*[A-Za-z~]|\eO[A-Z]|./s';

private string $savedMode = '';

/**
* @param resource $stream
* @param bool $raw Whether to switch the terminal to raw mode while open
*/
public function __construct(
private readonly mixed $stream,
private readonly bool $raw,
) {
}

/**
* Returns `false` when raw mode was wanted but the terminal settings could not be read.
*/
public function open(): bool
{
if (! $this->raw) {
return true;
}

// @codeCoverageIgnoreStart
$this->savedMode = trim((string) shell_exec('stty -g < /dev/tty 2>/dev/null'));

if ($this->savedMode === '') {
return false;
}

// Signals stay off so Ctrl+C arrives as a key, letting the terminal be restored before the process ends.
shell_exec('stty -icanon -isig -echo < /dev/tty 2>/dev/null');

return true;
// @codeCoverageIgnoreEnd
}

public function close(): void
{
if ($this->savedMode === '') {
return;
}

// @codeCoverageIgnoreStart
shell_exec(sprintf('stty %s < /dev/tty 2>/dev/null', escapeshellarg($this->savedMode)));

$this->savedMode = '';
// @codeCoverageIgnoreEnd
}

/**
* Returns the keys of the next read, or an empty list at the end of the stream.
*
* @return list<string>
*/
public function read(): array
{
$bytes = fread($this->stream, 16);

if ($bytes === false || $bytes === '') {
return [];
}

preg_match_all(self::KEY_PATTERN, $bytes, $matches);

return $matches[0];
}
}
Loading
Loading