TagLike.php 8.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. <?php
  2. namespace Muzich\CoreBundle\Util;
  3. use Doctrine\Bundle\DoctrineBundle\Registry;
  4. use Muzich\CoreBundle\Util\StrictCanonicalizer;
  5. /**
  6. * Cette classe permet d'aider a la recherche de mot similaires a un mot
  7. *
  8. *
  9. */
  10. class TagLike
  11. {
  12. protected $registry;
  13. public function __construct(Registry $registry)
  14. {
  15. $this->registry = $registry;
  16. }
  17. /**
  18. * Ajoute le tag au début du tableau passé en paramètre si celui-ci
  19. * n'est pas a l'intérieur.
  20. *
  21. * @param array $array
  22. * @param Tag $tag
  23. * @return array
  24. */
  25. private function sort_addtop_if_isnt_in($array, $tag)
  26. {
  27. $in = false;
  28. for ($x=0;$x<=sizeof($array)-1;$x++)
  29. {
  30. if ($array[$x]['id'] == $tag['id'])
  31. {
  32. $in = true;
  33. break;
  34. }
  35. }
  36. if (!$in)
  37. {
  38. array_unshift($array, $tag);
  39. return $array;
  40. }
  41. return $array;
  42. }
  43. /**
  44. * Ajoute le tag a al fin du tableau passé en paramètre si celui-ci
  45. * n'est pas a l'intérieur.
  46. *
  47. * @param array $array
  48. * @param Tag $tag
  49. * @return array
  50. */
  51. private function sort_addbottom_if_isnt_in($array, $tag)
  52. {
  53. $in = false;
  54. for ($x=0;$x<=sizeof($array)-1;$x++)
  55. {
  56. if ($array[$x]['id'] == $tag['id'])
  57. {
  58. $in = true;
  59. break;
  60. }
  61. }
  62. if (!$in)
  63. {
  64. $array[] = $tag;
  65. return $array;
  66. }
  67. return $array;
  68. }
  69. /**
  70. * Construit un tableau de mot a partir du terme de recherche. Ces mots
  71. * permettrons la recherche de tags en base et le trie des tags trouvé.
  72. *
  73. * La déduction de ces mot est basé sur:
  74. * * Le remplacement des espaces par des tirets et inversement (virgules aussi)
  75. *
  76. * Et chaque mot doit dépasser deux caractères
  77. *
  78. * @param string $search
  79. * @return array
  80. */
  81. protected function getSearchWordsReplacing($search)
  82. {
  83. // En base les tags sont composé de mot a '-' ou a ' '.
  84. $words = array_unique(array(
  85. str_replace(' ', '-', $search),
  86. str_replace('-', ' ', $search),
  87. str_replace(',', ' ', $search),
  88. str_replace(', ', ' ', $search),
  89. str_replace(',', '-', $search),
  90. str_replace(', ', '-', $search),
  91. str_replace(' & ', ' AND ', $search)
  92. ));
  93. return $words;
  94. }
  95. /**
  96. * Construit un tableau de mot a partir du terme de recherche. Ces mots
  97. * permettrons la recherche de tags en base et le trie des tags trouvé.
  98. *
  99. * La déduction de ces mot est basé sur:
  100. * * La découpe du terme par espaces, tirets et virgules
  101. *
  102. * Et chaque mot doit dépasser deux caractères
  103. *
  104. * @param string $search
  105. */
  106. protected function getSearchWordsExploding($search)
  107. {
  108. $words = array_unique(array_merge(
  109. explode(' ', $search),
  110. explode('-', $search),
  111. explode('- ', $search),
  112. explode(' -', $search),
  113. explode(' - ', $search),
  114. explode(',', $search),
  115. explode(', ', $search),
  116. explode(' ,', $search),
  117. explode(' , ', $search)
  118. ));
  119. $words_filetereds = array();
  120. foreach ($words as $i => $word)
  121. {
  122. if (trim(strlen($word)) > 1)
  123. {
  124. $words_filetereds[] = trim($word);
  125. }
  126. }
  127. return $words_filetereds;
  128. }
  129. /**
  130. * Recherche en base les tags ressemblant a la recherche.
  131. *
  132. * @param array $words
  133. * @param int $user_id
  134. * @return array
  135. */
  136. protected function searchTags($words, $user_id)
  137. {
  138. $where = '';
  139. $params = array();
  140. foreach ($words as $i => $word)
  141. {
  142. if ($where == '')
  143. {
  144. $where .= 'WHERE UPPER(t.slug) LIKE :str'.$i;
  145. }
  146. else
  147. {
  148. $where .= ' OR UPPER(t.slug) LIKE :str'.$i;
  149. }
  150. $params['str'.$i] = '%'.$word.'%';
  151. }
  152. $params['uid'] = '%"'.$user_id.'"%';
  153. $tags_query = $this->registry->getEntityManager()->createQuery("
  154. SELECT t.name, t.slug, t.id FROM MuzichCoreBundle:Tag t
  155. $where
  156. AND (t.tomoderate = '0' OR t.tomoderate IS NULL
  157. OR t.privateids LIKE :uid)
  158. ORDER BY t.name ASC"
  159. )
  160. ->setParameters($params)
  161. ->getScalarResult()
  162. ;
  163. $tags = array();
  164. foreach ($tags_query as $tag)
  165. {
  166. $tags[] = array(
  167. 'name' => $tag['name'],
  168. 'id' => $tag['id'],
  169. 'slug' => $tag['slug']
  170. );
  171. }
  172. return $tags;
  173. }
  174. /**
  175. * Trie les tags de manière a ce que les tags les plus ressemblant a la
  176. * recherche soient au début du tableau.
  177. *
  178. * @param array $tags
  179. * @param array $search
  180. * @param array $words
  181. * @param array $words_replacing
  182. * @param array $words_exploding
  183. * @return array
  184. */
  185. protected function sortTags($tags, $search, $words, $words_replacing, $words_exploding)
  186. {
  187. $same_found = false;
  188. $tag_sorted = array();
  189. /*
  190. * Première passe: Pas plus de trois caractères différents de la recherche
  191. * On se base ici sur le recherche non découpé
  192. */
  193. foreach ($tags as $i => $tag)
  194. {
  195. foreach ($words_replacing as $word)
  196. {
  197. $word = trim($word);
  198. if (strlen($word) > 1)
  199. {
  200. if (
  201. strlen(str_replace($word, '', strtoupper($tag['slug']))) < 4
  202. // Si on tombe sur le même nom, il ne faut pas le mettre en haut maintenant
  203. // ou il se fera décallé vers le bas
  204. && $word != $search
  205. )
  206. {
  207. $tag_sorted = $this->sort_addtop_if_isnt_in($tag_sorted, $tag);
  208. }
  209. }
  210. }
  211. }
  212. /*
  213. * Pour une recherche en plusieurs mots, on cherche la similitude avec
  214. * des tags. De façon a ce que "dark psytrance" soit reconnue comme proche de
  215. * "psytrance dark".
  216. */
  217. if (count($words_exploding) > 1)
  218. {
  219. $tags_counteds = array();
  220. /*
  221. * Pour chaque mot qui compose la recherche on regarde si ce mot
  222. * est compris dans un des tags
  223. */
  224. foreach ($tags as $i => $tag)
  225. {
  226. foreach ($words_exploding as $word)
  227. {
  228. if (strpos(strtoupper($tag['slug']), $word) !== false)
  229. {
  230. $count = 1;
  231. if (array_key_exists($tag['id'], $tags_counteds))
  232. {
  233. $count = ($tags_counteds[$tag['id']]['count'])+1;
  234. }
  235. $tags_counteds[$tag['id']] = array(
  236. 'count' => $count,
  237. 'tag' => $tag
  238. );
  239. }
  240. }
  241. }
  242. /*
  243. * Maintenant que l'on a un tableau contenant les tags comportant au moins
  244. * un mot identique a recherche
  245. */
  246. foreach ($tags_counteds as $id => $counted)
  247. {
  248. // Si le tag a eu plus d'une fois le même mot
  249. if ($counted['count'] > 1)
  250. {
  251. // Ci-dessous on va chercher a voir si le tag et la recherche on le
  252. // même nombre de mots, si c'est le cas on pourra considérer cette
  253. // recherche comme lié a un tag connu.
  254. if (count($words_exploding) == count($this->getSearchWordsExploding($counted['tag']['slug'])))
  255. {
  256. $same_found = true;
  257. }
  258. // Cette verif permet de ne pas ajouter les tags qui n'ont qu'un mot
  259. // Si on ajouté ce tag maintenant il ne serais pas ajouté au controle en dessous
  260. // (nom identique) et donc pas au dessus.
  261. $tag_sorted = $this->sort_addtop_if_isnt_in($tag_sorted, $counted['tag']);
  262. }
  263. }
  264. }
  265. /*
  266. * On recherche maintenant les noms de tags identique a la recherche
  267. */
  268. foreach ($tags as $i => $tag)
  269. {
  270. foreach ($words_replacing as $word)
  271. {
  272. if ($word == strtoupper($tag['slug']))
  273. {
  274. // Ci-dessous on déduit si le mot est identique au tag .
  275. // De façon a ce que si c'est le cas, pouvoir dire:
  276. // oui le terme recherché est connu.
  277. if (in_array($word, $words_replacing))
  278. {
  279. $same_found = true;
  280. }
  281. $tag_sorted = $this->sort_addtop_if_isnt_in($tag_sorted, $tag);
  282. }
  283. }
  284. }
  285. foreach ($tags as $i => $tag)
  286. {
  287. $tag_sorted = $this->sort_addbottom_if_isnt_in($tag_sorted, $tag);
  288. }
  289. return array(
  290. 'tags' => $tag_sorted,
  291. 'same_found' => $same_found
  292. );
  293. }
  294. public function getSimilarTags($search, $user_id)
  295. {
  296. $canonicalizer = new StrictCanonicalizer();
  297. $search = strtoupper($canonicalizer->canonicalize(trim($search)));
  298. if (strlen($search) < 2)
  299. {
  300. // Le terme de recherche doit faire au moins 2 caractéres
  301. return array('tags' => array(), 'same_found' => false);
  302. }
  303. $words_e = $this->getSearchWordsExploding($search);
  304. $words_r = $this->getSearchWordsReplacing($search);
  305. $words = array_unique(array_merge($words_e, $words_r));
  306. $tags = $this->searchTags($words, $user_id);
  307. return $this->sortTags($tags, $search, $words, $words_r, $words_e);
  308. }
  309. }