update to PHP-8.1
[m6w6/seekat] / lib / API / ContentType / Handler / Base64.php
1 <?php
2
3 namespace seekat\API\ContentType\Handler;
4
5 use http\Message\Body;
6 use seekat\API\ContentType\Handler;
7 use seekat\Exception\InvalidArgumentException;
8 use seekat\Exception\UnexpectedValueException;
9 use function seekat\typeof;
10
11 final class Base64 implements Handler {
12 /**
13 * @inheritdoc
14 */
15 function types() : array {
16 return ["base64"];
17 }
18
19 /**
20 * @inheritdoc
21 * @param string $data
22 */
23 function encode(mixed $data): Body {
24 if (!is_scalar($data)) {
25 throw new InvalidArgumentException(
26 "BASE64 encoding argument must be scalar, got ".typeof($data));
27 }
28 return (new Body)->append(base64_encode($data));
29 }
30
31 /**
32 * @inheritdoc
33 * @return string
34 */
35 function decode(Body $body) : string {
36 $data = base64_decode($body, true);
37
38 if (false === $data) {
39 $e = error_get_last();
40 throw new UnexpectedValueException("Could not decode BASE64: ".
41 ($e ? $e["message"] : "Unknown error"));
42 }
43
44 return $data;
45 }
46 }