summaryrefslogtreecommitdiffstats
path: root/lib/cepis/Health.php
blob: 08f754792277e60ec3a637fae676b293cf42c882 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<?php

declare(strict_types=1);

namespace Cepis;

/**
 * The response of `GET /health`.
 *
 * Good for two things: checking that the API answers, and knowing **which
 * version of the database** is live. The DNE database changes every two weeks;
 * {@see Health::$dne} identifies it.
 */
final class Health
{
    /**
     * Property names are the API's own JSON keys, `base_gerada_em` included.
     * See {@see Address} for why they are not translated or camel-cased.
     */
    public function __construct(
        public readonly string $status,
        public readonly string $dne,
        public readonly int $ceps,
        public readonly int $geo,
        public readonly string $base_gerada_em,
    ) {
    }

    /**
     * Build from the decoded response.
     *
     * @param array<string, mixed> $data
     */
    public static function fromArray(array $data): self
    {
        return new self(
            status: self::asString($data['status'] ?? ''),
            dne: self::asString($data['dne'] ?? ''),
            ceps: self::asInt($data['ceps'] ?? 0),
            geo: self::asInt($data['geo'] ?? 0),
            base_gerada_em: self::asString($data['base_gerada_em'] ?? ''),
        );
    }

    /**
     * `true` when the API reports itself healthy.
     */
    public function isOk(): bool
    {
        return $this->status === 'ok';
    }

    /**
     * @return array<string, mixed>
     */
    public function toArray(): array
    {
        return [
            'status' => $this->status,
            'dne' => $this->dne,
            'ceps' => $this->ceps,
            'geo' => $this->geo,
            'base_gerada_em' => $this->base_gerada_em,
        ];
    }

    private static function asString(mixed $value): string
    {
        return is_scalar($value) ? (string) $value : '';
    }

    private static function asInt(mixed $value): int
    {
        return is_numeric($value) ? (int) (float) $value : 0;
    }
}