describe("::encode()", function () { it("encodes in json", function () { $json = Media::encode('json', ['key' => 'value']); expect($json)->toBe('{"key":"value"}'); }); it("encodes objects in json", function () { $json = Media::encode('json', new Collection(['key' => 'value'])); expect($json)->toBe('{"key":"value"}'); }); it("encodes in form data", function () { $json = Media::encode('form', ['key1' => 'value1', 'key2' => 'value2']); expect($json)->toBe('key1=value1&key2=value2'); }); }); describe("::decode()", function () { it("decodes json", function () { $data = Media::decode('json', '{"key":"value"}'); expect($data)->toBe(['key' => 'value']); }); it("decodes form data", function () { $data = Media::decode('form', 'key1=value1&key2=value2'); expect($data)->toBe(['key1' => 'value1', 'key2' => 'value2']); }); }); describe("::to()", function () { it("delegates to `::encode()`", function () { expect(Media::class)->toReceive('::encode')->with('json', '', ['key' => 'value']); Media::to('json', '', ['key' => 'value']); }); }); });
public static function reset() { static::$_formats = []; static::set('html', ['text/html', 'application/xhtml+xml']); static::set('text', ['text/plain']); static::set('json', ['application/json'], ['encode' => function ($data, $options = []) { $defaults = ['depth' => 512, 'flag' => 0]; $options += $defaults; $result = json_encode($data, $options['flag'], $options['depth']); if (json_last_error() !== JSON_ERROR_NONE) { throw new InvalidArgumentException(json_last_error_msg()); } return $result; }, 'decode' => function ($data, $options = []) { $defaults = ['array' => true, 'depth' => 512, 'flag' => 0]; $options += $defaults; $result = json_decode($data, $options['array'], $options['depth'], $options['flag']); if (json_last_error() !== JSON_ERROR_NONE) { throw new InvalidArgumentException(json_last_error_msg()); } return $result; }]); static::set('form', ['application/x-www-form-urlencoded', 'multipart/form-data'], ['encode' => 'http_build_query', 'decode' => function ($data) { $decoded = array(); parse_str($data, $decoded); return $decoded; }]); } } Media::reset();
/** * Parses a JSON-API payload string. * * @return object The payload object. */ public static function parse($payload, $key = 'id', $keys = []) { if (!$payload) { $data = []; } elseif (is_string($payload)) { $data = Media::decode('json', $payload); } else { $data = $payload; } return new static(['data' => $data, 'key' => $key, 'keys' => $keys]); }