<?php
/**
* Matches patterns of lists for development purposes with error logging.
*
* @param array $patterns An array of patterns to match. Each pattern should be an array
* containing:
* - 'type': 'exact', 'contains', 'starts_with', 'ends_with'
* - 'value': The value to match against.
* - 'list_key': The key in the list to check (if applicable).
* - 'regex': Optional regex for more flexible matching (if type is 'contains').
* @param array $data The data containing the lists to check.
* @return array An array of matches, where each match is an array containing the pattern,
* the list key (if applicable), and the matched value.
*/
function matchListPatterns(array $patterns, array $data): array
{
$matches = [];
foreach ($patterns as $pattern) {
$type = $pattern['type'];
$value = $pattern['value'];
$listKey = $pattern['list_key'] ?? null; //Use null coalesce to handle missing list_key
$regex = $pattern['regex'] ?? null;
if (!is_array($pattern) || !isset($pattern['type']) || !isset($pattern['value'])) {
error_log("Invalid pattern format: " . print_r($pattern, true));
continue; // Skip invalid patterns
}
if (!is_array($data)) {
error_log("Data is not an array.");
continue; // Skip if data is not an array
}
foreach ($data as $listKeyData => $list) {
if ($listKey !== null && array_key_exists($listKey, $list)) {
$listValue = $list[$listKey];
} else {
$listValue = $list; //Use the whole list if listKey is not specified
}
try {
switch ($type) {
case 'exact':
if ($listValue === $value) {
$matches[] = [
'pattern' => $pattern,
'list_key' => $listKey,
'matched_value' => $listValue,
];
break;
}
break;
case 'contains':
if (strpos($listValue, $value) !== false) {
$matches[] = [
'pattern' => $pattern,
'list_key' => $listKey,
'matched_value' => $listValue,
];
break;
}
break;
case 'starts_with':
if (strpos($listValue, $value . '') === 0) {
$matches[] = [
'pattern' => $pattern,
'list_key' => $listKey,
'matched_value' => $listValue,
];
break;
}
break;
case 'ends_with':
if (substr($listValue, -strlen($value)) === $value) {
$matches[] = [
'pattern' => $pattern,
'list_key' => $listKey,
'matched_value' => $listValue,
];
break;
}
break;
case 'regex':
if (preg_match($regex, $listValue)) {
$matches[] = [
'pattern' => $pattern,
'list_key' => $listKey,
'matched_value' => $listValue,
];
break;
}
break;
default:
error_log("Invalid pattern type: " . $type);
break;
}
} catch (Exception $e) {
error_log("Error during pattern matching: " . $e->getMessage());
}
}
}
return $matches;
}
// Example usage (for development)
$patterns = [
['type' => 'exact', 'value' => 'apple', 'list_key' => 'fruit'],
['type' => 'contains', 'value' => 'ing', 'list_key' => 'verb'],
['type' => 'starts_with', 'value' => 'b', 'list_key' => 'color'],
Add your comment