Completed
Push — master ( c7ff67...1bd8ce )
by Ben
02:48
created

Client::setStatus()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4

Importance

Changes 4
Bugs 0 Features 0
Metric Value
c 4
b 0
f 0
dl 0
loc 10
ccs 8
cts 8
cp 1
rs 9.2
cc 4
eloc 5
nc 3
nop 1
crap 4
1
<?php
2
3
namespace Maenbn\GitlabCiBuildStatus;
4
5
use Curl\Curl;
6
7
class Client
8
{
9
10
    protected $projectUrl;
11
12
    protected $projectId;
13
14
    protected $privateKey;
15
16
    protected $status;
17
18
    /**
19
     * @param $projectUrl
20
     * @param $projectId
21
     * @param $privateKey
22
     */
23 3
    public function __construct($projectUrl, $projectId, $privateKey)
24
    {
25 3
        $this->projectUrl = $projectUrl;
26 3
        $this->projectId = $projectId;
27 3
        $this->privateKey = $privateKey;
28 3
    }
29
30
    /**
31
     * @param string $branch
32
     *
33
     * @return mixed
34
     * @throws \Exception
35
     */
36 3
    public function getStatus($branch = 'master')
37
    {
38
39 3
        $sha = $this->getLatestCommitSha($branch);
40
41 2
        $curl = new Curl();
42 2
        $curl->get($this->projectUrl . '/projects/' . $this->projectId . '/' .
43 2
            'repository/commits/' . $sha . '/statuses?private_token='. $this->privateKey);
44
45 2
        if ($curl->error) {
46
            throw new \Exception('Error: ' . $curl->errorCode . ': ' . $curl->errorMessage);
47
        }
48
49 2
        $response = $curl->response;
50
51 2
        $this->setStatus($response);
52
53 2
        return $this->status;
54
    }
55
56
    /**
57
     * @param $response
58
     *
59
     * @return array|null
60
     */
61 2
    protected function setStatus($response)
62
    {
63 2
        $this->status = 'success';
64
65 2
        foreach($response as $buildStatus) {
66 2
            if($buildStatus->allow_failure === false && $buildStatus->status == 'failed') {
67 1
                $this->status = 'failed';
68 1
            }
69 2
        }
70 2
    }
71
72
    /**
73
     * @param $branch
74
     * @return mixed
75
     * @throws \Exception
76
     */
77 3
    protected function getLatestCommitSha($branch)
78
    {
79 3
        $curl = new Curl();
80 3
        $curl->get($this->projectUrl . '/projects/' . $this->projectId . '/' .
81 3
            'repository/commits?private_token='. $this->privateKey . '&ref_name=' . $branch);
82
83 3
        if ($curl->error) {
84 1
            throw new \Exception('Error: ' . $curl->errorCode . ': ' . $curl->errorMessage);
85
        }
86
87 2
        $response = $curl->response;
88
89 2
        return $response[0]->id;
90
    }
91
92
}
93