Lesser known WordPress function to validate data structures

We validate data all the time. In programming, as in all areas of life, what we get is not always what we expect.

Let's take one specific case where we use validation: when constructing objects.

Painter::fromArray([
// ...
]);

PHP already offers functions to assert things, but many use dedicated libraries like Webmozart Assert or Respect\Validation. Me too! They are more convenient to use, and they are more powerful.

But if you are working with WordPress, there is a "WordPress-specific" solution that sits somewhere between the "native PHP" and libraries regarding convenience and power.

It's the rest_validate_object_value_from_schema function. It's something worth considering before requiring an extra dependency.

The function's name gives the impression that it is "REST API specific", but that's not the case.

Imagine that, for some reason, the Painter, besides the name, needs the favorite color in HEX format and possibly the name of the favorite artists.

Painter::fromArray([
'firstName' => 'John',
'lastName' => 'Doe',
'favoriteColor' => '#000',
'favoriteArtists' => ['Picasso', 'Salvador Dalí']
]);

How would you write the validation in "plain PHP"?

Here's how it might look using the rest_validate_object_value_from_schema:

class Painter
{
public static function fromArray(array $data): self
{
$validationResult = rest_validate_object_value_from_schema(
$data,
[
'properties' => [
'firstName' => [
'type' => 'string',
'required' => true,
],
'lastName' => [
'type' => 'string',
'required' => true,
],
'favoriteColor' => [
'type' => 'string',
'format' => 'hex-color',
'required' => true,
],
'favoriteArtists' => [
'type' => 'array',
'items' => [
'type' => 'string'
]
]
],
],
''
);
 
if (is_wp_error($validationResult)) {
throw new InvalidArgumentException(
// ...
);
}
 
return new self(
// ...
);
}
}

It's pretty readable and understandable at first sight.

If you want to keep the validation code inside the factory method or move it to a dedicated method or a class, that's up to you. Lately, I prefer having dedicated validation/assertion classes.

You can refer to the REST API Schema page to check the validation rules you can use.