Authentication   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 69
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 5

Importance

Changes 0
Metric Value
wmc 6
lcom 0
cbo 5
dl 0
loc 69
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A token() 0 4 1
A __toString() 0 4 1
A withToken() 0 4 1
B withUsernameAndPassword() 0 24 2
1
<?php
2
3
declare(strict_types = 1);
4
5
namespace SportTrackerConnector\Endomondo\API;
6
7
use GuzzleHttp\Client;
8
use Ramsey\Uuid\Uuid;
9
use SportTrackerConnector\Core\Tracker\Exception\InvalidCredentialsException;
10
11
final class Authentication
12
{
13
    private const URL_AUTHENTICATE = 'https://api.mobile.endomondo.com/mobile/auth';
14
15
    /**
16
     * @var string
17
     */
18
    protected $token;
19
20
    /**
21
     * @param string $token The token.
22
     */
23
    private function __construct(string $token)
24
    {
25
        $this->token = $token;
26
    }
27
28
    /**
29
     * Get the token.
30
     *
31
     * @return string
32
     */
33
    public function token(): string
34
    {
35
        return $this->token;
36
    }
37
38
    public static function withToken(string $token): Authentication
39
    {
40
        return new static($token);
41
    }
42
43
    /**
44
     * @param string $username
45
     * @param string $password
46
     * @param Client $client
47
     * @return Authentication If there is an error making the request.
48
     * @throws \SportTrackerConnector\Core\Tracker\Exception\InvalidCredentialsException
49
     */
50
    public static function withUsernameAndPassword(string $username, string $password, Client $client): Authentication
51
    {
52
        $response = $client->get(
53
            self::URL_AUTHENTICATE,
54
            array(
55
                'query' => array(
56
                    'country' => 'GB',
57
                    'action' => 'pair',
58
                    'deviceId' => Uuid::uuid5(Uuid::NAMESPACE_DNS, gethostname())->toString(),
59
                    'email' => $username,
60
                    'password' => $password,
61
                )
62
            )
63
        );
64
65
        $responseBody = $response->getBody()->getContents();
66
        $response = parse_ini_string($responseBody);
67
68
        if (array_key_exists('authToken', $response)) {
69
            return new static($response['authToken']);
70
        }
71
72
        throw new InvalidCredentialsException('Authentication on Endomondo failed.');
73
    }
74
75
    public function __toString()
76
    {
77
        return $this->token();
78
    }
79
}
80