Completed
Push — master ( 4a3a64...3709b8 )
by Peter
02:25
created

Auth   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 70
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 5
Bugs 0 Features 0
Metric Value
wmc 9
c 5
b 0
f 0
lcom 1
cbo 1
dl 0
loc 70
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 2
A init() 0 9 3
A login() 0 13 1
A keepAlive() 0 9 1
A logout() 0 11 1
A sessionRemaining() 0 4 1
1
<?php
2
3
namespace PeterColes\Betfair\Api;
4
5
use PeterColes\Betfair\Http\Client as HttpClient;
6
7
class Auth
8
{
9
    const ENDPOINT = 'https://identitysso.betfair.com/api/';
10
11
    const SESSION_LENGTH = 4 * 60 * 60; // 4 hours
12
13
    protected $httpClient;
14
15
    public static $appKey = null;
16
17
    public static $sessionToken = null;
18
19
    public static $lastLogin = null;
20
21
    public function __construct(HttpClient $httpClient = null)
22
    {
23
        $this->httpClient = $httpClient ?: new HttpClient;
24
    }
25
26
    public function init($appKey, $username, $password)
27
    {
28
        if ($appKey == self::$appKey && $this->sessionRemaining() > 5) {
29
            $this->keepAlive();
30
        } else {
31
            self::$appKey = $appKey;
32
            self::$sessionToken = $this->login($appKey, $username, $password);
33
        }
34
    }
35
36
    public function login($appKey, $username, $password)
37
    {
38
        $result = $this->httpClient
39
            ->setMethod('post')
40
            ->setEndPoint(self::ENDPOINT.'login/')
41
            ->authHeaders([ 'X-Application' => $appKey ])
42
            ->setFormData([ 'username' => $username, 'password' => $password ])
43
            ->send();
44
45
        self::$lastLogin = time();
46
47
        return $result->token;
48
    }
49
50
    public function keepAlive()
51
    {
52
        $this->httpClient
53
            ->setEndPoint(self::ENDPOINT.'keepAlive/')
54
            ->authHeaders()
55
            ->send();
56
57
        self::$lastLogin = time();
58
    }
59
60
    public function logout()
61
    {
62
        $this->httpClient
63
            ->setEndPoint(self::ENDPOINT.'logout/')
64
            ->authHeaders()
65
            ->send();
66
67
        self::$appKey = null;
68
        self::$sessionToken = null;
69
        self::$lastLogin = null;
70
    }
71
72
    public function sessionRemaining()
73
    {
74
        return self::$lastLogin + self::SESSION_LENGTH - time();
75
    }
76
}
77