PHP code example of nyra / zod
1. Go to this page and download the library: Download nyra/zod 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/ */
nyra / zod example snippets
use Nyra\Zod\Z;
$schema = Z::object([
'id' => Z::number()->int()->positive(),
'email' => Z::string()->email(),
'roles' => Z::array(Z::string()->nonempty())->nonempty(),
]);
$payload = $schema->parse([
'id' => 42,
'email' => '[email protected] ',
'roles' => ['admin'],
]);
use Nyra\Zod\Z;
$userSchema = Z::object([
'name' => Z::string()->min(2),
'age' => Z::coerce()->number()->int()->min(0)->default(18),
'email' => Z::string()->email()->optional(),
'address' => Z::object([
'street' => Z::string()->nonempty(),
'zip' => Z::string()->regex('/^[0-9]{5}$/'),
])->passthrough(),
]);
$result = $userSchema->safeParse($input);
if ($result->success) {
$user = $result->data; // validated payload
} else {
// handle $result->error
}
$trimmed = Z::string()
->preprocess(static fn ($value) => is_string($value) ? trim($value) : $value)
->nonempty();
$upper = Z::string()->transform('strtoupper');
use Nyra\Zod\Errors\ZodError;
try {
$userSchema->parse($input);
} catch (ZodError $error) {
foreach ($error->getIssues() as $issue) {
printf("[%s] %s at %s\n", $issue->code, $issue->message, implode('.', $issue->path));
}
}
/** @var array{name: string, age: int, email?: string|null} $user */
$user = $userSchema->parse($input);