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",
24 static function register(string $type, callable
$handler) {
25 self
::$types[$type] = $handler;
28 static function registered(string $type) : bool {
29 return isset(self
::$types[$type]);
32 static function unregister(string $type) {
33 unset(self
::$types[$type]);
36 static function version(int $v = null) : int {
37 $api = self
::$version;
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());
53 private static function fromBase64(Body
$base64) : string {
54 if (false === ($decoded = base64_decode($base64))) {
55 throw new \
UnexpectedValueExcpeption("Could not decode BASE64");
59 private static function fromData(Body
$data) : string {
60 return (string) $data;
63 function __construct(Header
$contentType) {
64 if (strcasecmp($contentType->name
, "Content-Type")) {
65 throw new \
InvalidArgumentException(
66 "Expected Content-Type header, got ". $contentType->name
);
68 $vapi = static::version();
69 $this->type
= preg_replace("/
70 (?:application\/(?:vnd\.github(?:\.v$vapi)?)?)
73 | (?:\.[^.+]+)?\+? (json)
74 )/x", "\\1", current(array_keys($contentType->getParams()->params
)));
77 function getType() : string {
81 function parseBody(Body
$data) {
82 $type = $this->getType();
83 if (static::registered($type)) {
84 return call_user_func(self
::$types[$type], $data, $type);
86 throw new \
UnexpectedValueException("Unhandled content type '$type'");