PHP code example of helmich / schema2class
1. Go to this page and download the library: Download helmich/schema2class 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/ */
helmich / schema2class example snippets
$userData = json_decode("user.json", true);
$user = \MyNamespace\Target\User::buildFromInput($userData);
echo "Hello, " . $user->getGivenName() . "\n";
class UserLocation
{
private static array $schema = array(
'properties' => array(
'city' => array(
'type' => 'string',
),
),
);
private ?string $country = null;
private ?string $city = null;
public function __construct()
{
}
public function getCity() : ?string
{
return $this->city;
}
public function withCity(string $city) : self
{
$validator = new \JsonSchema\Validator();
$validator->validate($city, static::$schema['properties']['city']);
if (!$validator->isValid()) {
throw new \InvalidArgumentException($validator->getErrors()[0]['message']);
}
$clone = clone $this;
$clone->city = $city;
return $clone;
}
public function withoutCity() : self
{
$clone = clone $this;
unset($clone->city);
return $clone;
}
public static function buildFromInput(array $input) : UserLocation
{
static::validateInput($input);
$city = null;
if (isset($input['city'])) {
$city = $input['city'];
}
$obj = new static();
$obj->city = $city;
return $obj;
}
public function toJson() : array
{
$output = [];
if (isset($this->city)) {
$output['city'] = $this->city;
}
return $output;
}
public static function validateInput(array $input, bool $return = false) : bool
{
$validator = new \JsonSchema\Validator();
$validator->validate($input, static::$schema);
if (!$validator->isValid() && !$return) {
$errors = array_map(function($e) {
return $e["property"] . ": " . $e["message"];
}, $validator->getErrors());
throw new \InvalidArgumentException(join(", ", $errors));
}
return $validator->isValid();
}
public function __clone()
{
}
}