Exporting to JSON Schema
Your schema is already a precise description of what the configuration may contain, and that description is useful outside PHP as well. Exported to JSON Schema, it lets editors:
- offer completion of keys and values right in the configuration file
- underline mistakes before the application even runs
- show the descriptions of the options as hints
Export
JsonSchema::export() turns your schema into a JSON Schema document, the
format editors read to offer completion and underline mistakes directly in the JSON or YAML file:
use Nette\Schema\Expect;
use Nette\Schema\JsonSchema;
$schema = Expect::structure([
'host' => Expect::string('localhost')->description('Database server hostname'),
'port' => Expect::int(3306)->min(1)->max(65535),
'user' => Expect::string()->required(),
]);
echo json_encode(JsonSchema::export($schema), JSON_PRETTY_PRINT);
{
"type": "object",
"properties": {
"host": {"type": "string", "description": "Database server hostname"},
"port": {"type": "integer", "minimum": 1, "maximum": 65535},
"user": {"type": "string"}
},
"required": ["user"],
"additionalProperties": false
}
Save the result into a file and point your editor to it; how exactly depends on the editor and the format of the configuration file.
What the Export Contains
The export describes the shape of the data: types, ranges, patterns, required items, enum values and the texts you added with description().
Default values, castTo() and transform() are deliberately left out, because they describe what
happens to the data after validation, and JSON Schema has no way to say that.
A type that exists only in PHP, such as a class (Expect::type(Address::class)), a callable or a resource, cannot
be exported at all. Instead of producing a document that would quietly describe something else, the export throws
Nette\NotSupportedException. The same goes for a custom element, whose rules the
export cannot know.
Differences from Validation
Two differences remain between the export and the validation. JSON Schema counts the length of a string in characters, while
Expect::string() counts bytes, so use Expect::unicode() for text that is not plain ASCII. And a
pattern() is exported as it is, but a JSON Schema validator reads it as an ECMAScript regular expression, so
constructions specific to PCRE may be understood differently there.