Passed
Push — master ( ad575b...d3e169 )
by Stephen
06:09
created

GithubUrl::getApiResponse()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 10
c 0
b 0
f 0
nc 2
nop 0
dl 0
loc 18
rs 9.9332
1
<?php
2
3
namespace Sfneal\Dependencies\Utils;
4
5
use Illuminate\Http\Client\Response;
6
use Illuminate\Support\Facades\Cache;
7
use Illuminate\Support\Facades\Http;
8
9
class GithubUrl extends DependencyUrl
10
{
11
    /**
12
     * @var Url
13
     */
14
    private $api;
15
16
    /**
17
     * @var string
18
     */
19
    private $githubRepo;
20
21
    /**
22
     * GithubUrl Constructor.
23
     *
24
     * @param  string  $githubRepo  GitHub repo name
25
     */
26
    public function __construct(string $githubRepo)
27
    {
28
        $this->githubRepo = $githubRepo;
29
        $this->api = Url::from("api.github.com/repos/{$this->githubRepo}");
30
31
        parent::__construct(Url::from("github.com/{$this->githubRepo}"), null);
32
    }
33
34
    /**
35
     * Retrieve the GitHub repo's description.
36
     *
37
     * @return string
38
     */
39
    public function description(): ?string
40
    {
41
        return $this->getApiResponse()->json('description');
42
    }
43
44
    /**
45
     * Retrieve the GitHub repo's description.
46
     *
47
     * @return string
48
     */
49
    public function defaultBranch(): string
50
    {
51
        return $this->getApiResponse()->json('default_branch') ?? 'master';
52
    }
53
54
    /**
55
     * Retrieve a link to download the GitHub repo zip.
56
     *
57
     * @return string
58
     */
59
    public function download(): string
60
    {
61
        return Url::from("github.com/{$this->githubRepo}/archive/refs/heads/{$this->defaultBranch()}.zip")->get();
62
    }
63
64
    /**
65
     * Retrieve a cached HTTP response from the GitHub api.
66
     *
67
     * @return ?Response
68
     */
69
    private function getApiResponse(): ?Response
70
    {
71
        $response = Http::withHeaders([
72
            'Authorization' => 'token '.config('dependencies.github_pat'),
73
        ])
74
            ->get($this->api->get());
75
76
        // Client error
77
        if ($response->clientError() && str_contains($response->json('message'), 'API rate limit exceeded')) {
78
            return null;
79
        }
80
81
        // Cache response
82
        return Cache::remember(
83
            config('dependencies.cache.prefix').':api-responses:'.crc32($this->api->get()),
84
            config('dependencies.cache.ttl'),
85
            function () use ($response): Response {
86
                return $response;
87
            }
88
        );
89
    }
90
}
91