1. <?php
  2. /**
  3. * Matches patterns against datasets with defensive checks.
  4. *
  5. * @param array $dataset The dataset to search within.
  6. * @param array $patterns An array of patterns to match. Each pattern should be an array of conditions.
  7. * @return array An array of matching data points.
  8. */
  9. function matchPatterns(array $dataset, array $patterns): array
  10. {
  11. $matches = [];
  12. // Defensive check: Ensure dataset is an array
  13. if (!is_array($dataset)) {
  14. error_log("Error: Dataset must be an array.");
  15. return [];
  16. }
  17. // Defensive check: Ensure patterns is an array
  18. if (!is_array($patterns)) {
  19. error_log("Error: Patterns must be an array.");
  20. return [];
  21. }
  22. foreach ($dataset as $dataPoint) {
  23. $isMatch = true;
  24. foreach ($patterns as $pattern) {
  25. // Defensive check: Ensure pattern is an array
  26. if (!is_array($pattern)) {
  27. error_log("Error: Each pattern must be an array.");
  28. $isMatch = false; // Skip this pattern if it's invalid.
  29. continue;
  30. }
  31. $match = true;
  32. foreach ($pattern as $condition) {
  33. // Defensive check: Ensure condition is an array or scalar
  34. if (!is_array($condition) && !is_scalar($condition)) {
  35. error_log("Error: Each condition must be an array or scalar.");
  36. $match = false;
  37. break; // Stop checking this pattern if a condition is invalid.
  38. }
  39. // Apply condition. Handle different condition types.
  40. if (is_array($condition)) {
  41. //Example using array_intersect
  42. if (!array_intersect($dataPoint, $condition)) {
  43. $match = false;
  44. break;
  45. }
  46. } else {
  47. //Simple scalar comparison
  48. if ($condition !== $dataPoint) {
  49. $match = false;
  50. break;
  51. }
  52. }
  53. }
  54. if (!$match) {
  55. $isMatch = false;
  56. break; // Stop checking patterns if one fails.
  57. }
  58. }
  59. if ($isMatch) {
  60. $matches[] = $dataPoint;
  61. }
  62. }
  63. return $matches;
  64. }
  65. //Example Usage:
  66. /*
  67. $data = [
  68. ['name' => 'Alice', 'age' => 30, 'city' => 'New York'],
  69. ['name' => 'Bob', 'age' => 25, 'city' => 'London'],
  70. ['name' => 'Charlie', 'age' => 30, 'city' => 'Paris']
  71. ];
  72. $patterns = [
  73. ['age' => 30], //Match people with age 30
  74. ['city' => 'London'], //Match people from London
  75. ['age' => 25, 'city' => 'London'] //Match people with age 25 from London
  76. ];
  77. $matchingData = matchPatterns($data, $patterns);
  78. print_r($matchingData);
  79. */
  80. ?>

Add your comment