1. <?php
  2. /**
  3. * CLI tool to check constraints of collections (arrays/lists).
  4. *
  5. * Usage: php check_constraints.php <collection_type> <constraint_name> <constraint_value> <collection_file>
  6. *
  7. * Example: php check_constraints.php array min 10 data.txt
  8. */
  9. if (count($argv) !== 4) {
  10. echo "Usage: php check_constraints.php <collection_type> <constraint_name> <constraint_value> <collection_file>\n";
  11. exit(1);
  12. }
  13. $collection_type = $argv[1];
  14. $constraint_name = $argv[2];
  15. $constraint_value = $argv[3];
  16. $collection_file = $argv[4];
  17. if ($collection_type !== 'array' && $collection_type !== 'list') {
  18. echo "Error: Collection type must be 'array' or 'list'.\n";
  19. exit(1);
  20. }
  21. if (!file_exists($collection_file)) {
  22. echo "Error: Collection file '$collection_file' not found.\n";
  23. exit(1);
  24. }
  25. $collection = json_decode(file_get_contents($collection_file), true);
  26. if ($collection === null) {
  27. echo "Error: Could not decode JSON from '$collection_file'.\n";
  28. exit(1);
  29. }
  30. try {
  31. if ($collection_type === 'array') {
  32. if (!is_array($collection)) {
  33. echo "Error: '$collection_file' is not an array.\n";
  34. exit(1);
  35. }
  36. if (array_key_exists($constraint_name, $collection)) {
  37. if ($collection[$constraint_name] !== $constraint_value) {
  38. echo "Constraint '$constraint_name' failed: Expected '$constraint_value', got '" . $collection[$constraint_name] . "'.\n";
  39. exit(1);
  40. }
  41. } else {
  42. echo "Constraint '$constraint_name' not found in '$collection_file'.\n";
  43. exit(1);
  44. }
  45. } elseif ($collection_type === 'list') {
  46. if (!is_array($collection)) {
  47. echo "Error: '$collection_file' is not a list (array).\n";
  48. exit(1);
  49. }
  50. $constraint_found = false;
  51. foreach ($collection as $item) {
  52. if ($item === $constraint_value) {
  53. $constraint_found = true;
  54. }
  55. }
  56. if (!$constraint_found) {
  57. echo "Constraint '$constraint_name' failed: Expected '$constraint_value', not found in '$collection_file'.\n";
  58. exit(1);
  59. }
  60. }
  61. echo "Constraint '$constraint_name' passed in '$collection_file'.\n";
  62. exit(0);
  63. } catch (Exception $e) {
  64. echo "Error: " . $e->getMessage() . "\n";
  65. exit(1);
  66. }
  67. ?>

Add your comment