-
Notifications
You must be signed in to change notification settings - Fork 0
/
AbstractClient.php
99 lines (86 loc) · 2.31 KB
/
AbstractClient.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
<?php
namespace Causal\F2GC;
abstract class AbstractClient
{
/**
* @var string
*/
protected $username;
/**
* @var string
*/
protected $password;
/**
* @var string
*/
protected $userAgent;
/**
* @var string
*/
protected $cookiePath;
/**
* @var string
*/
protected $token;
/**
* FitbitClient constructor.
*
* @param string $username
* @param string $password
*/
public function __construct(string $username, string $password)
{
$this->username = $username;
$this->password = $password;
$this->userAgent = sprintf('Mozilla/5.0 (%s %s %s) ' . str_replace('\\', '-', get_class($this)), php_uname('s'), php_uname('r'), php_uname('m'));
$this->cookiePath = sys_get_temp_dir();
$this->token = $this->getTokenFromCookie();
}
public abstract function connect() : bool;
public function disconnect() : bool
{
$cookieFileName = $this->getCookieFileName();
if (file_exists($cookieFileName)) {
return unlink($cookieFileName);
}
return false;
}
protected abstract function getTokenFromCookie() : ?string;
/**
* Returns the available cookies.
*
* @return array
*/
protected function getCookies(): array
{
$cookies = [];
$cookieFileName = $this->getCookieFileName();
if (!file_exists($cookieFileName)) {
return $cookies;
}
$contents = file_get_contents($cookieFileName);
$lines = explode("\n", $contents);
foreach ($lines as $line) {
if (empty($line) || $line{0} === '#') {
continue;
}
$data = explode("\t", $line);
$cookie = array_combine(
/** @see http://www.cookiecentral.com/faq/#3.5 */
['domain', 'flag', 'path', 'secure', 'expiration', 'name', 'value'],
$data
);
$cookies[$cookie['name']] = $cookie;
}
return $cookies;
}
/**
* Returns the cookie file name.
*
* @return string
*/
protected function getCookieFileName(): string
{
return $this->cookiePath . sha1($this->username . chr(0) . $this->password . chr(0) . $this->userAgent);
}
}