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