JsonType
in package
JsonType matches JSON structures against templates.
You can specify the type of fields in JSON or add additional validation rules.
JsonType is used by REST module in seeResponseMatchesJsonType
and dontSeeResponseMatchesJsonType
methods.
Usage example:
<?php
$jsonType = new JsonType(['name' => 'davert', 'id' => 1]);
$jsonType->matches([
'name' => 'string:!empty',
'id' => 'integer:>0|string:>0',
]); // => true
$jsonType->matches([
'id' => 'string',
]); // => `id: 1` is not of type string
?>
Class JsonType
Table of Contents
Properties
- $customFilters : mixed
- $jsonArray : mixed
Methods
- __construct() : mixed
- Creates instance of JsonType Pass an array or `\Codeception\Util\JsonArray` with data.
- addCustomFilter() : mixed
- Adds custom filter to JsonType list.
- cleanCustomFilters() : mixed
- Removes all custom filters
- matches() : bool|string
- Checks data against passed JsonType.
- matchFilter() : mixed
- typeComparison() : mixed
Properties
$customFilters
protected
static mixed
$customFilters
= []
$jsonArray
protected
mixed
$jsonArray
Methods
__construct()
Creates instance of JsonType Pass an array or `\Codeception\Util\JsonArray` with data.
public
__construct(mixed $jsonArray) : mixed
If non-associative array is passed - the very first element of it will be used for matching.
Parameters
- $jsonArray : mixed
-
array|\Codeception\Util\JsonArray
addCustomFilter()
Adds custom filter to JsonType list.
public
static addCustomFilter(mixed $name, callable $callable) : mixed
You should specify a name and parameters of a filter.
Example:
<?php
JsonType::addCustomFilter('slug', function($value) {
return strpos(' ', $value) !== false;
});
// => use it as 'string:slug'
// add custom function to matcher with `len($val)` syntax
// parameter matching patterns should be valid regex and start with `/` char
JsonType::addCustomFilter('/len\((.*?)\)/', function($value, $len) {
return strlen($value) == $len;
});
// use it as 'string:len(5)'
?>
Parameters
- $name : mixed
- $callable : callable
cleanCustomFilters()
Removes all custom filters
public
static cleanCustomFilters() : mixed
matches()
Checks data against passed JsonType.
public
matches(array<string|int, mixed> $jsonType) : bool|string
If matching fails function returns a string with a message describing failure.
On success returns true
.
Parameters
- $jsonType : array<string|int, mixed>
Return values
bool|stringmatchFilter()
protected
matchFilter(mixed $filter, mixed $value) : mixed
Parameters
- $filter : mixed
- $value : mixed
typeComparison()
protected
typeComparison(mixed $data, mixed $jsonType) : mixed
Parameters
- $data : mixed
- $jsonType : mixed