Skip to content
← Back to Snippets
Code

Interface-Like Array Contract Without Classes

Checks whether a procedural handler array provides the callable operations required by a small interface-like contract.

Purpose

Checks whether a procedural handler array provides the callable operations required by a small interface-like contract.

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-Like Array Contract Without Classes.
 *
 * Purpose:
 * Checks that a handler array contains the required callable operations.
 *
 * @param array $required_operations Operation names that must exist.
 * @param array $handlers Handler array keyed by operation name.
 * @return array Contract check result.
 */
function ogSnippetInterfaceLikeArrayContractWithoutClasses(array $required_operations, array $handlers): array {
	$result = array(
		'valid' => true,
		'missing' => array(),
		'not_callable' => array()
	);

	foreach ($required_operations as $operation_name) {
		$operation_name = trim((string) $operation_name);

		if ($operation_name === '') {
			continue;
		}

		if (array_key_exists($operation_name, $handlers) === false) {
			$result['valid'] = false;
			$result['missing'][] = $operation_name;
			continue;
		}

		if (is_callable($handlers[$operation_name]) === false) {
			$result['valid'] = false;
			$result['not_callable'][] = $operation_name;
		}
	}

	return $result;
}

$required_operations = array('scan', 'report', 'stand_down');
$alien_containment_handlers = array(
	'scan' => 'trim',
	'report' => 'strtoupper',
	'stand_down' => 'strtolower'
);

$handler_check = ogSnippetInterfaceLikeArrayContractWithoutClasses($required_operations, $alien_containment_handlers);

$handler_valid = 'no';

if ($handler_check['valid'] === true) {
	$handler_valid = 'yes';
}

echo 'Aliens handler contract valid: '.$handler_valid;