Completed
Pull Request — master (#2)
by Michał
01:58
created

Authentication   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
wmc 4
lcom 1
cbo 4
dl 0
loc 47
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A authenticate() 0 14 2
A register() 0 16 1
1
<?php
2
namespace Barenote\Endpoint;
3
4
use Barenote\Domain\Credentials;
5
use Barenote\Domain\Token;
6
use Barenote\Enum\HttpMethod;
7
use Barenote\Transport\Transport;
8
9
class Authentication
10
{
11
    const URL_LOGIN = '/api/login';
12
    const URL_REGISTER = '/api/register';
13
14
    /**
15
     * @var Transport
16
     */
17
    private $transport;
18
19
    public function __construct(Transport $transport)
20
    {
21
        $this->transport = $transport;
22
    }
23
24
    public function authenticate(Credentials $credentials): Token
25
    {
26
        $method = HttpMethod::POST();
27
        $body   = json_encode($credentials);
28
        $url    = self::URL_LOGIN;
29
30
        $response = $this->transport->sendRequest($method, $url, $body);
31
32
        if ($response->code === 403) {
33
            throw new \Exception("Invalid credentials");
34
        }
35
36
        return new Token($response->body->access_token);
37
    }
38
39
    public function register(string $username, string $email, string $password): bool
40
    {
41
        $method = HttpMethod::POST();
42
        $body   = json_encode(
43
            [
44
                'username' => $username,
45
                'password' => $password,
46
                'email'    => $email
47
            ]
48
        );
49
        $url    = self::URL_REGISTER;
50
51
        $response = $this->transport->sendRequest($method, $url, $body);
52
53
        return $response->code == 201;
54
    }
55
}