| Conditions | 9 |
| Paths | 49 |
| Total Lines | 60 |
| Code Lines | 31 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 1 | ||
| Bugs | 0 | Features | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
| 1 | <?php |
||
| 57 | public function indexDocument( |
||
| 58 | array $fields, |
||
| 59 | array $terms = [], |
||
| 60 | ?string $language = null, |
||
| 61 | ): int { |
||
| 62 | if (!\class_exists(\XapianWritableDatabase::class)) { |
||
| 63 | throw new \RuntimeException('Xapian PHP extension is not loaded.'); |
||
| 64 | } |
||
| 65 | |||
| 66 | $db = $this->openWritableDatabase(); |
||
| 67 | |||
| 68 | $doc = new \XapianDocument(); |
||
| 69 | $termGen = new \XapianTermGenerator(); |
||
| 70 | |||
| 71 | $lang = $language ?: self::DEFAULT_LANGUAGE; |
||
| 72 | $stemmer = new \XapianStem($lang); |
||
| 73 | |||
| 74 | $termGen->set_stemmer($stemmer); |
||
| 75 | $termGen->set_document($doc); |
||
| 76 | |||
| 77 | // Index all field values as free-text (title, content, etc.) |
||
| 78 | foreach ($fields as $value) { |
||
| 79 | if ($value === null) { |
||
| 80 | continue; |
||
| 81 | } |
||
| 82 | |||
| 83 | if (!\is_string($value)) { |
||
| 84 | $value = (string) $value; |
||
| 85 | } |
||
| 86 | |||
| 87 | $termGen->index_text($value, 1); |
||
| 88 | } |
||
| 89 | |||
| 90 | // Add explicit terms if provided |
||
| 91 | foreach ($terms as $term) { |
||
| 92 | $term = (string) $term; |
||
| 93 | if ($term === '') { |
||
| 94 | continue; |
||
| 95 | } |
||
| 96 | |||
| 97 | $doc->add_term($term, 1); |
||
| 98 | } |
||
| 99 | |||
| 100 | // Store fields as serialized payload (compatible with the search service decode) |
||
| 101 | $doc->set_data(\serialize($fields)); |
||
| 102 | |||
| 103 | try { |
||
| 104 | $docId = $db->add_document($doc); |
||
| 105 | $db->flush(); |
||
| 106 | |||
| 107 | error_log('[Xapian] XapianIndexService::indexDocument: document added with docId=' |
||
| 108 | .var_export($docId, true) |
||
| 109 | ); |
||
| 110 | |||
| 111 | return $docId; |
||
| 112 | } catch (\Throwable $e) { |
||
| 113 | throw new \RuntimeException( |
||
| 114 | \sprintf('Failed to index document in Xapian: %s', $e->getMessage()), |
||
| 115 | 0, |
||
| 116 | $e |
||
| 117 | ); |
||
| 160 |