### Installation Source: https://github.com/nette/schema/blob/master/readme.md Installs the Nette Schema library using Composer. Requires PHP version 8.1 or higher. ```shell composer require nette/schema ``` -------------------------------- ### Data Normalization with before() Source: https://github.com/nette/schema/blob/master/readme.md Demonstrates how to normalize data before validation using the 'before()' method. This example shows splitting a string into an array. ```php $explode = fn($v) => explode(' ', $v); $schema = Expect::arrayOf('string') ->before($explode); $normalized = $processor->process($schema, 'a b c'); // OK, returns ['a', 'b', 'c'] ``` -------------------------------- ### Array of Specific Types Source: https://github.com/nette/schema/blob/master/readme.md Shows how to define schemas for arrays where all elements must be of a specific type (e.g., string) or have specific keys and values. Includes examples for both general arrays and indexed lists. ```php $schema = Expect::arrayOf('string'); $schema = Expect::arrayOf('string', 'int'); $schema = Expect::listOf('string'); $schema = Expect::arrayOf(Expect::bool()); ``` -------------------------------- ### Schema Definition: Basic Data Types Source: https://github.com/nette/schema/blob/master/readme.md Provides examples of defining schemas for basic PHP data types like string, integer, float, boolean, null, and array. ```php Expect::string($default = null) Expect::int($default = null) Expect::float($default = null) Expect::bool($default = null) Expect::null() Expect::array($default = []) ``` -------------------------------- ### Custom Assertion for Array Count Source: https://github.com/nette/schema/blob/master/readme.md Adds a custom validation rule using a callable. This example checks if the number of elements in an array is even. An optional description can be provided for error messages. ```php $countIsEven = fn($v) => count($v) % 2 === 0; $schema = Expect::arrayOf('string') ->assert($countIsEven); // the count must be even $processor->process($schema, ['a', 'b']); // OK $processor->process($schema, ['a', 'b', 'c']); // ERROR: 3 is not even ``` ```php $schema = Expect::arrayOf('string') ->assert($countIsEven, 'Even items in array'); $processor->process($schema, ['a', 'b', 'c']); // Failed assertion "Even items in array" for item with value array. ``` -------------------------------- ### Structure Definition with Properties Source: https://github.com/nette/schema/blob/master/readme.md Demonstrates how to define structures with required and optional properties, including setting default values and handling nullability. Shows how to skip default values in the output. ```php $schema = Expect::structure([ 'required' => Expect::string()->required(), 'optional' => Expect::string(), // the default value is null ]); $schema = Expect::structure([ 'required' => Expect::string()->required(), 'optional' => Expect::string(), ])->skipDefaults(); $schema = Expect::structure([ 'optional' => Expect::string(), 'nullable' => Expect::string()->nullable(), ]); ``` -------------------------------- ### Customizing Object Mapping with from() Source: https://github.com/nette/schema/blob/master/readme.md Explains how to provide custom schema definitions for elements when using the 'from()' method to map data to objects. ```php $schema = Expect::from(new Config, [ 'name' => Expect::string()->pattern('\w:.*'), ]); ``` -------------------------------- ### Mapping Data to Objects with from() Source: https://github.com/nette/schema/blob/master/readme.md Illustrates how to generate a schema from a PHP class definition using the 'from()' method. Supports mapping input data to class properties. ```php class Config { public string $name; public ?string $password; public bool $admin = false; } $schema = Expect::from(new Config); $data = [ 'name' => 'jeff', ]; $normalized = $processor->process($schema, $data); // $normalized instanceof Config // $normalized = {'name' => 'jeff', 'password' => null, 'admin' => false} ``` -------------------------------- ### Mapping Anonymous Classes with from() Source: https://github.com/nette/schema/blob/master/readme.md Shows how to use the 'from()' method with anonymous classes to generate schemas. ```php $schema = Expect::from(new class { public string $name; public ?string $password; public bool $admin = false; }); ``` -------------------------------- ### Chained Transformations and Assertions Source: https://github.com/nette/schema/blob/master/readme.md Demonstrates chaining multiple operations: casting to string, asserting lowercase characters, and transforming to uppercase. ```php Expect::type('string|int') ->castTo('string') ->assert('ctype_lower', 'All characters must be lowercased') ->transform(fn(string $s) => strtoupper($s)); // conversion to uppercase ``` -------------------------------- ### Schema Definition: Setting Default Values Source: https://github.com/nette/schema/blob/master/readme.md Shows how to set a default value for a field using the default() method or directly in the Expect constructor. ```php use Nette\Schema\Expect; // Using default() method $schema1 = Expect::bool()->default(false); // Using constructor $schema2 = Expect::bool(false); ``` -------------------------------- ### Schema Definition: Basic Structure Source: https://github.com/nette/schema/blob/master/readme.md Defines a basic schema for a structure expecting 'processRefund' (boolean) and 'refundAmount' (integer) fields using Nette\Schema\Expect. ```php use Nette\Schema\Expect; $schema = Expect::structure([ 'processRefund' => Expect::bool(), 'refundAmount' => Expect::int(), ]); ``` -------------------------------- ### Scalar and Union Type Expectations Source: https://github.com/nette/schema/blob/master/readme.md Demonstrates how to define expected scalar types (like bool, string, int) and union types using Expect::type(). It also shows how to specify class or interface names as types. ```php Expect::type('scalar'); Expect::scalar(); Expect::type('AddressEntity'); Expect::type('bool|string|array'); ``` -------------------------------- ### Enumeration with anyOf() Source: https://github.com/nette/schema/blob/master/readme.md Illustrates the use of Expect::anyOf() to define a set of allowed values or schemas for elements within an array. Covers specifying default values and using the unpacking operator. ```php $schema = Expect::listOf(Expect::anyOf('a', true, null)); $schema = Expect::listOf(Expect::anyOf(Expect::string(), true, null)); // default is 'hello' Expect::anyOf(Expect::string('hello'), true, null)->firstIsDefault(); ``` -------------------------------- ### Handling Additional Structure Items Source: https://github.com/nette/schema/blob/master/readme.md Explains how to configure structures to allow or disallow additional items not explicitly defined in the schema, using the otherItems() method to specify a schema for these extra elements. ```php $schema = Expect::structure([ 'key' => Expect::string(), ])->otherItems(Expect::int()); ``` -------------------------------- ### Schema Definition: Casting to Array Source: https://github.com/nette/schema/blob/master/readme.md Shows how to define a schema that will cast the processed output to an array using the castTo('array') method. ```php use Nette\Schema\Expect; $schema = Expect::structure([...])->castTo('array'); ``` -------------------------------- ### Transform with Custom Error Reporting Source: https://github.com/nette/schema/blob/master/readme.md Shows how to use the `transform` method with a callback that receives a `Nette\Schema\Context` object to add custom error messages and codes. ```php Expect::string() ->transform(function (string $s, Nette\Schema\Context $context) { if (!ctype_lower($s)) { $context->addError('All characters must be lowercased', 'my.case.error'); return null; } return strtoupper($s); }); } ``` -------------------------------- ### Basic Usage: Processing Data Source: https://github.com/nette/schema/blob/master/readme.md Demonstrates the basic usage of Nette Schema for validating and normalizing data. It uses the Nette\Schema\Processor to process data against a schema and handles potential Nette\Schema\ValidationException errors. ```php use Nette\Schema\Processor; use Nette\Schema\ValidationException; $processor = new Processor; try { $normalized = $processor->process($schema, $data); } catch (ValidationException $e) { echo 'Data is invalid: ' . $e->getMessage(); } ``` -------------------------------- ### Schema Definition: Allowing Nullable Fields Source: https://github.com/nette/schema/blob/master/readme.md Illustrates how to make a field nullable in the schema definition using the nullable() method. ```php use Nette\Schema\Expect; $schema = Expect::structure([ 'processRefund' => Expect::bool()->nullable(), 'refundAmount' => Expect::int(), ]); ``` -------------------------------- ### Deprecating Properties Source: https://github.com/nette/schema/blob/master/readme.md Demonstrates how to mark properties as deprecated using the `deprecated()` method. Deprecation notices are retrieved using `$processor->getWarnings()`. ```php $schema = Expect::structure([ 'old' => Expect::int()->deprecated('The item %path% is deprecated'), ]); $processor->process($schema, ['old' => 1]); // OK $processor->getWarnings(); // ["The item 'old' is deprecated"] ``` -------------------------------- ### Casting to a Class with Constructor Source: https://github.com/nette/schema/blob/master/readme.md Casts validated data to a class instance, passing structure elements as named parameters to the constructor. ```php class Info { public function __construct( public bool $processRefund, public int $refundAmount, ) { } } // creates $obj = new Info(processRefund: ..., refundAmount: ...) ``` -------------------------------- ### Custom Assertion for File Existence Source: https://github.com/nette/schema/blob/master/readme.md Applies a custom assertion to validate if a given string represents an existing file. ```php Expect::string()->assert('is_file'); // the file must exist ``` -------------------------------- ### String Transformation to Uppercase Source: https://github.com/nette/schema/blob/master/readme.md Transforms a validated string to its uppercase equivalent using a callback function. ```php // conversion to uppercase: Expect::string()->transform(fn(string $s) => strtoupper($s)); ``` -------------------------------- ### Schema Definition: Making Fields Required Source: https://github.com/nette/schema/blob/master/readme.md Demonstrates how to make a field mandatory in the schema using the required() method. ```php use Nette\Schema\Expect; $schema = Expect::structure([ 'processRefund' => Expect::bool()->required(), 'refundAmount' => Expect::int(), ]); ``` -------------------------------- ### Schema Definition: Accepting Multiple Types Source: https://github.com/nette/schema/blob/master/readme.md Defines a schema that accepts multiple types (boolean, integer 1, or integer 0) for a field and casts them to boolean. ```php use Nette\Schema\Expect; $schema = Expect::structure([ 'processRefund' => Expect::anyOf(true, false, 1, 0)->castTo('bool'), 'refundAmount' => Expect::int(), ]); ``` -------------------------------- ### Casting to a Class with Public Properties Source: https://github.com/nette/schema/blob/master/readme.md Casts validated data to a class instance, populating its public properties from the structure. ```php class Info { public bool $processRefund; public int $refundAmount; } Expect::structure([ 'processRefund' => Expect::bool(), 'refundAmount' => Expect::int(), ])->castTo(Info::class); // creates '$obj = new Info' and writes to $obj->processRefund and $obj->refundAmount ``` -------------------------------- ### Casting Scalar to Class with Single Constructor Parameter Source: https://github.com/nette/schema/blob/master/readme.md Casts a scalar validated value to a class instance by passing the value as the sole parameter to the constructor. ```php Expect::string()->castTo(DateTime::class); // creates new DateTime(...) ``` -------------------------------- ### String Pattern Validation Source: https://github.com/nette/schema/blob/master/readme.md Validates that a string matches a given regular expression. The pattern is implicitly anchored with `^` and `$`. ```php // just 9 digits Expect::string()->pattern('\d{9}'); ``` -------------------------------- ### String Length Validation Source: https://github.com/nette/schema/blob/master/readme.md Validates that a string has a minimum and maximum length. ```php // string, at least 10 characters long, maximum 20 characters Expect::string()->min(10)->max(20); ``` -------------------------------- ### Casting to String Source: https://github.com/nette/schema/blob/master/readme.md Casts validated data to the string type. ```php Expect::scalar()->castTo('string'); ``` -------------------------------- ### Integer Range Validation Source: https://github.com/nette/schema/blob/master/readme.md Validates that an integer falls within a specified minimum and maximum value (inclusive). ```php // integer, between 10 and 20 inclusive Expect::int()->min(10)->max(20); ``` -------------------------------- ### String Maximum Length Validation Source: https://github.com/nette/schema/blob/master/readme.md Validates that a string does not exceed a maximum length. ```php // string, maximum 20 characters Expect::string()->max(20); ``` -------------------------------- ### Array Range Validation Source: https://github.com/nette/schema/blob/master/readme.md Validates that an array contains a minimum and maximum number of elements. ```php // array, at least 10 items, maximum 20 items Expect::array()->min(10)->max(20); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.