Completed
Pull Request — master (#331)
by Alejandro
05:29
created

HealthAction::handle()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 9
nc 2
nop 1
dl 0
loc 13
rs 9.9666
c 0
b 0
f 0
ccs 7
cts 7
cp 1
crap 3
1
<?php
2
declare(strict_types=1);
3
4
namespace Shlinkio\Shlink\Rest\Action;
5
6
use Doctrine\DBAL\Connection;
7
use Psr\Http\Message\ResponseInterface;
8
use Psr\Http\Message\ServerRequestInterface;
9
use Psr\Log\LoggerInterface;
10
use Shlinkio\Shlink\Core\Options\AppOptions;
11
use Zend\Diactoros\Response\JsonResponse;
12
13
class HealthAction extends AbstractRestAction
14
{
15
    private const HEALTH_CONTENT_TYPE = 'application/health+json';
16
    private const PASS_STATUS = 'pass';
17
    private const FAIL_STATUS = 'fail';
18
19
    protected const ROUTE_PATH = '/health';
20
    protected const ROUTE_ALLOWED_METHODS = [self::METHOD_GET];
21
22
    /** @var AppOptions */
23
    private $options;
24
    /** @var Connection */
25
    private $conn;
26
27 3
    public function __construct(Connection $conn, AppOptions $options, LoggerInterface $logger = null)
28
    {
29 3
        parent::__construct($logger);
30 3
        $this->conn = $conn;
31 3
        $this->options = $options;
32
    }
33
34
    /**
35
     * Handles a request and produces a response.
36
     *
37
     * May call other collaborating code to generate the response.
38
     */
39 2
    public function handle(ServerRequestInterface $request): ResponseInterface
40
    {
41 2
        $connected = $this->conn->ping();
42 2
        $statusCode = $connected ? self::STATUS_OK : self::STATUS_SERVICE_UNAVAILABLE;
43
44 2
        return new JsonResponse([
45 2
            'status' => $connected ? self::PASS_STATUS : self::FAIL_STATUS,
46 2
            'version' => $this->options->getVersion(),
47
            'links' => [
48
                'about' => 'https://shlink.io',
49
                'project' => 'https://github.com/shlinkio/shlink',
50
            ],
51 2
        ], $statusCode, ['Content-type' => self::HEALTH_CONTENT_TYPE]);
52
    }
53
}
54