TelnetPromptMatcher::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Graze\WipotecCheckweigherClient;
4
5
use Graze\TelnetClient\PromptMatcherInterface;
6
use DomainException;
7
8
class TelnetPromptMatcher implements PromptMatcherInterface
9
{
10
    /** @var string[] */
11
    protected $matches = [];
12
13
    /** @var string */
14
    protected $responseText = '';
15
16
    /** @var string */
17
    protected $promptError;
18
19
    /**
20
     * @param string $promptError
21
     */
22 6
    public function __construct($promptError)
23
    {
24 6
        $this->promptError = $promptError;
25 6
    }
26
27
    /**
28
     * @param string $prompt
29
     * @param string $subject
30
     * @param string $lineEnding
31
     * @return bool
32
     */
33 5
    public function isMatch($prompt, $subject, $lineEnding = null)
34
    {
35 5
        $responseEnding = "</cw:response>\r\n";
36
37
        // Cheap ending check before expensive regex
38 5
        if (substr($subject, -1 * strlen($responseEnding)) != $responseEnding) {
39
            return false;
40
        }
41
42 5
        if (!preg_match("/^\r\n<\(len\)>\d{7}<\/\(len\)>\r\n(.*)$/s", $subject, $match)) {
43 1
            throw new DomainException('Response is invalid, could not find header');
44
        }
45
46 4
        $responseText = $match[1];
47
48
        // The prompt type determines whether an error is expected or not.
49 4
        if ($prompt == $this->promptError xor false !== strpos($responseText, '<cw:error_info>')) {
50 2
            return false;
51
        }
52
53 2
        $this->responseText = $responseText;
54 2
        return true;
55
    }
56
57
    /**
58
     * @return string[]
59
     */
60
    public function getMatches()
61
    {
62
        return $this->matches;
63
    }
64
65
    /**
66
     * @return string
67
     */
68
    public function getResponseText()
69
    {
70
        return $this->responseText;
71
    }
72
}
73