Interface Contract Array Without Abstract Classes
Validates an associative array against a required field contract without abstract classes or inheritance.
Purpose
Validates an associative array against a required field contract without abstract classes or inheritance.
Snippet details
ContextValidationLevelProductionCopy-and-paste statusMarked safe after review.Categories
- Forms and Validation
Code
<?php
/*
* Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
* Free for personal and internal use. Paid project use requires visible credit
* to Jeffery L. Paris. Corporate use requires a paid license fee unless a
* separate written license states otherwise.
*/
/**
* Interface Contract Array Without Abstract Classes.
*
* Purpose:
* Validates array data against a simple required-field contract.
*
* @param array $contract Required field names and expected scalar types.
* @param array $payload Data to validate.
* @return array Validation result with errors.
*/
function ogSnippetInterfaceContractArrayWithoutAbstractClasses(array $contract, array $payload): array {
$result = array(
'valid' => true,
'errors' => array()
);
foreach ($contract as $field_name => $expected_type) {
$field_name = trim((string) $field_name);
$expected_type = strtolower(trim((string) $expected_type));
if ($field_name === '') {
continue;
}
if (array_key_exists($field_name, $payload) === false) {
$result['valid'] = false;
$result['errors'][] = 'Missing field: '.$field_name;
continue;
}
$value = $payload[$field_name];
$type_matches = false;
if ($expected_type === 'string' && is_string($value) === true) {
$type_matches = true;
} elseif ($expected_type === 'integer' && is_int($value) === true) {
$type_matches = true;
} elseif ($expected_type === 'boolean' && is_bool($value) === true) {
$type_matches = true;
} elseif ($expected_type === 'array' && is_array($value) === true) {
$type_matches = true;
}
if ($type_matches === false) {
$result['valid'] = false;
$result['errors'][] = 'Invalid type for field: '.$field_name;
}
}
return $result;
}
$module_contract = array(
'callsign' => 'string',
'crew_count' => 'integer',
'active' => 'boolean'
);
$module_payload = array(
'callsign' => 'firefly-serenity',
'crew_count' => 9,
'active' => true
);
$contract_result = ogSnippetInterfaceContractArrayWithoutAbstractClasses($module_contract, $module_payload);
$contract_valid = 'no';
if ($contract_result['valid'] === true) {
$contract_valid = 'yes';
}
echo 'Firefly contract valid: '.$contract_valid;