Passed
Push — master ( 922855...7901b7 )
by Nils
02:07
created

StatusCodeCheck   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 8
eloc 24
dl 0
loc 54
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A setHttpClient() 0 3 1
A getIdentifier() 0 3 1
A init() 0 4 1
A run() 0 19 5
1
<?php
2
3
namespace Leankoala\HealthFoundation\Check\Resource\Http;
4
5
use GuzzleHttp\Client;
6
use GuzzleHttp\Exception\ClientException;
7
use Leankoala\HealthFoundation\Check\Check;
8
use Leankoala\HealthFoundation\Check\HttpClientAwareCheck;
9
use Leankoala\HealthFoundation\Check\Result;
10
11
class StatusCodeCheck implements Check, HttpClientAwareCheck
12
{
13
    const IDENTIFIER = 'base:resource:http:status';
14
15
    private $destination = null;
16
    private $expectedHttpStatus = null;
17
18
    /**
19
     * @var Client
20
     */
21
    private $httpClient;
22
23
    public function init($destination, $expectedHttpStatus = 200)
24
    {
25
        $this->destination = $destination;
26
        $this->expectedHttpStatus = (int)$expectedHttpStatus;
27
    }
28
29
    public function setHttpClient(Client $client)
30
    {
31
        $this->httpClient = $client;
32
    }
33
34
    /**
35
     * Checks the response status
36
     *
37
     * @return Result
38
     */
39
    public function run()
40
    {
41
        try {
42
            $response = $this->httpClient->request('HEAD', $this->destination);
43
            $statusCode = $response->getStatusCode();
44
        } catch (ClientException $e) {
45
            $statusCode = $e->getResponse()->getStatusCode();
46
        } catch (\Exception $e) {
47
            $statusCode = 0;
48
            $errorMessage = $e->getMessage();
49
        }
50
51
        if ($statusCode === $this->expectedHttpStatus) {
52
            return new Result(Result::STATUS_PASS, 'HTTP status code for ' . $this->destination . ' was ' . $statusCode . ' as expected.');
53
        } else {
54
            if ($statusCode === 0) {
55
                return new Result(Result::STATUS_FAIL, 'The HTTP request could not be sent. Message: ' . $errorMessage);
56
            } else {
57
                return new Result(Result::STATUS_FAIL, 'HTTP status for ' . $this->destination . ' is different [' . $this->expectedHttpStatus . ' was expected but ' . $statusCode . ' was delivered]');
58
            }
59
        }
60
    }
61
62
    public function getIdentifier()
63
    {
64
        return self::IDENTIFIER;
65
    }
66
}
67