summaryrefslogtreecommitdiffstats
path: root/src/Response.php
blob: f0ecb8d5eb4671421b41539f22592b0fec78890b (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
<?php

declare(strict_types=1);

namespace Cepis;

/**
 * What a {@see Transport} hands back: an HTTP status, the response headers and
 * the body as a string.
 *
 * Deliberately not a PSR-7 message. This library makes one GET and needs three
 * things out of it; a plain value object keeps the {@see Transport} interface
 * implementable in a few lines against whatever HTTP layer the host
 * application already has.
 */
final class Response
{
    /**
     * @param array<string, string|list<string>> $headers Response headers.
     *     Keys may be in any case and values may be a single string or a list
     *     of them; {@see Response::header()} handles both, so an implementer
     *     can pass through whatever their HTTP layer produced.
     */
    public function __construct(
        public readonly int $status,
        public readonly array $headers = [],
        public readonly string $body = '',
    ) {
    }

    /**
     * Look a header up case-insensitively, returning the first value or `null`
     * when it is absent.
     */
    public function header(string $name): ?string
    {
        foreach ($this->headers as $key => $value) {
            if (strcasecmp((string) $key, $name) !== 0) {
                continue;
            }
            if (is_array($value)) {
                $value = $value[array_key_first($value)] ?? null;
            }

            return is_scalar($value) ? (string) $value : null;
        }

        return null;
    }
}