PromptMatcher   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 68
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 0
dl 0
loc 68
ccs 22
cts 22
cp 1
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A isMatch() 0 32 4
A getMatches() 0 4 1
A getResponseText() 0 4 1
1
<?php
2
3
/**
4
 * This file is part of graze/telnet-client.
5
 *
6
 * Copyright (c) 2016 Nature Delivered Ltd. <https://www.graze.com>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 *
11
 * @license https://github.com/graze/telnet-client/blob/master/LICENSE
12
 * @link https://github.com/graze/telnet-client
13
 */
14
15
namespace Graze\TelnetClient;
16
17
class PromptMatcher implements PromptMatcherInterface
18
{
19
    /**
20
     * @var array
21
     */
22
    protected $matches = [];
23
24
    /**
25
     * @var string
26
     */
27
    protected $responseText = '';
28
29
    /**
30
     * @param string $prompt
31
     * @param string $subject
32
     * @param string $lineEnding
33
     *
34
     * @return bool
35
     */
36 18
    public function isMatch($prompt, $subject, $lineEnding = null)
37
    {
38
        // cheap line ending check before expensive regex
39 18
        if (!is_null($lineEnding) && substr($subject, -1 * strlen($lineEnding)) != $lineEnding) {
40 15
            return false;
41
        }
42
43 17
        $matches = [];
44
        $callback = function ($matchesCallback) use (&$matches) {
45 16
            $matches = $matchesCallback;
46
            // replace matches with an empty string (remove prompt from $subject)
47 16
            return '';
48 17
        };
49 17
        $pattern = sprintf('/%s%s$/', $prompt, $lineEnding);
50
51 17
        $responseText = preg_replace_callback($pattern, $callback, $subject);
52
53 17
        if (empty($matches)) {
54 15
            return false;
55
        }
56
57
        // trim line endings
58 16
        $trimmable = [&$matches, &$responseText];
59 16
        array_walk_recursive($trimmable, function (&$trimee) use ($lineEnding) {
60 16
            $trimee = trim($trimee, $lineEnding);
61 16
        });
62
63 16
        $this->matches = $matches;
64 16
        $this->responseText = $responseText;
65
66 16
        return true;
67
    }
68
69
    /**
70
     * @return array
71
     */
72 16
    public function getMatches()
73
    {
74 16
        return $this->matches;
75
    }
76
77
    /**
78
     * @return string
79
     */
80 16
    public function getResponseText()
81
    {
82 16
        return $this->responseText;
83
    }
84
}
85