Schemas provide lightweight structural validation for loaded configuration arrays. They are intentionally smaller than full JSON Schema and are designed for simple application config checks.
Related pages:
Create a schema by extending AbstractConfigSchema.
use CommonPHP\Config\Contracts\AbstractConfigSchema;
final class AppConfigSchema extends AbstractConfigSchema
{
}
$schema = new AppConfigSchema([
'name' => 'required|string',
'debug' => 'boolean',
'database.host' => 'required|string',
'database.port' => 'required|integer',
]);Schemas can be passed to ConfigDefinition.
$provider->define('app', ConfigDefinition::file(
'config/app.json',
schema: $schema,
));use CommonPHP\Config\ConfigSchemaValidator;
$validator = new ConfigSchemaValidator();
$errors = $validator->validate($config, [
'name' => 'required|string',
]);
$validator->assertValid($config, [
'name' => 'required|string',
]);validate() returns a list of error messages. assertValid() throws ConfigValidationException when errors are present.
Rules can be compact strings:
[
'name' => 'required|string',
'debug' => 'boolean',
'timezone' => 'nullable|string',
]Supported rule tokens:
requiredoptionalnullable- type names such as
string,integer,boolean,array,list,scalar,object,callable,mixed, andnull - aliases
bool,int,double, andnumeric type:string,integerin:production,staging
Rules can also be arrays:
[
'name' => [
'required' => true,
'type' => 'string',
'pattern' => '/^[a-z0-9_-]+$/',
],
'env' => [
'type' => 'string',
'allowed' => ['production', 'staging'],
],
]Supported array keys:
requirednullabletypetypesallowedenumpatternrulescallback
Callbacks receive the value, field name, and full config array.
[
'database.port' => static function (mixed $value): bool {
return is_int($value) && $value > 0;
},
]Return true or null to pass, false for a generic error, or a non-empty string for a custom error message.