PageRenderTime 50ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/vendor/gedmo/doctrine-extensions/lib/Gedmo/Translatable/Query/TreeWalker/TranslationWalker.php

https://bitbucket.org/hanutimes/hanutimes
PHP | 411 lines | 245 code | 34 blank | 132 comment | 32 complexity | cd95b56209fa674b4d8a28d4942512db MD5 | raw file
  1. <?php
  2. namespace Gedmo\Translatable\Query\TreeWalker;
  3. use Gedmo\Translatable\Mapping\Event\Adapter\ORM as TranslatableEventAdapter;
  4. use Gedmo\Translatable\TranslatableListener;
  5. use Doctrine\ORM\Query;
  6. use Doctrine\ORM\Query\SqlWalker;
  7. use Doctrine\ORM\Query\TreeWalkerAdapter;
  8. use Doctrine\ORM\Query\AST\SelectStatement;
  9. use Doctrine\ORM\Query\Exec\SingleSelectExecutor;
  10. use Doctrine\ORM\Query\AST\RangeVariableDeclaration;
  11. use Doctrine\ORM\Query\AST\Join;
  12. /**
  13. * The translation sql output walker makes it possible
  14. * to translate all query components during single query.
  15. * It works with any select query, any hydration method.
  16. *
  17. * Behind the scenes, during the object hydration it forces
  18. * custom hydrator in order to interact with TranslatableListener
  19. * and skip postLoad event which would couse automatic retranslation
  20. * of the fields.
  21. *
  22. * @author Gediminas Morkevicius <gediminas.morkevicius@gmail.com>
  23. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  24. */
  25. class TranslationWalker extends SqlWalker
  26. {
  27. /**
  28. * Name for translation fallback hint
  29. *
  30. * @internal
  31. */
  32. const HINT_TRANSLATION_FALLBACKS = '__gedmo.translatable.stored.fallbacks';
  33. /**
  34. * Customized object hydrator name
  35. *
  36. * @internal
  37. */
  38. const HYDRATE_OBJECT_TRANSLATION = '__gedmo.translatable.object.hydrator';
  39. /**
  40. * Customized object hydrator name
  41. *
  42. * @internal
  43. */
  44. const HYDRATE_SIMPLE_OBJECT_TRANSLATION = '__gedmo.translatable.simple_object.hydrator';
  45. /**
  46. * Stores all component references from select clause
  47. *
  48. * @var array
  49. */
  50. private $translatedComponents = array();
  51. /**
  52. * DBAL database platform
  53. *
  54. * @var Doctrine\DBAL\Platforms\AbstractPlatform
  55. */
  56. private $platform;
  57. /**
  58. * DBAL database connection
  59. *
  60. * @var Doctrine\DBAL\Connection
  61. */
  62. private $conn;
  63. /**
  64. * List of aliases to replace with translation
  65. * content reference
  66. *
  67. * @var array
  68. */
  69. private $replacements = array();
  70. /**
  71. * List of joins for translated components in query
  72. *
  73. * @var array
  74. */
  75. private $components = array();
  76. /**
  77. * {@inheritDoc}
  78. */
  79. public function __construct($query, $parserResult, array $queryComponents)
  80. {
  81. parent::__construct($query, $parserResult, $queryComponents);
  82. $this->conn = $this->getConnection();
  83. $this->platform = $this->getConnection()->getDatabasePlatform();
  84. $this->listener = $this->getTranslatableListener();
  85. $this->extractTranslatedComponents($queryComponents);
  86. }
  87. /**
  88. * {@inheritDoc}
  89. */
  90. public function getExecutor($AST)
  91. {
  92. if (!$AST instanceof SelectStatement) {
  93. throw new \Gedmo\Exception\UnexpectedValueException('Translation walker should be used only on select statement');
  94. }
  95. $this->prepareTranslatedComponents();
  96. return new SingleSelectExecutor($AST, $this);
  97. }
  98. /**
  99. * {@inheritDoc}
  100. */
  101. public function walkSelectStatement(SelectStatement $AST)
  102. {
  103. $result = parent::walkSelectStatement($AST);
  104. if (!count($this->translatedComponents)) {
  105. return $result;
  106. }
  107. $hydrationMode = $this->getQuery()->getHydrationMode();
  108. if ($hydrationMode === Query::HYDRATE_OBJECT) {
  109. $this->getQuery()->setHydrationMode(self::HYDRATE_OBJECT_TRANSLATION);
  110. $this->getEntityManager()->getConfiguration()->addCustomHydrationMode(
  111. self::HYDRATE_OBJECT_TRANSLATION,
  112. 'Gedmo\\Translatable\\Hydrator\\ORM\\ObjectHydrator'
  113. );
  114. $this->getQuery()->setHint(Query::HINT_REFRESH, true);
  115. } elseif ($hydrationMode === Query::HYDRATE_SIMPLEOBJECT) {
  116. $this->getQuery()->setHydrationMode(self::HYDRATE_SIMPLE_OBJECT_TRANSLATION);
  117. $this->getEntityManager()->getConfiguration()->addCustomHydrationMode(
  118. self::HYDRATE_SIMPLE_OBJECT_TRANSLATION,
  119. 'Gedmo\\Translatable\\Hydrator\\ORM\\SimpleObjectHydrator'
  120. );
  121. $this->getQuery()->setHint(Query::HINT_REFRESH, true);
  122. }
  123. return $result;
  124. }
  125. /**
  126. * {@inheritDoc}
  127. */
  128. public function walkSelectClause($selectClause)
  129. {
  130. $result = parent::walkSelectClause($selectClause);
  131. $result = $this->replace($this->replacements, $result);
  132. return $result;
  133. }
  134. /**
  135. * {@inheritDoc}
  136. */
  137. public function walkFromClause($fromClause)
  138. {
  139. $result = parent::walkFromClause($fromClause);
  140. $result .= $this->joinTranslations($fromClause);
  141. return $result;
  142. }
  143. /**
  144. * {@inheritDoc}
  145. */
  146. public function walkWhereClause($whereClause)
  147. {
  148. $result = parent::walkWhereClause($whereClause);
  149. return $this->replace($this->replacements, $result);
  150. }
  151. /**
  152. * {@inheritDoc}
  153. */
  154. public function walkHavingClause($havingClause)
  155. {
  156. $result = parent::walkHavingClause($havingClause);
  157. return $this->replace($this->replacements, $result);
  158. }
  159. /**
  160. * {@inheritDoc}
  161. */
  162. public function walkOrderByClause($orderByClause)
  163. {
  164. $result = parent::walkOrderByClause($orderByClause);
  165. return $this->replace($this->replacements, $result);
  166. }
  167. /**
  168. * {@inheritDoc}
  169. */
  170. public function walkSubselect($subselect)
  171. {
  172. $result = parent::walkSubselect($subselect);
  173. return $result;
  174. }
  175. /**
  176. * {@inheritDoc}
  177. */
  178. public function walkSubselectFromClause($subselectFromClause)
  179. {
  180. $result = parent::walkSubselectFromClause($subselectFromClause);
  181. $result .= $this->joinTranslations($subselectFromClause);
  182. return $result;
  183. }
  184. /**
  185. * {@inheritDoc}
  186. */
  187. public function walkSimpleSelectClause($simpleSelectClause)
  188. {
  189. $result = parent::walkSimpleSelectClause($simpleSelectClause);
  190. return $this->replace($this->replacements, $result);
  191. }
  192. /**
  193. * Walks from clause, and creates translation joins
  194. * for the translated components
  195. *
  196. * @param Doctrine\ORM\Query\AST\FromClause $from
  197. * @return string
  198. */
  199. private function joinTranslations($from)
  200. {
  201. $result = '';
  202. foreach ($from->identificationVariableDeclarations as $decl) {
  203. if ($decl->rangeVariableDeclaration instanceof RangeVariableDeclaration) {
  204. if (isset($this->components[$decl->rangeVariableDeclaration->aliasIdentificationVariable])) {
  205. $result .= $this->components[$decl->rangeVariableDeclaration->aliasIdentificationVariable];
  206. }
  207. }
  208. if (isset($decl->joinVariableDeclarations)) {
  209. foreach ($decl->joinVariableDeclarations as $joinDecl) {
  210. if ($joinDecl->join instanceof Join) {
  211. if (isset($this->components[$joinDecl->join->aliasIdentificationVariable])) {
  212. $result .= $this->components[$joinDecl->join->aliasIdentificationVariable];
  213. }
  214. }
  215. }
  216. } else {
  217. // based on new changes
  218. foreach ($decl->joins as $join) {
  219. if ($join instanceof Join) {
  220. if (isset($this->components[$join->joinAssociationDeclaration->aliasIdentificationVariable])) {
  221. $result .= $this->components[$join->joinAssociationDeclaration->aliasIdentificationVariable];
  222. }
  223. }
  224. }
  225. }
  226. }
  227. return $result;
  228. }
  229. /**
  230. * Creates a left join list for translations
  231. * on used query components
  232. *
  233. * @todo: make it cleaner
  234. * @return string
  235. */
  236. private function prepareTranslatedComponents()
  237. {
  238. $q = $this->getQuery();
  239. $locale = $q->getHint(TranslatableListener::HINT_TRANSLATABLE_LOCALE);
  240. if (!$locale) {
  241. // use from listener
  242. $locale = $this->listener->getListenerLocale();
  243. }
  244. $defaultLocale = $this->listener->getDefaultLocale();
  245. if ($locale === $defaultLocale && !$this->listener->getPersistDefaultLocaleTranslation()) {
  246. // Skip preparation as there's no need to translate anything
  247. return;
  248. }
  249. $em = $this->getEntityManager();
  250. $ea = new TranslatableEventAdapter;
  251. $ea->setEntityManager($em);
  252. $joinStrategy = $q->getHint(TranslatableListener::HINT_INNER_JOIN) ? 'INNER' : 'LEFT';
  253. foreach ($this->translatedComponents as $dqlAlias => $comp) {
  254. $meta = $comp['metadata'];
  255. $config = $this->listener->getConfiguration($em, $meta->name);
  256. $transClass = $this->listener->getTranslationClass($ea, $meta->name);
  257. $transMeta = $em->getClassMetadata($transClass);
  258. $transTable = $transMeta->getQuotedTableName($this->platform);
  259. foreach ($config['fields'] as $field) {
  260. $compTableName = $meta->getQuotedTableName($this->platform);
  261. $compTblAlias = $this->getSQLTableAlias($compTableName, $dqlAlias);
  262. $tblAlias = $this->getSQLTableAlias('trans'.$compTblAlias.$field);
  263. $sql = " {$joinStrategy} JOIN ".$transTable.' '.$tblAlias;
  264. $sql .= ' ON '.$tblAlias.'.'.$transMeta->getQuotedColumnName('locale', $this->platform)
  265. .' = '.$this->conn->quote($locale);
  266. $sql .= ' AND '.$tblAlias.'.'.$transMeta->getQuotedColumnName('field', $this->platform)
  267. .' = '.$this->conn->quote($field);
  268. $identifier = $meta->getSingleIdentifierFieldName();
  269. $idColName = $meta->getQuotedColumnName($identifier, $this->platform);
  270. if ($ea->usesPersonalTranslation($transClass)) {
  271. $sql .= ' AND '.$tblAlias.'.'.$transMeta->getSingleAssociationJoinColumnName('object')
  272. .' = '.$compTblAlias.'.'.$idColName;
  273. } else {
  274. $sql .= ' AND '.$tblAlias.'.'.$transMeta->getQuotedColumnName('objectClass', $this->platform)
  275. .' = '.$this->conn->quote($meta->name);
  276. $sql .= ' AND '.$tblAlias.'.'.$transMeta->getQuotedColumnName('foreignKey', $this->platform)
  277. .' = '.$compTblAlias.'.'.$idColName;
  278. }
  279. isset($this->components[$dqlAlias]) ? $this->components[$dqlAlias] .= $sql : $this->components[$dqlAlias] = $sql;
  280. $originalField = $compTblAlias.'.'.$meta->getQuotedColumnName($field, $this->platform);
  281. $substituteField = $tblAlias . '.' . $transMeta->getQuotedColumnName('content', $this->platform);
  282. // If original field is integer - treat translation as integer (for ORDER BY, WHERE, etc)
  283. $fieldMapping = $meta->getFieldMapping($field);
  284. if (in_array($fieldMapping["type"], array("integer", "bigint", "tinyint", "int"))) {
  285. $substituteField = 'CAST(' . $substituteField . ' AS SIGNED)';
  286. }
  287. // Fallback to original if was asked for
  288. if (($this->needsFallback() && (!isset($config['fallback'][$field]) || $config['fallback'][$field]))
  289. || (!$this->needsFallback() && isset($config['fallback'][$field]) && $config['fallback'][$field])
  290. ) {
  291. $substituteField = 'COALESCE('.$substituteField.', '.$originalField.')';
  292. }
  293. $this->replacements[$originalField] = $substituteField;
  294. }
  295. }
  296. }
  297. /**
  298. * Checks if translation fallbacks are needed
  299. *
  300. * @return boolean
  301. */
  302. private function needsFallback()
  303. {
  304. $q = $this->getQuery();
  305. $fallback = $q->getHint(TranslatableListener::HINT_FALLBACK);
  306. if (false === $fallback) {
  307. // non overrided
  308. $fallback = $this->listener->getTranslationFallback();
  309. }
  310. return (bool)$fallback
  311. && $q->getHydrationMode() !== Query::HYDRATE_SCALAR
  312. && $q->getHydrationMode() !== Query::HYDRATE_SINGLE_SCALAR;
  313. }
  314. /**
  315. * Search for translated components in the select clause
  316. *
  317. * @param array $queryComponents
  318. * @return void
  319. */
  320. private function extractTranslatedComponents(array $queryComponents)
  321. {
  322. $em = $this->getEntityManager();
  323. foreach ($queryComponents as $alias => $comp) {
  324. if (!isset($comp['metadata'])) {
  325. continue;
  326. }
  327. $meta = $comp['metadata'];
  328. $config = $this->listener->getConfiguration($em, $meta->name);
  329. if ($config && isset($config['fields'])) {
  330. $this->translatedComponents[$alias] = $comp;
  331. }
  332. }
  333. }
  334. /**
  335. * Get the currently used TranslatableListener
  336. *
  337. * @throws \Gedmo\Exception\RuntimeException - if listener is not found
  338. * @return TranslatableListener
  339. */
  340. private function getTranslatableListener()
  341. {
  342. $translatableListener = null;
  343. $em = $this->getEntityManager();
  344. foreach ($em->getEventManager()->getListeners() as $event => $listeners) {
  345. foreach ($listeners as $hash => $listener) {
  346. if ($listener instanceof TranslatableListener) {
  347. $translatableListener = $listener;
  348. break;
  349. }
  350. }
  351. if ($translatableListener) {
  352. break;
  353. }
  354. }
  355. if (is_null($translatableListener)) {
  356. throw new \Gedmo\Exception\RuntimeException('The translation listener could not be found');
  357. }
  358. return $translatableListener;
  359. }
  360. /**
  361. * Replaces given sql $str with required
  362. * results
  363. *
  364. * @param array $repl
  365. * @param string $str
  366. * @return string
  367. */
  368. private function replace(array $repl, $str)
  369. {
  370. foreach ($repl as $target => $result) {
  371. $str = preg_replace_callback('/(\s|\()('.$target.')(\s|\))/smi', function($m) use ($result) {
  372. return $m[1].$result.$m[3];
  373. }, $str);
  374. }
  375. return $str;
  376. }
  377. }