<?php
/**
* CLI tool to check constraints of collections (arrays/lists).
*
* Usage: php check_constraints.php <collection_type> <constraint_name> <constraint_value> <collection_file>
*
* Example: php check_constraints.php array min 10 data.txt
*/
if (count($argv) !== 4) {
echo "Usage: php check_constraints.php <collection_type> <constraint_name> <constraint_value> <collection_file>\n";
exit(1);
}
$collection_type = $argv[1];
$constraint_name = $argv[2];
$constraint_value = $argv[3];
$collection_file = $argv[4];
if ($collection_type !== 'array' && $collection_type !== 'list') {
echo "Error: Collection type must be 'array' or 'list'.\n";
exit(1);
}
if (!file_exists($collection_file)) {
echo "Error: Collection file '$collection_file' not found.\n";
exit(1);
}
$collection = json_decode(file_get_contents($collection_file), true);
if ($collection === null) {
echo "Error: Could not decode JSON from '$collection_file'.\n";
exit(1);
}
try {
if ($collection_type === 'array') {
if (!is_array($collection)) {
echo "Error: '$collection_file' is not an array.\n";
exit(1);
}
if (array_key_exists($constraint_name, $collection)) {
if ($collection[$constraint_name] !== $constraint_value) {
echo "Constraint '$constraint_name' failed: Expected '$constraint_value', got '" . $collection[$constraint_name] . "'.\n";
exit(1);
}
} else {
echo "Constraint '$constraint_name' not found in '$collection_file'.\n";
exit(1);
}
} elseif ($collection_type === 'list') {
if (!is_array($collection)) {
echo "Error: '$collection_file' is not a list (array).\n";
exit(1);
}
$constraint_found = false;
foreach ($collection as $item) {
if ($item === $constraint_value) {
$constraint_found = true;
}
}
if (!$constraint_found) {
echo "Constraint '$constraint_name' failed: Expected '$constraint_value', not found in '$collection_file'.\n";
exit(1);
}
}
echo "Constraint '$constraint_name' passed in '$collection_file'.\n";
exit(0);
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
exit(1);
}
?>
Add your comment