Skip to content

Instantly share code, notes, and snippets.

@kocsismate
Created August 21, 2020 11:59
Show Gist options
  • Save kocsismate/3936b27b2e445d8492ad395e8cb83ea7 to your computer and use it in GitHub Desktop.
Save kocsismate/3936b27b2e445d8492ad395e8cb83ea7 to your computer and use it in GitHub Desktop.
ext/json OO API
<?php
final class Json
{
/** Equivalent to json_encode() */
public static function fromValue(mixed $value, int $options, int $depth = 512): Json {}
/** Just stores the stream */
public static function fromStream($stream): Json {}
/** Just stores the string */
public static function fromString(string $string): Json {}
/** Just stores the string */
public function __construct(string $string) {}
/** Functionality offered by simdjson */
public function isValid(): bool {}
/** Functionality offered by simdjson */
public function keyExists(string $key): bool {}
/** Functionality offered by simdjson */
public function keyValue(string $key): mixed {}
/** Functionality offered by simdjson */
public function keyCount(string $key): int {}
/** Returns the string representation */
public function __toString(): string {}
/** Returns the string representation */
public function toString(): string {}
/** Equivalent to json_decode() */
public function toValue(int $options, int $depth = 512): mixed {}
/** Equivalent to json_decode(), but fails if root level is not an object */
public function toObject(int $options, int $depth = 512): object {}
/** Equivalent to json_decode(), but converts objects to arrays, and fails if root level is not an array */
public function toArray(int $options, int $depth = 512): array {}
}
$value = ["count" => 3, "items" => [1, 2, 3]];
// json_encode()
$json = Json::fromValue($value)->toString(); // {"count":3,"items":[1,2,3]}
// json_decode()
$value = Json::fromString($json)->toValue(); // object(stdClass)#1 (2) { ["count"]=> int(3), ["items"]=> ... }
$object = Json::fromString($json)->toObject(); // object(stdClass)#1 (2) { ["count"]=> int(3), ["items"]=> ... }
$array = Json::fromString($json)->toArray(); // array(2) { ["count"]=> int(3), ["items"]=> ... }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment