Completed
Push — master ( 893fe7...1d240f )
by Michał
01:59
created

Authentication::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 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->prepare($method, $url, $body)->send();
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->prepare($method, $url, $body)->send();
52
53
        return $response->code == 201;
54
    }
55
}