1. <?php
  2. /**
  3. * Indexes content of entries for quick fixes using a configuration file.
  4. *
  5. * @param string $config_file Path to the configuration file.
  6. * @param array $entries Array of entries to index. Each entry should be an associative array with a 'content' key.
  7. * @return array Indexed entries.
  8. */
  9. function indexEntries(string $config_file, array $entries): array
  10. {
  11. // Load configuration.
  12. $config = loadConfig($config_file);
  13. if (empty($entries)) {
  14. return []; // Return empty array if no entries provided.
  15. }
  16. // Create an index array.
  17. $index = [];
  18. foreach ($entries as $entry) {
  19. if (isset($entry['content']) && is_string($entry['content'])) {
  20. $content = strtolower($entry['content']); // Convert to lowercase for case-insensitive indexing.
  21. $terms = explode(' ', trim($content)); // Split content into terms.
  22. foreach ($terms as $term) {
  23. if (strlen($term) > 0) {
  24. if (!isset($index[$term])) {
  25. $index[$term] = [];
  26. }
  27. if (!in_array(array_key_exists($entry['id'], $index[$term]), $index[$term])) {
  28. $index[$term][] = $entry['id'];
  29. }
  30. }
  31. }
  32. }
  33. }
  34. return $index;
  35. }
  36. /**
  37. * Loads configuration from a file.
  38. *
  39. * @param string $file_path Path to the configuration file.
  40. * @return array Configuration data.
  41. */
  42. function loadConfig(string $file_path): array
  43. {
  44. if (file_exists($file_path)) {
  45. $config = json_decode(file_get_contents($file_path), true);
  46. if (json_last_error() !== JSON_ERROR_NONE) {
  47. error_log("Error decoding config file: " . json_last_error_msg());
  48. return [];
  49. }
  50. return $config;
  51. } else {
  52. error_log("Config file not found: " . $file_path);
  53. return [];
  54. }
  55. }
  56. // Example usage (for testing):
  57. /*
  58. $entries = [
  59. ['id' => 1, 'content' => 'This is a test entry.'],
  60. ['id' => 2, 'content' => 'Another test entry with some different words.'],
  61. ['id' => 3, 'content' => 'This is a test entry.'],
  62. ];
  63. $config_file = 'config.json'; // Create a config.json file
  64. // Create a dummy config.json file for testing
  65. $config = [
  66. 'index_word_length_min' => 2,
  67. 'index_word_length_max' => 10,
  68. ];
  69. file_put_contents($config_file, json_encode($config));
  70. $index = indexEntries($config_file, $entries);
  71. print_r($index);
  72. */
  73. ?>

Add your comment