Completed
Push — master ( 939cef...4aee11 )
by Kacper
03:59
created

PingKeepAlive::setClient()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 6
cc 1
eloc 3
nc 1
nop 1
rs 9.4285
1
<?php
2
/**
3
 * Nucleus - XMPP Library for PHP
4
 *
5
 * Copyright (C) 2016, Some rights reserved.
6
 *
7
 * @author Kacper "Kadet" Donat <[email protected]>
8
 *
9
 * Contact with author:
10
 * Xmpp: [email protected]
11
 * E-mail: [email protected]
12
 *
13
 * From Kadet with love.
14
 */
15
16
namespace Kadet\Xmpp\Component;
17
18
19
use Kadet\Xmpp\Stanza\Iq;
20
use Kadet\Xmpp\XmppClient;
21
22
class PingKeepAlive extends Component
23
{
24
    /** @var float|int */
25
    private $_interval = 15;
26
    private $_timer;
27
28
    /**
29
     * PingKeepAlive constructor.
30
     *
31
     * @param float $interval Keep alive interval in seconds
32
     */
33
    public function __construct($interval = 15.)
34
    {
35
        $this->_interval = $interval;
36
    }
37
38
    public function setClient(XmppClient $client)
39
    {
40
        parent::setClient($client);
41
42
        $this->_client->on('state', [$this, 'enable'], \Kadet\Xmpp\Utils\filter\equals('ready'));
43
    }
44
45
    /**
46
     * Starts keep alive timer
47
     */
48
    public function enable()
49
    {
50
        $this->_timer = $this->_client->connector->getLoop()->addPeriodicTimer($this->_interval, function() {
51
            $this->keepAlive();
52
        });
53
    }
54
55
    /**
56
     * Stops keep alive timer
57
     */
58
    public function disable()
59
    {
60
        $this->_client->connector->getLoop()->cancelTimer($this->_timer);
61
    }
62
63
    private function keepAlive()
64
    {
65
        $ping = new Iq(['type' => 'get', 'query' => new Iq\Query('urn:xmpp:ping', 'ping')]);
66
67
        $this->_client->write($ping);
68
    }
69
}
70