e8f75dca1abbc03f343f1d507691fb34c67aef3e
[m6w6/seekat] / lib / API / ContentType.php
1 <?php
2
3 namespace seekat\API;
4
5 use http\Header;
6 use http\Message\Body;
7
8 class ContentType
9 {
10 static private $version = 3;
11
12 static private $types = [
13 "json" => "self::fromJson",
14 "base64" => "self::fromBase64",
15 "sha" => "self::fromData",
16 "raw" => "self::fromData",
17 "html" => "self::fromData",
18 "diff" => "self::fromData",
19 "patch" => "self::fromData",
20 ];
21
22 private $type;
23
24 static function register(string $type, callable $handler) {
25 self::$types[$type] = $handler;
26 }
27
28 static function registered(string $type) : bool {
29 return isset(self::$types[$type]);
30 }
31
32 static function unregister(string $type) {
33 unset(self::$types[$type]);
34 }
35
36 static function version(int $v = null) : int {
37 $api = self::$version;
38 if (isset($v)) {
39 self::$version = $v;
40 }
41 return $api;
42 }
43
44 private static function fromJson(Body $json) {
45 $decoded = json_decode($json);
46 if (!isset($decoded) && json_last_error()) {
47 throw new \UnexpectedValueException("Could not decode JSON: ".
48 json_last_error_msg());
49 }
50 return $decoded;
51 }
52
53 private static function fromBase64(Body $base64) : string {
54 if (false === ($decoded = base64_decode($base64))) {
55 throw new \UnexpectedValueExcpeption("Could not decode BASE64");
56 }
57 }
58
59 private static function fromData(Body $data) : string {
60 return (string) $data;
61 }
62
63 function __construct(Header $contentType) {
64 if (strcasecmp($contentType->name, "Content-Type")) {
65 throw new \InvalidArgumentException(
66 "Expected Content-Type header, got ". $contentType->name);
67 }
68 $vapi = static::version();
69 $this->type = preg_replace("/
70 (?:application\/(?:vnd\.github(?:\.v$vapi)?)?)
71 (?|
72 \. ([^.+]+)
73 | (?:\.[^.+]+)?\+? (json)
74 )/x", "\\1", current(array_keys($contentType->getParams()->params)));
75 }
76
77 function getType() : string {
78 return $this->type;
79 }
80
81 function parseBody(Body $data) {
82 $type = $this->getType();
83 if (static::registered($type)) {
84 return call_user_func(self::$types[$type], $data, $type);
85 }
86 throw new \UnexpectedValueException("Unhandled content type '$type'");
87 }
88 }