Completed
Push — master ( 021a9d...7befbe )
by Burhan
10:40 queued 03:14
created

TelnetClient::connect()   A

Complexity

Conditions 5
Paths 16

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 5.0073

Importance

Changes 0
Metric Value
dl 0
loc 22
ccs 14
cts 15
cp 0.9333
rs 9.2568
c 0
b 0
f 0
cc 5
nc 16
nop 5
crap 5.0073
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
use Exception;
18
use Graze\TelnetClient\Exception\TelnetException;
19
use Graze\TelnetClient\Exception\TelnetExceptionInterface;
20
use Socket\Raw\Factory as SocketFactory;
21
use Socket\Raw\Socket;
22
23
class TelnetClient implements TelnetClientInterface
24
{
25
    /**
26
     * @var SocketFactory
27
     */
28
    protected $socketFactory;
29
30
    /**
31
     * @var PromptMatcherInterface
32
     */
33
    protected $promptMatcher;
34
35
    /**
36
     * @var InterpretAsCommand
37
     */
38
    protected $interpretAsCommand;
39
40
    /**
41
     * @var string
42
     */
43
    protected $prompt = '\$';
44
45
    /**
46
     * @var string
47
     */
48
    protected $promptError = 'ERROR';
49
50
    /**
51
     * @var string
52
     */
53
    protected $lineEnding = "\n";
54
55
    /**
56
     * @var Socket
57
     */
58
    protected $socket;
59
60
    /**
61
     * @var string
62
     */
63
    protected $buffer;
64
65
    /**
66
     * @var string
67
     */
68
    protected $NULL;
69
70
    /**
71
     * @var string
72
     */
73
    protected $DC1;
74
75
    /**
76
     * @var string
77
     */
78
    protected $IAC;
79
80
    /**
81
     * @param SocketFactory $socketFactory
82
     * @param PromptMatcherInterface $promptMatcher
83
     * @param InterpretAsCommand $interpretAsCommand
84
     */
85 18
    public function __construct(
86
        SocketFactory $socketFactory,
87
        PromptMatcherInterface $promptMatcher,
88
        InterpretAsCommand $interpretAsCommand
89
    ) {
90 18
        $this->socketFactory = $socketFactory;
91 18
        $this->promptMatcher = $promptMatcher;
92 18
        $this->interpretAsCommand = $interpretAsCommand;
93
94 18
        $this->NULL = chr(0);
95 18
        $this->DC1 = chr(17);
96 18
    }
97
98
    /**
99
     * @param string $dsn
100
     * @param string $prompt
101
     * @param string $promptError
102
     * @param string $lineEnding
103
     * @param float|null $timeout
104
     *
105
     * @throws TelnetExceptionInterface
106
     */
107 17
    public function connect($dsn, $prompt = null, $promptError = null, $lineEnding = null, $timeout = null)
108
    {
109 17
        if ($prompt !== null) {
110 4
            $this->setPrompt($prompt);
111 4
        }
112
113 17
        if ($promptError !== null) {
114 3
            $this->setPromptError($promptError);
115 3
        }
116
117 17
        if ($lineEnding !== null) {
118 16
            $this->setLineEnding($lineEnding);
119 16
        }
120
121
        try {
122 17
            $socket = $this->socketFactory->createClient($dsn, $timeout);
123 17
        } catch (Exception $e) {
124
            throw new TelnetException(sprintf('unable to create socket connection to [%s]', $dsn), 0, $e);
125
        }
126
127 17
        $this->setSocket($socket);
128 17
    }
129
130
    /**
131
     * @param string $prompt
132
     */
133 2
    public function setPrompt($prompt)
134
    {
135 2
        $this->prompt = $prompt;
136 2
    }
137
138
    /**
139
     * @param string $promptError
140
     */
141 1
    public function setPromptError($promptError)
142
    {
143 1
        $this->promptError = $promptError;
144 1
    }
145
146
    /**
147
     * @param string $lineEnding
148
     */
149 14
    public function setLineEnding($lineEnding)
150
    {
151 14
        $this->lineEnding = $lineEnding;
152 14
    }
153
154
    /**
155
     * @param Socket $socket
156
     */
157 16
    public function setSocket(Socket $socket)
158
    {
159 16
        $this->socket = $socket;
160 16
    }
161
162
    /**
163
     * @return Socket
164
     */
165
    public function getSocket()
166
    {
167
        return $this->socket;
168
    }
169
170
    /**
171
     * @param string $command
172
     * @param string $prompt
173
     * @param string $promptError
174
     *
175
     * @return TelnetResponseInterface
176
     */
177 17
    public function execute($command, $prompt = null, $promptError = null)
178
    {
179 17
        if (!$this->socket) {
180 1
            throw new TelnetException('attempt to execute without a connection - call connect first');
181
        }
182
183 16
        $this->write($command);
184 15
        return $this->getResponse($prompt, $promptError);
185
    }
186
187
    /**
188
     * @param string $command
189
     *
190
     * @return void
191
     * @throws TelnetExceptionInterface
192
     */
193 16
    protected function write($command)
194
    {
195
        try {
196 16
            $this->socket->write($command . $this->lineEnding);
197 16
        } catch (Exception $e) {
198 1
            throw new TelnetException(sprintf('failed writing to socket [%s]', $command), 0, $e);
199
        }
200 15
    }
201
202
    /**
203
     * @param string $prompt
204
     * @param string $promptError
205
     *
206
     * @return TelnetResponseInterface
207
     * @throws TelnetExceptionInterface
208
     */
209 15
    protected function getResponse($prompt = null, $promptError = null)
210
    {
211 15
        $isError = false;
212 15
        $buffer = '';
213
        do {
214
            // process one character at a time
215
            try {
216 15
                $character = $this->socket->read(1);
217 15
            } catch (Exception $e) {
218 1
                throw new TelnetException('failed reading from socket', 0, $e);
219
            }
220
221 14
            if (in_array($character, [$this->NULL, $this->DC1])) {
222
                break;
223
            }
224
225 14
            if ($this->interpretAsCommand->interpret($character, $this->socket)) {
226
                continue;
227
            }
228
229 14
            $buffer .= $character;
230
231
            // check for prompt
232 14
            if ($this->promptMatcher->isMatch($prompt ?: $this->prompt, $buffer, $this->lineEnding)) {
233 8
                break;
234
            }
235
236
            // check for error prompt
237 14
            if ($this->promptMatcher->isMatch($promptError ?: $this->promptError, $buffer, $this->lineEnding)) {
238 6
                $isError = true;
239 6
                break;
240
            }
241 14
        } while (true);
242
243 14
        return new TelnetResponse(
244 14
            $isError,
245 14
            $this->promptMatcher->getResponseText(),
246 14
            $this->promptMatcher->getMatches()
247 14
        );
248
    }
249
250
    /**
251
     * @return TelnetClientInterface
252
     */
253 1
    public static function factory()
254
    {
255 1
        return new static(
256 1
            new SocketFactory(),
257 1
            new PromptMatcher(),
258 1
            new InterpretAsCommand()
259 1
        );
260
    }
261
262 15
    public function __destruct()
263
    {
264 15
        if (!$this->socket) {
265 1
            return;
266
        }
267
268 14
        $this->socket->close();
269 14
    }
270
}
271