From 6e26d2d1ca2095ff50f8b73e76f9d80b6bda492c Mon Sep 17 00:00:00 2001
From: mrded <mrded@556088.no-reply.drupal.org>
Date: Wed, 1 Apr 2015 10:24:54 +0100
Subject: [PATCH] Issue #2463541: synonyms_get_term_by_synonym() function is
 too slow

---
 synonyms.module | 32 +++++++++++++++-----------------
 1 file changed, 15 insertions(+), 17 deletions(-)

diff --git a/synonyms.module b/synonyms.module
index e3f07db..139c81b 100644
--- a/synonyms.module
+++ b/synonyms.module
@@ -351,26 +351,24 @@ function synonyms_autocomplete_validate($element, &$form_state) {
  *   found term, otherwise returns 0
  */
 function synonyms_get_term_by_synonym($name, $vocabulary, $parent = 0) {
-  $name = mb_strtoupper(trim($name), 'UTF-8');
+  $query = db_select('field_data_synonyms_synonyms', 's');
+  $query->fields('s', array('entity_id'));
+  $query->innerJoin('taxonomy_term_data', 't', 't.tid = s.entity_id');
+  $query->innerJoin('taxonomy_term_hierarchy', 'h', 'h.tid = s.entity_id');
 
-  $tree = taxonomy_get_tree($vocabulary->vid, $parent, NULL, TRUE);
-  foreach ($tree as $term) {
-    if (mb_strtoupper($term->name, 'UTF-8') == $name) {
-      return $term->tid;
-    }
+  $query->condition('t.vid', $vocabulary->vid);
+  $query->condition('h.parent', $parent);
+  $query->condition('s.synonyms_synonyms_value', $name, 'LIKE');
 
-    // We additionally scan through the synonyms.
-    $synonyms = synonyms_get_sanitized($term);
-    foreach ($synonyms as $item) {
-      if (mb_strtoupper($item, 'UTF-8') == $name) {
-        return $term->tid;
-      }
-    }
+  if ($tid = $query->execute()->fetchField()) {
+   return $tid;
+  }
+  elseif ($term = taxonomy_get_term_by_name($name, $vocabulary)) {
+    return $term->tid;
+  }
+  else {
+    return 0;
   }
-
-  // If we have reached down here, this means we haven't got any match
-  // as fallback we return 0.
-  return 0;
 }
 
 /**
-- 
1.9.5 (Apple Git-50.3)

