Socket   A
last analyzed

Complexity

Total Complexity 18

Size/Duplication

Total Lines 179
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 90.28%

Importance

Changes 0
Metric Value
wmc 18
lcom 1
cbo 6
dl 0
loc 179
ccs 65
cts 72
cp 0.9028
rs 10
c 0
b 0
f 0

10 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A factory() 0 7 1
A receive() 0 18 3
A reconnectTls() 0 22 3
A send() 0 15 3
A connect() 0 13 2
A disconnect() 0 10 2
A getAddress() 0 4 1
A getSocket() 0 4 1
A setSocket() 0 5 1
1
<?php
2
3
/**
4
 * Copyright 2014 Fabian Grutschus. All rights reserved.
5
 *
6
 * Redistribution and use in source and binary forms, with or without modification,
7
 * are permitted provided that the following conditions are met:
8
 *
9
 * 1. Redistributions of source code must retain the above copyright notice, this
10
 *   list of conditions and the following disclaimer.
11
 *
12
 * 2. Redistributions in binary form must reproduce the above copyright notice,
13
 *   this list of conditions and the following disclaimer in the documentation
14
 *   and/or other materials provided with the distribution.
15
 *
16
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
17
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
20
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26
 *
27
 * The views and conclusions contained in the software and documentation are those
28
 * of the authors and should not be interpreted as representing official policies,
29
 * either expressed or implied, of the copyright holders.
30
 *
31
 * @author    Fabian Grutschus <[email protected]>
32
 * @copyright 2014 Fabian Grutschus. All rights reserved.
33
 * @license   BSD
34
 * @link      http://github.com/fabiang/xmpp
35
 */
36
37
namespace Fabiang\Xmpp\Connection;
38
39
use Psr\Log\LogLevel;
40
use Fabiang\Xmpp\Stream\SocketClient;
41
use Fabiang\Xmpp\Util\XML;
42
use Fabiang\Xmpp\Options;
43
use Fabiang\Xmpp\Exception\TimeoutException;
44
45
/**
46
 * Connection to a socket stream.
47
 *
48
 * @package Xmpp\Connection
49
 */
50
class Socket extends AbstractConnection implements SocketConnectionInterface
51
{
52
53
    const DEFAULT_LENGTH = 4096;
54
    const STREAM_START   = <<<'XML'
55
<?xml version="1.0" encoding="UTF-8"?>
56
<stream:stream to="%s" xmlns:stream="http://etherx.jabber.org/streams" xmlns="jabber:client" version="1.0">
57
XML;
58
    const STREAM_END     = '</stream:stream>';
59
60
    /**
61
     * Socket.
62
     *
63
     * @var SocketClient
64
     */
65
    protected $socket;
66
67
    /**
68
     * Did we received any data yet?
69
     *
70
     * @var bool
71
     */
72
    private $receivedAnyData = false;
73
74
    /**
75
     * Constructor set default socket instance if no socket was given.
76
     *
77
     * @param StreamSocket $socket  Socket instance
78
     */
79 3
    public function __construct(SocketClient $socket)
80
    {
81 3
        $this->setSocket($socket);
82 3
    }
83
84
    /**
85
     * Factory for connection class.
86
     *
87
     * @param Options $options Options object
88
     * @return static
89
     */
90
    public static function factory(Options $options)
91
    {
92
        $socket = new SocketClient($options->getAddress(), $options->getContextOptions());
93
        $object = new static($socket);
94
        $object->setOptions($options);
95
        return $object;
96
    }
97
98
    /**
99
     * {@inheritDoc}
100
     */
101 6
    public function receive()
102
    {
103 6
        $buffer = $this->getSocket()->read(static::DEFAULT_LENGTH);
104
105 6
        if ($buffer) {
106 3
            $this->receivedAnyData = true;
107 3
            $address = $this->getAddress();
108 3
            $this->log("Received buffer '$buffer' from '{$address}'", LogLevel::DEBUG);
109 3
            $this->getInputStream()->parse($buffer);
110 3
            return $buffer;
111
        }
112
113
        try {
114 3
            $this->checkTimeout($buffer);
115 3
        } catch (TimeoutException $exception) {
116 3
            $this->reconnectTls($exception);
117
        }
118 3
    }
119
120
    /**
121
     * Try to reconnect via TLS.
122
     *
123
     * @param TimeoutException $exception
124
     * @return null
125
     * @throws TimeoutException
126
     */
127 3
    private function reconnectTls(TimeoutException $exception)
128
    {
129
        // check if we didn't receive any data
130
        // if not we re-try to connect via TLS
131 3
        if (false === $this->receivedAnyData) {
132 3
            $matches = [];
133 3
            $previousAddress = $this->getOptions()->getAddress();
134
            // only reconnect via tls if we've used tcp before.
135 3
            if (preg_match('#tcp://(?<address>.+)#', $previousAddress, $matches)) {
136 3
                $this->log('Connecting via TCP failed, now trying to connect via TLS');
137
138 3
                $address = 'tls://' . $matches['address'];
139 3
                $this->connected = false;
140 3
                $this->getOptions()->setAddress($address);
141 3
                $this->getSocket()->reconnect($address);
142 3
                $this->connect();
143 3
                return;
144
            }
145 3
        }
146
147 3
        throw $exception;
148
    }
149
150
    /**
151
     * {@inheritDoc}
152
     */
153 3
    public function send($buffer)
154
    {
155 3
        if (false === $this->isConnected()) {
156 3
            $this->connect();
157 3
        }
158
159 3
        $address = $this->getAddress();
160 3
        $this->log("Sending data '$buffer' to '{$address}'", LogLevel::DEBUG);
161 3
        $this->getSocket()->write($buffer);
162 3
        $this->getOutputStream()->parse($buffer);
163
164 3
        while ($this->checkBlockingListeners()) {
165
            $this->receive();
166
        }
167 3
    }
168
169
    /**
170
     * {@inheritDoc}
171
     */
172 3
    public function connect()
173
    {
174 3
        if (false === $this->connected) {
175 3
            $address = $this->getAddress();
176 3
            $this->getSocket()->connect($this->getOptions()->getTimeout());
177 3
            $this->getSocket()->setBlocking(true);
178
179 3
            $this->connected = true;
180 3
            $this->log("Connected to '{$address}'", LogLevel::DEBUG);
181 3
        }
182
183 3
        $this->send(sprintf(static::STREAM_START, XML::quote($this->getOptions()->getTo())));
184 3
    }
185
186
    /**
187
     * {@inheritDoc}
188
     */
189 3
    public function disconnect()
190
    {
191 3
        if (true === $this->connected) {
192 3
            $address         = $this->getAddress();
193 3
            $this->send(static::STREAM_END);
194 3
            $this->getSocket()->close();
195 3
            $this->connected = false;
196 3
            $this->log("Disconnected from '{$address}'", LogLevel::DEBUG);
197 3
        }
198 3
    }
199
200
    /**
201
     * Get address from options object.
202
     *
203
     * @return string
204
     */
205 3
    protected function getAddress()
206
    {
207 3
        return $this->getOptions()->getAddress();
208
    }
209
210
    /**
211
     * Return socket instance.
212
     *
213
     * @return SocketClient
214
     */
215 3
    public function getSocket()
216
    {
217 3
        return $this->socket;
218
    }
219
220
    /**
221
     * {@inheritDoc}
222
     */
223 3
    public function setSocket(SocketClient $socket)
224
    {
225 3
        $this->socket = $socket;
226 3
        return $this;
227
    }
228
}
229