Completed
Push — master ( b67977...b30551 )
by Timur
03:20
created

ApiProvider::getClient()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 6
nc 4
nop 0
1
<?php
2
3
namespace Laravel\Forge;
4
5
use GuzzleHttp\Client;
6
use GuzzleHttp\ClientInterface;
7
8
class ApiProvider
9
{
10
    /**
11
     * Base API URI.
12
     *
13
     * @var string
14
     */
15
    const BASE_URI = 'https://forge.laravel.com/api/v1/';
16
17
    /**
18
     * API token.
19
     *
20
     * @var string
21
     */
22
    private $token;
23
24
    /**
25
     * HTTP client.
26
     *
27
     * @var \GuzzleHttp\ClientInterface
28
     */
29
    protected $client;
30
31
    /**
32
     * The optional rate limiting function.
33
     *
34
     * @var callable|null
35
     */
36
    protected $rateLimiter;
37
38
    /**
39
     * Create new API provider instance.
40
     *
41
     * @param string $token
42
     */
43
    public function __construct(string $token)
44
    {
45
        $this->token = $token;
46
    }
47
48
    /**
49
     * HTTP client.
50
     *
51
     * @return \GuzzleHttp\ClientInterface
52
     */
53
    public function getClient(): ClientInterface
54
    {
55
        if (!is_null($this->rateLimiter)) {
56
            call_user_func($this->rateLimiter);
57
        }
58
59
        if (!is_null($this->client)) {
60
            return $this->client;
61
        }
62
63
        return $this->client = $this->createClient();
64
    }
65
66
    /**
67
     * API token.
68
     *
69
     * @return string
70
     */
71
    public function getToken(): string
72
    {
73
        return $this->token;
74
    }
75
76
    /**
77
     * Create new HTTP client.
78
     *
79
     * @return \GuzzleHttp\ClientInterface
80
     */
81
    public function createClient(): ClientInterface
82
    {
83
        $client = new Client([
84
            'base_uri' => static::BASE_URI,
85
            'headers' => [
86
                'Authorization' => 'Bearer '.$this->getToken(),
87
                'Accept' => 'application/json',
88
                'Content-Type' => 'application/json',
89
            ],
90
        ]);
91
92
        return $client;
93
    }
94
95
    /**
96
     * Sets an optional rate limiting function.
97
     *
98
     * @param callable $rateLimiter
99
     */
100
    public function setRateLimiter(callable $rateLimiter)
101
    {
102
        $this->rateLimiter = $rateLimiter;
103
    }
104
}
105