1. Go to this page and download the library: Download klimick/decode library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
klimick / decode example snippets
use Klimick\Decode\Decoder as t;
// Describes runtime type for array{name: string, age: int, meta: list<string>}
$libraryDefinition = t\shape(
id: t\int(),
name: t\string(),
meta: t\listOf(t\string()),
);
// Untrusted data
$json = '{
"id": 42,
"name": "Decode",
"meta": [
"runtime type system",
"psalm integration",
"with whsv26/functional"
]
}';
// If decode will fail, CastException is thrown.
// $person is array{name: string, age: int, meta: list<string>}
$person = t\tryCast(
value: $json,
to: t\fromJson($libraryDefinition),
);
// Either data type from whsv26/functional
// Left side contains decoding errors
// Right side holds decoded valid
// $person is Either<Invalid, Valid<array{name: string, age: int, meta: list<string>}>>
$personEither = t\decode(
value: $json,
with: t\fromJson($libraryDefinition),
)
// Option data type from whsv26/functional
// $person is Option<array{name: string, age: int, meta: list<string>}>
$personOption = t\cast(
value: $json,
to: t\fromJson($libraryDefinition),
);
final class SomeClass
{
public function __construct(
public int $prop1,
public string $prop2,
) {}
/**
* @return DecoderInterface<SomeClass>
*/
public static function type(): DecoderInterface
{
return object(self::class)(
prop1: int(),
prop2: string(),
);
}
}
final class SomeClass
{
/**
* @param list<SomeClass> $recursive
*/
public function __construct(
public int $prop1,
public string $prop2,
public array $recursive = [],
) { }
/**
* @return DecoderInterface<SomeClass>
*/
public static function type(): DecoderInterface
{
$self = rec(fn() => self::type());
return object(self::class)(
prop1: int(),
prop2: string(),
recursive: listOf($self),
);
}
}