Passed
Push — master ( 68f6f3...4b285f )
by Mikołaj
02:46
created

BuildsService::getLastBuildByBranch()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 9
nc 2
nop 2
dl 0
loc 15
ccs 0
cts 8
cp 0
crap 6
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace Wulkanowy\BitriseRedirector\Service;
4
5
use GuzzleHttp\Client;
6
use GuzzleHttp\Exception\ClientException;
7
use Symfony\Component\Cache\Simple\FilesystemCache;
8
9
class BuildsService
10
{
11
    private const STATUS_SUCCESS = 1;
12
13
    /**
14
     * @var Client
15
     */
16
    private $client;
17
18
    /**
19
     * @var FilesystemCache
20
     */
21
    private $cache;
22
23
    public function __construct(Client $client)
24
    {
25
        $this->client = $client;
26
        $this->cache = new FilesystemCache();
27
    }
28
29
    /**
30
     * @param string $branch
31
     * @param string $slug
32
     *
33
     * @throws \RuntimeException
34
     * @throws RequestFailedException
35
     * @throws \Psr\SimpleCache\InvalidArgumentException
36
     *
37
     * @return array
38
     */
39
    public function getLastBuildInfoByBranch(string $branch, string $slug): array
40
    {
41
        $tag = 'builds.'.$slug.'.'.$branch.'.last';
42
43
        if ($this->cache->has($tag)) {
44
            $response = $this->cache->get($tag);
45
        } else {
46
            $response = $this->getLastBuildByBranch($slug, $branch)->getBody()->getContents();
47
            $this->cache->set($tag, $response, 3600);
48
        }
49
50
        $lastBuild = json_decode($response, true)['data'];
51
52
        if (empty($lastBuild)) {
53
            throw new RequestFailedException('Build on branch '.$branch.' not found.');
54
        }
55
56
        return $lastBuild[0];
57
    }
58
59
    /**
60
     * @param string $slug
61
     * @param string $branch
62
     *
63
     * @return \Psr\Http\Message\ResponseInterface
64
     * @throws RequestFailedException
65
     */
66
    private function getLastBuildByBranch(string $slug, string $branch): \Psr\Http\Message\ResponseInterface
67
    {
68
        try {
69
            return $this->client->get(
70
                'apps/'.$slug.'/builds',
71
                [
72
                    'query' => [
73
                        'branch' => $branch,
74
                        'limit'  => 1,
75
                        'status' => self::STATUS_SUCCESS,
76
                    ],
77
                ]
78
            );
79
        } catch (ClientException $e) {
80
            throw new RequestFailedException('App not exist.');
81
        }
82
    }
83
}
84