New contact form with friendlycaptcha

This commit is contained in:
Jorit Tijsen
2026-02-24 14:04:04 +01:00
parent 6786ac7ce1
commit 3b4030113b
80 changed files with 2860 additions and 1918 deletions

View File

@@ -1,5 +1,4 @@
Nette Schema
************
# Nette Schema
[![Downloads this Month](https://img.shields.io/packagist/dm/nette/schema.svg)](https://packagist.org/packages/nette/schema)
[![Tests](https://github.com/nette/schema/workflows/Tests/badge.svg?branch=master)](https://github.com/nette/schema/actions)
@@ -21,7 +20,7 @@ Installation:
composer require nette/schema
```
It requires PHP version 7.1 and supports PHP up to 8.2.
It requires PHP version 8.1 and supports PHP up to 8.5.
[Support Me](https://github.com/sponsors/dg)
@@ -39,7 +38,7 @@ Basic Usage
In variable `$schema` we have a validation schema (what exactly this means and how to create it we will say later) and in variable `$data` we have a data structure that we want to validate and normalize. This can be, for example, data sent by the user through an API, configuration file, etc.
The task is handled by the [Nette\Schema\Processor](https://api.nette.org/3.0/Nette/Schema/Processor.html) class, which processes the input and either returns normalized data or throws an [Nette\Schema\ValidationException](https://api.nette.org/3.0/Nette/Schema/ValidationException.html) exception on error.
The task is handled by the [Nette\Schema\Processor](https://api.nette.org/schema/master/Nette/Schema/Processor.html) class, which processes the input and either returns normalized data or throws an [Nette\Schema\ValidationException](https://api.nette.org/schema/master/Nette/Schema/ValidationException.html) exception on error.
```php
$processor = new Nette\Schema\Processor;
@@ -51,20 +50,20 @@ try {
}
```
Method `$e->getMessages()` returns array of all message strings and `$e->getMessageObjects()` return all messages as [Nette\Schema\Message](https://api.nette.org/3.1/Nette/Schema/Message.html) objects.
Method `$e->getMessages()` returns array of all message strings and `$e->getMessageObjects()` return all messages as [Nette\Schema\Message](https://api.nette.org/schema/master/Nette/Schema/Message.html) objects.
Defining Schema
---------------
And now let's create a schema. The class [Nette\Schema\Expect](https://api.nette.org/3.0/Nette/Schema/Expect.html) is used to define it, we actually define expectations of what the data should look like. Let's say that the input data must be a structure (e.g. an array) containing elements `processRefund` of type bool and `refundAmount` of type int.
And now let's create a schema. The class [Nette\Schema\Expect](https://api.nette.org/schema/master/Nette/Schema/Expect.html) is used to define it, we actually define expectations of what the data should look like. Let's say that the input data must be a structure (e.g. an array) containing elements `processRefund` of type bool and `refundAmount` of type int.
```php
use Nette\Schema\Expect;
$schema = Expect::structure([
'processRefund' => Expect::bool(),
'refundAmount' => Expect::int(),
'processRefund' => Expect::bool(),
'refundAmount' => Expect::int(),
]);
```
@@ -74,8 +73,8 @@ Lets send the following data for validation:
```php
$data = [
'processRefund' => true,
'refundAmount' => 17,
'processRefund' => true,
'refundAmount' => 17,
];
$normalized = $processor->process($schema, $data); // OK, it passes
@@ -87,7 +86,7 @@ All elements of the structure are optional and have a default value `null`. Exam
```php
$data = [
'refundAmount' => 17,
'refundAmount' => 17,
];
$normalized = $processor->process($schema, $data); // OK, it passes
@@ -102,8 +101,8 @@ And what if we wanted to accept `1` and `0` besides booleans? Then we list the a
```php
$schema = Expect::structure([
'processRefund' => Expect::anyOf(true, false, 1, 0)->castTo('bool'),
'refundAmount' => Expect::int(),
'processRefund' => Expect::anyOf(true, false, 1, 0)->castTo('bool'),
'refundAmount' => Expect::int(),
]);
$normalized = $processor->process($schema, $data);
@@ -113,7 +112,6 @@ is_bool($normalized->processRefund); // true
Now you know the basics of how the schema is defined and how the individual elements of the structure behave. We will now show what all the other elements can be used in defining a schema.
Data Types: type()
------------------
@@ -152,6 +150,15 @@ $processor->process($schema, ['a' => 'hello', 'b' => 'world']); // OK
$processor->process($schema, ['key' => 123]); // ERROR: 123 is not a string
```
The second parameter can be used to specify keys (since version 1.2):
```php
$schema = Expect::arrayOf('string', 'int');
$processor->process($schema, ['hello', 'world']); // OK
$processor->process($schema, ['a' => 'hello']); // ERROR: 'a' is not int
```
The list is an indexed array:
```php
@@ -169,7 +176,7 @@ The parameter can also be a schema, so we can write:
Expect::arrayOf(Expect::bool())
```
The default value is an empty array. If you specify default value, it will be merged with the passed data. This can be disabled using `mergeDefaults(false)`.
The default value is an empty array. If you specify a default value, it will be merged with the passed data. This can be disabled using `mergeDefaults(false)`.
Enumeration: anyOf()
@@ -179,7 +186,7 @@ Enumeration: anyOf()
```php
$schema = Expect::listOf(
Expect::anyOf('a', true, null)
Expect::anyOf('a', true, null),
);
$processor->process($schema, ['a', true, null, 'a']); // OK
@@ -190,14 +197,21 @@ The enumeration elements can also be schemas:
```php
$schema = Expect::listOf(
Expect::anyOf(Expect::string(), true, null)
Expect::anyOf(Expect::string(), true, null),
);
$processor->process($schema, ['foo', true, null, 'bar']); // OK
$processor->process($schema, [123]); // ERROR
```
The default value is `null`.
The `anyOf()` method accepts variants as individual parameters, not as array. To pass it an array of values, use the unpacking operator `anyOf(...$variants)`.
The default value is `null`. Use the `firstIsDefault()` method to make the first element the default:
```php
// default is 'hello'
Expect::anyOf(Expect::string('hello'), true, null)->firstIsDefault();
```
Structures
@@ -216,12 +230,24 @@ $schema = Expect::structure([
]);
$processor->process($schema, ['optional' => '']);
// ERROR: item 'required' is missing
// ERROR: option 'required' is missing
$processor->process($schema, ['required' => 'foo']);
// OK, returns {'required' => 'foo', 'optional' => null}
```
If you do not want to output properties with only a default value, use `skipDefaults()`:
```php
$schema = Expect::structure([
'required' => Expect::string()->required(),
'optional' => Expect::string(),
])->skipDefaults();
$processor->process($schema, ['required' => 'foo']);
// OK, returns {'required' => 'foo'}
```
Although `null` is the default value of the `optional` property, it is not allowed in the input data (the value must be a string). Properties accepting `null` are defined using `nullable()`:
```php
@@ -259,10 +285,11 @@ $processor->process($schema, ['additional' => 1]); // OK
$processor->process($schema, ['additional' => true]); // ERROR
```
Deprecations
------------
You can deprecate property using the `deprecated([string $message])` method. Deprecation notices are returned by `$processor->getWarnings()` (since v1.1):
You can deprecate property using the `deprecated([string $message])` method. Deprecation notices are returned by `$processor->getWarnings()`:
```php
$schema = Expect::structure([
@@ -273,6 +300,7 @@ $processor->process($schema, ['old' => 1]); // OK
$processor->getWarnings(); // ["The item 'old' is deprecated"]
```
Ranges: min() max()
-------------------
@@ -322,7 +350,7 @@ Custom Assertions: assert()
You can add any other restrictions using `assert(callable $fn)`.
```php
$countIsEven = function ($v) { return count($v) % 2 === 0; };
$countIsEven = fn($v) => count($v) % 2 === 0;
$schema = Expect::arrayOf('string')
->assert($countIsEven); // the count must be even
@@ -337,7 +365,7 @@ Or
Expect::string()->assert('is_file'); // the file must exist
```
You can add your own description for each assertions. It will be part of the error message.
You can add your own description for each assertion. It will be part of the error message.
```php
$schema = Expect::arrayOf('string')
@@ -347,7 +375,106 @@ $processor->process($schema, ['a', 'b', 'c']);
// Failed assertion "Even items in array" for item with value array.
```
The method can be called repeatedly to add more assertions.
The method can be called repeatedly to add multiple constraints. It can be intermixed with calls to `transform()` and `castTo()`.
Transformation: transform()
---------------------------
Successfully validated data can be modified using a custom function:
```php
// conversion to uppercase:
Expect::string()->transform(fn(string $s) => strtoupper($s));
```
The method can be called repeatedly to add multiple transformations. It can be intermixed with calls to `assert()` and `castTo()`. The operations will be executed in the order in which they are declared:
```php
Expect::type('string|int')
->castTo('string')
->assert('ctype_lower', 'All characters must be lowercased')
->transform(fn(string $s) => strtoupper($s)); // conversion to uppercase
```
The `transform()` method can both transform and validate the value simultaneously. This is often simpler and less redundant than chaining `transform()` and `assert()`. For this purpose, the function receives a [Nette\Schema\Context](https://api.nette.org/schema/master/Nette/Schema/Context.html) object with an `addError()` method, which can be used to add information about validation issues:
```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);
});
```
Casting: castTo()
-----------------
Successfully validated data can be cast:
```php
Expect::scalar()->castTo('string');
```
In addition to native PHP types, you can also cast to classes. It distinguishes whether it is a simple class without a constructor or a class with a constructor. If the class has no constructor, an instance of it is created and all elements of the structure are written to its properties:
```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
```
If the class has a constructor, the elements of the structure are passed as named parameters to the constructor:
```php
class Info
{
public function __construct(
public bool $processRefund,
public int $refundAmount,
) {
}
}
// creates $obj = new Info(processRefund: ..., refundAmount: ...)
```
Casting combined with a scalar parameter creates an object and passes the value as the sole parameter to the constructor:
```php
Expect::string()->castTo(DateTime::class);
// creates new DateTime(...)
```
Normalization: before()
-----------------------
Prior to the validation itself, the data can be normalized using the method `before()`. As an example, let's have an element that must be an array of strings (eg `['a', 'b', 'c']`), but receives input in the form of a string `a b c`:
```php
$explode = fn($v) => explode(' ', $v);
$schema = Expect::arrayOf('string')
->before($explode);
$normalized = $processor->process($schema, 'a b c');
// OK, returns ['a', 'b', 'c']
```
Mapping to Objects: from()
@@ -407,35 +534,3 @@ $schema = Expect::from(new Config, [
'name' => Expect::string()->pattern('\w:.*'),
]);
```
Casting: castTo()
-----------------
Successfully validated data can be cast:
```php
Expect::scalar()->castTo('string');
```
In addition to native PHP types, you can also cast to classes:
```php
Expect::scalar()->castTo('AddressEntity');
```
Normalization: before()
-----------------------
Prior to the validation itself, the data can be normalized using the method `before()`. As an example, let's have an element that must be an array of strings (eg `['a', 'b', 'c']`), but receives input in the form of a string `a b c`:
```php
$explode = function ($v) { return explode(' ', $v); };
$schema = Expect::arrayOf('string')
->before($explode);
$normalized = $processor->process($schema, 'a b c');
// OK, returns ['a', 'b', 'c']
```