10 static private $version = 3;
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 "text/plain"=> "self::fromData",
25 static function register(string $type, callable
$handler) {
26 self
::$types[$type] = $handler;
29 static function registered(string $type) : bool {
30 return isset(self
::$types[$type]);
33 static function unregister(string $type) {
34 unset(self
::$types[$type]);
37 static function version(int $v = null) : int {
38 $api = self
::$version;
45 private static function fromJson(Body
$json) {
46 $decoded = json_decode($json);
47 if (!isset($decoded) && json_last_error()) {
48 throw new \
UnexpectedValueException("Could not decode JSON: ".
49 json_last_error_msg());
54 private static function fromBase64(Body
$base64) : string {
55 if (false === ($decoded = base64_decode($base64))) {
56 throw new \
UnexpectedValueExcpeption("Could not decode BASE64");
60 private static function fromData(Body
$data) : string {
61 return (string) $data;
64 function __construct(Header
$contentType) {
65 if (strcasecmp($contentType->name
, "Content-Type")) {
66 throw new \
InvalidArgumentException(
67 "Expected Content-Type header, got ". $contentType->name
);
69 $vapi = static::version();
70 $this->type
= preg_replace("/
71 (?:application\/(?:vnd\.github(?:\.v$vapi)?)?)
74 | (?:\.[^.+]+)?\+? (json)
75 )/x", "\\1", current(array_keys($contentType->getParams()->params
)));
78 function getType() : string {
82 function parseBody(Body
$data) {
83 $type = $this->getType();
84 if (static::registered($type)) {
85 return call_user_func(self
::$types[$type], $data, $type);
87 throw new \
UnexpectedValueException("Unhandled content type '$type'");