Passed
Pull Request — master (#9)
by Shinji
02:56
created

KeyboardCancelMiddleware   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 23
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 13
dl 0
loc 23
rs 10
c 0
b 0
f 0
wmc 3

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
A invoke() 0 7 2
1
<?php
2
3
/**
4
 * This file is part of the sj-i/php-profiler package.
5
 *
6
 * (c) sji <[email protected]>
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
declare(strict_types=1);
13
14
namespace PhpProfiler\Lib\Loop\LoopMiddleware;
15
16
use PhpProfiler\Lib\Loop\LoopMiddlewareInterface;
17
18
final class KeyboardCancelMiddleware implements LoopMiddlewareInterface
19
{
20
    private LoopMiddlewareInterface $chain;
21
    private string $cancel_key;
22
    /** @var resource */
23
    private $keyboard_input;
24
25
    public function __construct(string $cancel_key, LoopMiddlewareInterface $chain)
26
    {
27
        $this->chain = $chain;
28
        exec('stty -icanon -echo');
29
        $this->keyboard_input = fopen('php://stdin', 'r');
30
        stream_set_blocking($this->keyboard_input, false);
31
        $this->cancel_key = $cancel_key;
32
    }
33
34
    public function invoke(): bool
35
    {
36
        $key = fread($this->keyboard_input, 1);
37
        if ($key === $this->cancel_key) {
38
            return false;
39
        }
40
        return $this->chain->invoke();
41
    }
42
}
43