TranslateBehaviorTest.php 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  5. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  6. *
  7. * Licensed under The MIT License
  8. * For full copyright and license information, please see the LICENSE.txt
  9. * Redistributions of files must retain the above copyright notice.
  10. *
  11. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  12. * @link https://cakephp.org CakePHP(tm) Project
  13. * @since 3.0.0
  14. * @license https://opensource.org/licenses/mit-license.php MIT License
  15. */
  16. namespace Cake\Test\TestCase\ORM\Behavior;
  17. use Cake\Collection\Collection;
  18. use Cake\Datasource\EntityInterface;
  19. use Cake\I18n\I18n;
  20. use Cake\ORM\Entity;
  21. use Cake\ORM\Locator\TableLocator;
  22. use Cake\TestSuite\TestCase;
  23. use Cake\Validation\Validator;
  24. use TestApp\Model\Entity\TranslateArticle;
  25. use TestApp\Model\Table\I18nTable;
  26. /**
  27. * Translate behavior test case
  28. */
  29. class TranslateBehaviorTest extends TestCase
  30. {
  31. /**
  32. * fixtures
  33. *
  34. * @var array
  35. */
  36. public $fixtures = [
  37. 'core.Articles',
  38. 'core.Authors',
  39. 'core.Groups',
  40. 'core.SpecialTags',
  41. 'core.Tags',
  42. 'core.Comments',
  43. 'core.Translates',
  44. ];
  45. public function tearDown()
  46. {
  47. parent::tearDown();
  48. I18n::setLocale(I18n::getDefaultLocale());
  49. $this->getTableLocator()->clear();
  50. }
  51. /**
  52. * Returns an array with all the translations found for a set of records
  53. *
  54. * @param array|\Traversable $data
  55. * @return \Cake\Collection\CollectionInterface
  56. */
  57. protected function _extractTranslations($data)
  58. {
  59. return (new Collection($data))->map(function (EntityInterface $row) {
  60. $translations = $row->get('_translations');
  61. if (!$translations) {
  62. return [];
  63. }
  64. return array_map(function (EntityInterface $entity) {
  65. return $entity->toArray();
  66. }, $translations);
  67. });
  68. }
  69. /**
  70. * Tests that custom translation tables are respected
  71. *
  72. * @return void
  73. */
  74. public function testCustomTranslationTable()
  75. {
  76. $table = $this->getTableLocator()->get('Articles');
  77. $table->addBehavior('Translate', [
  78. 'translationTable' => I18nTable::class,
  79. 'fields' => ['title', 'body'],
  80. ]);
  81. $items = $table->associations();
  82. $i18n = $items->getByProperty('_i18n');
  83. $this->assertEquals(I18nTable::class, $i18n->getName());
  84. $this->assertInstanceOf(I18nTable::class, $i18n->getTarget());
  85. $this->assertEquals('test_custom_i18n_datasource', $i18n->getTarget()->getConnection()->configName());
  86. $this->assertEquals('custom_i18n_table', $i18n->getTarget()->getTable());
  87. }
  88. /**
  89. * Tests that the strategy can be changed for i18n
  90. *
  91. * @return void
  92. */
  93. public function testStrategy()
  94. {
  95. $table = $this->getTableLocator()->get('Articles');
  96. $table->addBehavior('Translate', [
  97. 'strategy' => 'select',
  98. 'fields' => ['title', 'body'],
  99. ]);
  100. $items = $table->associations();
  101. $i18n = $items->getByProperty('_i18n');
  102. $this->assertEquals('select', $i18n->getStrategy());
  103. }
  104. /**
  105. * Tests that fields from a translated model are overridden
  106. *
  107. * @return void
  108. */
  109. public function testFindSingleLocale()
  110. {
  111. $table = $this->getTableLocator()->get('Articles');
  112. $table->addBehavior('Translate', ['fields' => ['title', 'body']]);
  113. $table->setLocale('eng');
  114. $results = $table->find()->combine('title', 'body', 'id')->toArray();
  115. $expected = [
  116. 1 => ['Title #1' => 'Content #1'],
  117. 2 => ['Title #2' => 'Content #2'],
  118. 3 => ['Title #3' => 'Content #3'],
  119. ];
  120. $this->assertSame($expected, $results);
  121. }
  122. /**
  123. * Test that iterating in a formatResults() does not drop data.
  124. *
  125. * @return void
  126. */
  127. public function testFindTranslationsFormatResultsIteration()
  128. {
  129. $table = $this->getTableLocator()->get('Articles');
  130. $table->addBehavior('Translate', ['fields' => ['title', 'body']]);
  131. $table->setLocale('eng');
  132. $results = $table->find('translations')
  133. ->limit(1)
  134. ->formatResults(function ($results) {
  135. foreach ($results as $res) {
  136. $res->first = 'val';
  137. }
  138. foreach ($results as $res) {
  139. $res->second = 'loop';
  140. }
  141. return $results;
  142. })
  143. ->toArray();
  144. $this->assertCount(1, $results);
  145. $this->assertSame('Title #1', $results[0]->title);
  146. $this->assertSame('val', $results[0]->first);
  147. $this->assertSame('loop', $results[0]->second);
  148. $this->assertNotEmpty($results[0]->_translations);
  149. }
  150. /**
  151. * Tests that fields from a translated model use the I18n class locale
  152. * and that it propagates to associated models
  153. *
  154. * @return void
  155. */
  156. public function testFindSingleLocaleAssociatedEnv()
  157. {
  158. I18n::setLocale('eng');
  159. $table = $this->getTableLocator()->get('Articles');
  160. $table->addBehavior('Translate', ['fields' => ['title', 'body']]);
  161. $table->hasMany('Comments');
  162. $table->Comments->addBehavior('Translate', ['fields' => ['comment']]);
  163. $results = $table->find()
  164. ->select(['id', 'title', 'body'])
  165. ->contain(['Comments' => ['fields' => ['article_id', 'comment']]])
  166. ->enableHydration(false)
  167. ->toArray();
  168. $expected = [
  169. [
  170. 'id' => 1,
  171. 'title' => 'Title #1',
  172. 'body' => 'Content #1',
  173. 'comments' => [
  174. ['article_id' => 1, 'comment' => 'Comment #1', '_locale' => 'eng'],
  175. ['article_id' => 1, 'comment' => 'Comment #2', '_locale' => 'eng'],
  176. ['article_id' => 1, 'comment' => 'Comment #3', '_locale' => 'eng'],
  177. ['article_id' => 1, 'comment' => 'Comment #4', '_locale' => 'eng'],
  178. ],
  179. '_locale' => 'eng',
  180. ],
  181. [
  182. 'id' => 2,
  183. 'title' => 'Title #2',
  184. 'body' => 'Content #2',
  185. 'comments' => [
  186. ['article_id' => 2, 'comment' => 'First Comment for Second Article', '_locale' => 'eng'],
  187. ['article_id' => 2, 'comment' => 'Second Comment for Second Article', '_locale' => 'eng'],
  188. ],
  189. '_locale' => 'eng',
  190. ],
  191. [
  192. 'id' => 3,
  193. 'title' => 'Title #3',
  194. 'body' => 'Content #3',
  195. 'comments' => [],
  196. '_locale' => 'eng',
  197. ],
  198. ];
  199. $this->assertSame($expected, $results);
  200. I18n::setLocale('spa');
  201. $results = $table->find()
  202. ->select(['id', 'title', 'body'])
  203. ->contain([
  204. 'Comments' => [
  205. 'fields' => ['article_id', 'comment'],
  206. 'sort' => ['Comments.id' => 'ASC'],
  207. ],
  208. ])
  209. ->enableHydration(false)
  210. ->toArray();
  211. $expected = [
  212. [
  213. 'id' => 1,
  214. 'title' => 'First Article',
  215. 'body' => 'Contenido #1',
  216. 'comments' => [
  217. ['article_id' => 1, 'comment' => 'First Comment for First Article', '_locale' => 'spa'],
  218. ['article_id' => 1, 'comment' => 'Second Comment for First Article', '_locale' => 'spa'],
  219. ['article_id' => 1, 'comment' => 'Third Comment for First Article', '_locale' => 'spa'],
  220. ['article_id' => 1, 'comment' => 'Comentario #4', '_locale' => 'spa'],
  221. ],
  222. '_locale' => 'spa',
  223. ],
  224. [
  225. 'id' => 2,
  226. 'title' => 'Second Article',
  227. 'body' => 'Second Article Body',
  228. 'comments' => [
  229. ['article_id' => 2, 'comment' => 'First Comment for Second Article', '_locale' => 'spa'],
  230. ['article_id' => 2, 'comment' => 'Second Comment for Second Article', '_locale' => 'spa'],
  231. ],
  232. '_locale' => 'spa',
  233. ],
  234. [
  235. 'id' => 3,
  236. 'title' => 'Third Article',
  237. 'body' => 'Third Article Body',
  238. 'comments' => [],
  239. '_locale' => 'spa',
  240. ],
  241. ];
  242. $this->assertSame($expected, $results);
  243. }
  244. /**
  245. * Tests that fields from a translated model are not overridden if translation
  246. * is null
  247. *
  248. * @return void
  249. */
  250. public function testFindSingleLocaleWithNullTranslation()
  251. {
  252. $table = $this->getTableLocator()->get('Comments');
  253. $table->addBehavior('Translate', ['fields' => ['comment']]);
  254. $table->setLocale('spa');
  255. $results = $table->find()
  256. ->where(['Comments.id' => 6])
  257. ->combine('id', 'comment')->toArray();
  258. $expected = [6 => 'Second Comment for Second Article'];
  259. $this->assertSame($expected, $results);
  260. }
  261. /**
  262. * Tests that overriding fields with the translate behavior works when
  263. * using conditions and that all other columns are preserved
  264. *
  265. * @return void
  266. */
  267. public function testFindSingleLocaleWithgetConditions()
  268. {
  269. $table = $this->getTableLocator()->get('Articles');
  270. $table->addBehavior('Translate', ['fields' => ['title', 'body']]);
  271. $table->setLocale('eng');
  272. $results = $table->find()
  273. ->where(['Articles.id' => 2])
  274. ->all();
  275. $this->assertCount(1, $results);
  276. $row = $results->first();
  277. $expected = [
  278. 'id' => 2,
  279. 'title' => 'Title #2',
  280. 'body' => 'Content #2',
  281. 'author_id' => 3,
  282. 'published' => 'Y',
  283. '_locale' => 'eng',
  284. ];
  285. $this->assertEquals($expected, $row->toArray());
  286. }
  287. /**
  288. * Tests the locale setter/getter.
  289. *
  290. * @return void
  291. */
  292. public function testSetGetLocale()
  293. {
  294. $table = $this->getTableLocator()->get('Articles');
  295. $table->addBehavior('Translate');
  296. $this->assertEquals('en_US', $table->getLocale());
  297. $table->setLocale('fr_FR');
  298. $this->assertEquals('fr_FR', $table->getLocale());
  299. $table->setLocale(null);
  300. $this->assertEquals('en_US', $table->getLocale());
  301. I18n::setLocale('fr_FR');
  302. $this->assertEquals('fr_FR', $table->getLocale());
  303. }
  304. /**
  305. * Tests translationField method for translated fields.
  306. *
  307. * @return void
  308. */
  309. public function testTranslationFieldForTranslatedFields()
  310. {
  311. $table = $this->getTableLocator()->get('Articles');
  312. $table->addBehavior('Translate', [
  313. 'fields' => ['title', 'body'],
  314. 'defaultLocale' => 'en_US',
  315. ]);
  316. $expectedSameLocale = 'Articles.title';
  317. $expectedOtherLocale = 'Articles_title_translation.content';
  318. $field = $table->translationField('title');
  319. $this->assertSame($expectedSameLocale, $field);
  320. I18n::setLocale('es_ES');
  321. $field = $table->translationField('title');
  322. $this->assertSame($expectedOtherLocale, $field);
  323. I18n::setLocale('en');
  324. $field = $table->translationField('title');
  325. $this->assertSame($expectedOtherLocale, $field);
  326. $table->removeBehavior('Translate');
  327. $table->addBehavior('Translate', [
  328. 'fields' => ['title', 'body'],
  329. 'defaultLocale' => 'de_DE',
  330. ]);
  331. I18n::setLocale('de_DE');
  332. $field = $table->translationField('title');
  333. $this->assertSame($expectedSameLocale, $field);
  334. I18n::setLocale('en_US');
  335. $field = $table->translationField('title');
  336. $this->assertSame($expectedOtherLocale, $field);
  337. $table->setLocale('de_DE');
  338. $field = $table->translationField('title');
  339. $this->assertSame($expectedSameLocale, $field);
  340. $table->setLocale('es');
  341. $field = $table->translationField('title');
  342. $this->assertSame($expectedOtherLocale, $field);
  343. }
  344. /**
  345. * Tests translationField method for other fields.
  346. *
  347. * @return void
  348. */
  349. public function testTranslationFieldForOtherFields()
  350. {
  351. $table = $this->getTableLocator()->get('Articles');
  352. $table->addBehavior('Translate', ['fields' => ['title', 'body']]);
  353. $expected = 'Articles.foo';
  354. $field = $table->translationField('foo');
  355. $this->assertSame($expected, $field);
  356. }
  357. /**
  358. * Tests that translating fields work when other formatters are used
  359. *
  360. * @return void
  361. */
  362. public function testFindList()
  363. {
  364. $table = $this->getTableLocator()->get('Articles');
  365. $table->addBehavior('Translate', ['fields' => ['title', 'body']]);
  366. $table->setLocale('eng');
  367. $results = $table->find('list')->toArray();
  368. $expected = [1 => 'Title #1', 2 => 'Title #2', 3 => 'Title #3'];
  369. $this->assertSame($expected, $results);
  370. }
  371. /**
  372. * Tests that the query count return the correct results
  373. *
  374. * @return void
  375. */
  376. public function testFindCount()
  377. {
  378. $table = $this->getTableLocator()->get('Articles');
  379. $table->addBehavior('Translate', ['fields' => ['title', 'body']]);
  380. $table->setLocale('eng');
  381. $this->assertEquals(3, $table->find()->count());
  382. }
  383. /**
  384. * Tests that it is possible to get all translated fields at once
  385. *
  386. * @return void
  387. */
  388. public function testFindTranslations()
  389. {
  390. $table = $this->getTableLocator()->get('Articles');
  391. $table->addBehavior('Translate', ['fields' => ['title', 'body']]);
  392. $results = $table->find('translations');
  393. $expected = [
  394. [
  395. 'eng' => ['title' => 'Title #1', 'body' => 'Content #1', 'description' => 'Description #1', 'locale' => 'eng'],
  396. 'deu' => ['title' => 'Titel #1', 'body' => 'Inhalt #1', 'locale' => 'deu'],
  397. 'cze' => ['title' => 'Titulek #1', 'body' => 'Obsah #1', 'locale' => 'cze'],
  398. 'spa' => ['body' => 'Contenido #1', 'locale' => 'spa', 'description' => ''],
  399. ],
  400. [
  401. 'eng' => ['title' => 'Title #2', 'body' => 'Content #2', 'locale' => 'eng'],
  402. 'deu' => ['title' => 'Titel #2', 'body' => 'Inhalt #2', 'locale' => 'deu'],
  403. 'cze' => ['title' => 'Titulek #2', 'body' => 'Obsah #2', 'locale' => 'cze'],
  404. ],
  405. [
  406. 'eng' => ['title' => 'Title #3', 'body' => 'Content #3', 'locale' => 'eng'],
  407. 'deu' => ['title' => 'Titel #3', 'body' => 'Inhalt #3', 'locale' => 'deu'],
  408. 'cze' => ['title' => 'Titulek #3', 'body' => 'Obsah #3', 'locale' => 'cze'],
  409. ],
  410. ];
  411. $translations = $this->_extractTranslations($results);
  412. $this->assertEquals($expected, $translations->toArray());
  413. $expected = [
  414. 1 => ['First Article' => 'First Article Body'],
  415. 2 => ['Second Article' => 'Second Article Body'],
  416. 3 => ['Third Article' => 'Third Article Body'],
  417. ];
  418. $grouped = $results->combine('title', 'body', 'id');
  419. $this->assertEquals($expected, $grouped->toArray());
  420. }
  421. /**
  422. * Tests that it is possible to request just a few translations
  423. *
  424. * @return void
  425. */
  426. public function testFindFilteredTranslations()
  427. {
  428. $table = $this->getTableLocator()->get('Articles');
  429. $table->addBehavior('Translate', ['fields' => ['title', 'body']]);
  430. $results = $table->find('translations', ['locales' => ['deu', 'cze']]);
  431. $expected = [
  432. [
  433. 'deu' => ['title' => 'Titel #1', 'body' => 'Inhalt #1', 'locale' => 'deu'],
  434. 'cze' => ['title' => 'Titulek #1', 'body' => 'Obsah #1', 'locale' => 'cze'],
  435. ],
  436. [
  437. 'deu' => ['title' => 'Titel #2', 'body' => 'Inhalt #2', 'locale' => 'deu'],
  438. 'cze' => ['title' => 'Titulek #2', 'body' => 'Obsah #2', 'locale' => 'cze'],
  439. ],
  440. [
  441. 'deu' => ['title' => 'Titel #3', 'body' => 'Inhalt #3', 'locale' => 'deu'],
  442. 'cze' => ['title' => 'Titulek #3', 'body' => 'Obsah #3', 'locale' => 'cze'],
  443. ],
  444. ];
  445. $translations = $this->_extractTranslations($results);
  446. $this->assertEquals($expected, $translations->toArray());
  447. $expected = [
  448. 1 => ['First Article' => 'First Article Body'],
  449. 2 => ['Second Article' => 'Second Article Body'],
  450. 3 => ['Third Article' => 'Third Article Body'],
  451. ];
  452. $grouped = $results->combine('title', 'body', 'id');
  453. $this->assertEquals($expected, $grouped->toArray());
  454. }
  455. /**
  456. * Tests that it is possible to combine find('list') and find('translations')
  457. *
  458. * @return void
  459. */
  460. public function testFindTranslationsList()
  461. {
  462. $table = $this->getTableLocator()->get('Articles');
  463. $table->addBehavior('Translate', ['fields' => ['title', 'body']]);
  464. $results = $table
  465. ->find('list', [
  466. 'keyField' => 'title',
  467. 'valueField' => '_translations.deu.title',
  468. 'groupField' => 'id',
  469. ])
  470. ->find('translations', ['locales' => ['deu']]);
  471. $expected = [
  472. 1 => ['First Article' => 'Titel #1'],
  473. 2 => ['Second Article' => 'Titel #2'],
  474. 3 => ['Third Article' => 'Titel #3'],
  475. ];
  476. $this->assertEquals($expected, $results->toArray());
  477. }
  478. /**
  479. * Tests that you can both override fields and find all translations
  480. *
  481. * @return void
  482. */
  483. public function testFindTranslationsWithFieldOverriding()
  484. {
  485. $table = $this->getTableLocator()->get('Articles');
  486. $table->addBehavior('Translate', ['fields' => ['title', 'body']]);
  487. $table->setLocale('cze');
  488. $results = $table->find('translations', ['locales' => ['deu', 'cze']]);
  489. $expected = [
  490. [
  491. 'deu' => ['title' => 'Titel #1', 'body' => 'Inhalt #1', 'locale' => 'deu'],
  492. 'cze' => ['title' => 'Titulek #1', 'body' => 'Obsah #1', 'locale' => 'cze'],
  493. ],
  494. [
  495. 'deu' => ['title' => 'Titel #2', 'body' => 'Inhalt #2', 'locale' => 'deu'],
  496. 'cze' => ['title' => 'Titulek #2', 'body' => 'Obsah #2', 'locale' => 'cze'],
  497. ],
  498. [
  499. 'deu' => ['title' => 'Titel #3', 'body' => 'Inhalt #3', 'locale' => 'deu'],
  500. 'cze' => ['title' => 'Titulek #3', 'body' => 'Obsah #3', 'locale' => 'cze'],
  501. ],
  502. ];
  503. $translations = $this->_extractTranslations($results);
  504. $this->assertEquals($expected, $translations->toArray());
  505. $expected = [
  506. 1 => ['Titulek #1' => 'Obsah #1'],
  507. 2 => ['Titulek #2' => 'Obsah #2'],
  508. 3 => ['Titulek #3' => 'Obsah #3'],
  509. ];
  510. $grouped = $results->combine('title', 'body', 'id');
  511. $this->assertEquals($expected, $grouped->toArray());
  512. }
  513. /**
  514. * Tests that fields can be overridden in a hasMany association
  515. *
  516. * @return void
  517. */
  518. public function testFindSingleLocaleHasMany()
  519. {
  520. $table = $this->getTableLocator()->get('Articles');
  521. $table->addBehavior('Translate', ['fields' => ['title', 'body']]);
  522. $table->hasMany('Comments');
  523. $comments = $table->hasMany('Comments')->getTarget();
  524. $comments->addBehavior('Translate', ['fields' => ['comment']]);
  525. $table->setLocale('eng');
  526. $comments->setLocale('eng');
  527. $results = $table->find()->contain(['Comments' => function ($q) {
  528. return $q->select(['id', 'comment', 'article_id']);
  529. }]);
  530. $list = new Collection($results->first()->comments);
  531. $expected = [
  532. 1 => 'Comment #1',
  533. 2 => 'Comment #2',
  534. 3 => 'Comment #3',
  535. 4 => 'Comment #4',
  536. ];
  537. $this->assertEquals($expected, $list->combine('id', 'comment')->toArray());
  538. }
  539. /**
  540. * Test that it is possible to bring translations from hasMany relations
  541. *
  542. * @return void
  543. */
  544. public function testTranslationsHasMany()
  545. {
  546. $table = $this->getTableLocator()->get('Articles');
  547. $table->addBehavior('Translate', ['fields' => ['title', 'body']]);
  548. $table->hasMany('Comments');
  549. $comments = $table->hasMany('Comments')->getTarget();
  550. $comments->addBehavior('Translate', ['fields' => ['comment']]);
  551. $results = $table->find('translations')->contain([
  552. 'Comments' => function ($q) {
  553. return $q->find('translations')->select(['id', 'comment', 'article_id']);
  554. },
  555. ]);
  556. $comments = $results->first()->comments;
  557. $expected = [
  558. [
  559. 'eng' => ['comment' => 'Comment #1', 'locale' => 'eng'],
  560. ],
  561. [
  562. 'eng' => ['comment' => 'Comment #2', 'locale' => 'eng'],
  563. ],
  564. [
  565. 'eng' => ['comment' => 'Comment #3', 'locale' => 'eng'],
  566. ],
  567. [
  568. 'eng' => ['comment' => 'Comment #4', 'locale' => 'eng'],
  569. 'spa' => ['comment' => 'Comentario #4', 'locale' => 'spa'],
  570. ],
  571. ];
  572. $translations = $this->_extractTranslations($comments);
  573. $this->assertEquals($expected, $translations->toArray());
  574. }
  575. /**
  576. * Tests that it is possible to both override fields with a translation and
  577. * also find separately other translations
  578. *
  579. * @return void
  580. */
  581. public function testTranslationsHasManyWithOverride()
  582. {
  583. $table = $this->getTableLocator()->get('Articles');
  584. $table->addBehavior('Translate', ['fields' => ['title', 'body']]);
  585. $table->hasMany('Comments');
  586. $comments = $table->hasMany('Comments')->getTarget();
  587. $comments->addBehavior('Translate', ['fields' => ['comment']]);
  588. $table->setLocale('cze');
  589. $comments->setLocale('eng');
  590. $results = $table->find('translations')->contain([
  591. 'Comments' => function ($q) {
  592. return $q->find('translations')->select(['id', 'comment', 'article_id']);
  593. },
  594. ]);
  595. $comments = $results->first()->comments;
  596. $expected = [
  597. 1 => 'Comment #1',
  598. 2 => 'Comment #2',
  599. 3 => 'Comment #3',
  600. 4 => 'Comment #4',
  601. ];
  602. $list = new Collection($comments);
  603. $this->assertEquals($expected, $list->combine('id', 'comment')->toArray());
  604. $expected = [
  605. [
  606. 'eng' => ['comment' => 'Comment #1', 'locale' => 'eng'],
  607. ],
  608. [
  609. 'eng' => ['comment' => 'Comment #2', 'locale' => 'eng'],
  610. ],
  611. [
  612. 'eng' => ['comment' => 'Comment #3', 'locale' => 'eng'],
  613. ],
  614. [
  615. 'eng' => ['comment' => 'Comment #4', 'locale' => 'eng'],
  616. 'spa' => ['comment' => 'Comentario #4', 'locale' => 'spa'],
  617. ],
  618. ];
  619. $translations = $this->_extractTranslations($comments);
  620. $this->assertEquals($expected, $translations->toArray());
  621. $this->assertEquals('Titulek #1', $results->first()->title);
  622. $this->assertEquals('Obsah #1', $results->first()->body);
  623. }
  624. /**
  625. * Tests that it is possible to translate belongsTo associations
  626. *
  627. * @return void
  628. */
  629. public function testFindSingleLocaleBelongsto()
  630. {
  631. $table = $this->getTableLocator()->get('Articles');
  632. $table->addBehavior('Translate', ['fields' => ['title', 'body']]);
  633. $authors = $table->belongsTo('Authors')->getTarget();
  634. $authors->addBehavior('Translate', ['fields' => ['name']]);
  635. $table->setLocale('eng');
  636. $authors->setLocale('eng');
  637. $results = $table->find()
  638. ->select(['title', 'body'])
  639. ->order(['title' => 'asc'])
  640. ->contain(['Authors' => function ($q) {
  641. return $q->select(['id', 'name']);
  642. }]);
  643. $expected = [
  644. [
  645. 'title' => 'Title #1',
  646. 'body' => 'Content #1',
  647. 'author' => ['id' => 1, 'name' => 'May-rianoh', '_locale' => 'eng'],
  648. '_locale' => 'eng',
  649. ],
  650. [
  651. 'title' => 'Title #2',
  652. 'body' => 'Content #2',
  653. 'author' => ['id' => 3, 'name' => 'larry', '_locale' => 'eng'],
  654. '_locale' => 'eng',
  655. ],
  656. [
  657. 'title' => 'Title #3',
  658. 'body' => 'Content #3',
  659. 'author' => ['id' => 1, 'name' => 'May-rianoh', '_locale' => 'eng'],
  660. '_locale' => 'eng',
  661. ],
  662. ];
  663. $results = array_map(function ($r) {
  664. return $r->toArray();
  665. }, $results->toArray());
  666. $this->assertEquals($expected, $results);
  667. }
  668. /**
  669. * Tests that it is possible to translate belongsToMany associations
  670. *
  671. * @return void
  672. */
  673. public function testFindSingleLocaleBelongsToMany()
  674. {
  675. $table = $this->getTableLocator()->get('Articles');
  676. $specialTags = $this->getTableLocator()->get('SpecialTags');
  677. $specialTags->addBehavior('Translate', ['fields' => ['extra_info']]);
  678. $table->belongsToMany('Tags', [
  679. 'through' => $specialTags,
  680. ]);
  681. $specialTags->setLocale('eng');
  682. $result = $table->get(2, ['contain' => 'Tags']);
  683. $this->assertNotEmpty($result);
  684. $this->assertNotEmpty($result->tags);
  685. $this->assertEquals('Translated Info', $result->tags[0]->special_tags[0]->extra_info);
  686. }
  687. /**
  688. * Tests that updating an existing record translations work
  689. *
  690. * @return void
  691. */
  692. public function testUpdateSingleLocale()
  693. {
  694. $table = $this->getTableLocator()->get('Articles');
  695. $table->addBehavior('Translate', ['fields' => ['title', 'body']]);
  696. $table->setLocale('eng');
  697. $article = $table->find()->first();
  698. $this->assertEquals(1, $article->get('id'));
  699. $article->set('title', 'New translated article');
  700. $table->save($article);
  701. $this->assertNull($article->get('_i18n'));
  702. $article = $table->find()->first();
  703. $this->assertEquals(1, $article->get('id'));
  704. $this->assertEquals('New translated article', $article->get('title'));
  705. $this->assertEquals('Content #1', $article->get('body'));
  706. $table->setLocale(false);
  707. $article = $table->find()->first();
  708. $this->assertEquals(1, $article->get('id'));
  709. $this->assertEquals('First Article', $article->get('title'));
  710. $table->setLocale('eng');
  711. $article->set('title', 'Wow, such translated article');
  712. $article->set('body', 'A translated body');
  713. $table->save($article);
  714. $this->assertNull($article->get('_i18n'));
  715. $article = $table->find()->first();
  716. $this->assertEquals(1, $article->get('id'));
  717. $this->assertEquals('Wow, such translated article', $article->get('title'));
  718. $this->assertEquals('A translated body', $article->get('body'));
  719. }
  720. /**
  721. * Tests adding new translation to a record
  722. *
  723. * @return void
  724. */
  725. public function testInsertNewTranslations()
  726. {
  727. $table = $this->getTableLocator()->get('Articles');
  728. $table->addBehavior('Translate', ['fields' => ['title', 'body']]);
  729. $table->setLocale('fra');
  730. $article = $table->find()->first();
  731. $this->assertEquals(1, $article->get('id'));
  732. $article->set('title', 'Le titre');
  733. $table->save($article);
  734. $this->assertEquals('fra', $article->get('_locale'));
  735. $article = $table->find()->first();
  736. $this->assertEquals(1, $article->get('id'));
  737. $this->assertEquals('Le titre', $article->get('title'));
  738. $this->assertEquals('First Article Body', $article->get('body'));
  739. $article->set('title', 'Un autre titre');
  740. $article->set('body', 'Le contenu');
  741. $table->save($article);
  742. $this->assertNull($article->get('_i18n'));
  743. $article = $table->find()->first();
  744. $this->assertEquals('Un autre titre', $article->get('title'));
  745. $this->assertEquals('Le contenu', $article->get('body'));
  746. }
  747. /**
  748. * Tests adding new translation to a record
  749. *
  750. * @return void
  751. */
  752. public function testAllowEmptyFalse()
  753. {
  754. $table = $this->getTableLocator()->get('Articles');
  755. $table->addBehavior('Translate', ['fields' => ['title'], 'allowEmptyTranslations' => false]);
  756. $article = $table->find()->first();
  757. $this->assertEquals(1, $article->get('id'));
  758. $article = $table->patchEntity($article, [
  759. '_translations' => [
  760. 'fra' => [
  761. 'title' => '',
  762. ],
  763. ],
  764. ]);
  765. $table->save($article);
  766. // Remove the Behavior to unset the content != '' condition
  767. $table->removeBehavior('Translate');
  768. $noFra = $table->I18n->find()->where(['locale' => 'fra'])->first();
  769. $this->assertEmpty($noFra);
  770. }
  771. /**
  772. * Tests adding new translation to a record
  773. *
  774. * @return void
  775. */
  776. public function testMixedAllowEmptyFalse()
  777. {
  778. $table = $this->getTableLocator()->get('Articles');
  779. $table->addBehavior('Translate', ['fields' => ['title', 'body'], 'allowEmptyTranslations' => false]);
  780. $article = $table->find()->first();
  781. $this->assertEquals(1, $article->get('id'));
  782. $article = $table->patchEntity($article, [
  783. '_translations' => [
  784. 'fra' => [
  785. 'title' => '',
  786. 'body' => 'Bonjour',
  787. ],
  788. ],
  789. ]);
  790. $table->save($article);
  791. $fra = $table->I18n->find()
  792. ->where([
  793. 'locale' => 'fra',
  794. 'field' => 'body',
  795. ])
  796. ->first();
  797. $this->assertSame('Bonjour', $fra->content);
  798. // Remove the Behavior to unset the content != '' condition
  799. $table->removeBehavior('Translate');
  800. $noTitle = $table->I18n->find()
  801. ->where([
  802. 'locale' => 'fra',
  803. 'field' => 'title',
  804. ])
  805. ->first();
  806. $this->assertEmpty($noTitle);
  807. }
  808. /**
  809. * Tests adding new translation to a record
  810. *
  811. * @return void
  812. */
  813. public function testMultipleAllowEmptyFalse()
  814. {
  815. $table = $this->getTableLocator()->get('Articles');
  816. $table->addBehavior('Translate', ['fields' => ['title', 'body'], 'allowEmptyTranslations' => false]);
  817. $article = $table->find()->first();
  818. $this->assertEquals(1, $article->get('id'));
  819. $article = $table->patchEntity($article, [
  820. '_translations' => [
  821. 'fra' => [
  822. 'title' => '',
  823. 'body' => 'Bonjour',
  824. ],
  825. 'de' => [
  826. 'title' => 'Titel',
  827. 'body' => 'Hallo',
  828. ],
  829. ],
  830. ]);
  831. $table->save($article);
  832. $fra = $table->I18n->find()
  833. ->where([
  834. 'locale' => 'fra',
  835. 'field' => 'body',
  836. ])
  837. ->first();
  838. $this->assertSame('Bonjour', $fra->content);
  839. $deTitle = $table->I18n->find()
  840. ->where([
  841. 'locale' => 'de',
  842. 'field' => 'title',
  843. ])
  844. ->first();
  845. $this->assertSame('Titel', $deTitle->content);
  846. $deBody = $table->I18n->find()
  847. ->where([
  848. 'locale' => 'de',
  849. 'field' => 'body',
  850. ])
  851. ->first();
  852. $this->assertSame('Hallo', $deBody->content);
  853. // Remove the Behavior to unset the content != '' condition
  854. $table->removeBehavior('Translate');
  855. $noTitle = $table->I18n->find()
  856. ->where([
  857. 'locale' => 'fra',
  858. 'field' => 'title',
  859. ])
  860. ->first();
  861. $this->assertEmpty($noTitle);
  862. }
  863. /**
  864. * Tests that it is possible to use the _locale property to specify the language
  865. * to use for saving an entity
  866. *
  867. * @return void
  868. */
  869. public function testUpdateTranslationWithLocaleInEntity()
  870. {
  871. $table = $this->getTableLocator()->get('Articles');
  872. $table->addBehavior('Translate', ['fields' => ['title', 'body']]);
  873. $article = $table->find()->first();
  874. $this->assertEquals(1, $article->get('id'));
  875. $article->set('_locale', 'fra');
  876. $article->set('title', 'Le titre');
  877. $table->save($article);
  878. $this->assertNull($article->get('_i18n'));
  879. $article = $table->find()->first();
  880. $this->assertEquals(1, $article->get('id'));
  881. $this->assertEquals('First Article', $article->get('title'));
  882. $this->assertEquals('First Article Body', $article->get('body'));
  883. $table->setLocale('fra');
  884. $article = $table->find()->first();
  885. $this->assertEquals(1, $article->get('id'));
  886. $this->assertEquals('Le titre', $article->get('title'));
  887. $this->assertEquals('First Article Body', $article->get('body'));
  888. }
  889. /**
  890. * Tests that translations are added to the whitelist of associations to be
  891. * saved
  892. *
  893. * @return void
  894. */
  895. public function testSaveTranslationWithAssociationWhitelist()
  896. {
  897. $table = $this->getTableLocator()->get('Articles');
  898. $table->hasMany('Comments');
  899. $table->addBehavior('Translate', ['fields' => ['title', 'body']]);
  900. $table->setLocale('fra');
  901. $article = $table->find()->first();
  902. $this->assertEquals(1, $article->get('id'));
  903. $article->set('title', 'Le titre');
  904. $table->save($article, ['associated' => ['Comments']]);
  905. $this->assertNull($article->get('_i18n'));
  906. $article = $table->find()->first();
  907. $this->assertEquals('Le titre', $article->get('title'));
  908. }
  909. /**
  910. * Tests that after deleting a translated entity, all translations are also removed
  911. *
  912. * @return void
  913. */
  914. public function testDelete()
  915. {
  916. $table = $this->getTableLocator()->get('Articles');
  917. $table->addBehavior('Translate', ['fields' => ['title', 'body']]);
  918. $article = $table->find()->first();
  919. $this->assertTrue($table->delete($article));
  920. $translations = $this->getTableLocator()->get('I18n')->find()
  921. ->where(['model' => 'Articles', 'foreign_key' => $article->id])
  922. ->count();
  923. $this->assertEquals(0, $translations);
  924. }
  925. /**
  926. * Tests saving multiple translations at once when the translations already
  927. * exist in the database
  928. *
  929. * @return void
  930. */
  931. public function testSaveMultipleTranslations()
  932. {
  933. $table = $this->getTableLocator()->get('Articles');
  934. $table->addBehavior('Translate', ['fields' => ['title', 'body']]);
  935. $article = $results = $table->find('translations')->first();
  936. $translations = $article->get('_translations');
  937. $translations['deu']->set('title', 'Another title');
  938. $translations['eng']->set('body', 'Another body');
  939. $article->set('_translations', $translations);
  940. $table->save($article);
  941. $this->assertNull($article->get('_i18n'));
  942. $article = $results = $table->find('translations')->first();
  943. $translations = $article->get('_translations');
  944. $this->assertEquals('Another title', $translations['deu']->get('title'));
  945. $this->assertEquals('Another body', $translations['eng']->get('body'));
  946. }
  947. /**
  948. * Tests saving multiple existing translations and adding new ones
  949. *
  950. * @return void
  951. */
  952. public function testSaveMultipleNewTranslations()
  953. {
  954. $table = $this->getTableLocator()->get('Articles');
  955. $table->addBehavior('Translate', ['fields' => ['title', 'body']]);
  956. $article = $results = $table->find('translations')->first();
  957. $translations = $article->get('_translations');
  958. $translations['deu']->set('title', 'Another title');
  959. $translations['eng']->set('body', 'Another body');
  960. $translations['spa'] = new Entity(['title' => 'Titulo']);
  961. $translations['fre'] = new Entity(['title' => 'Titre']);
  962. $article->set('_translations', $translations);
  963. $table->save($article);
  964. $this->assertNull($article->get('_i18n'));
  965. $article = $results = $table->find('translations')->first();
  966. $translations = $article->get('_translations');
  967. $this->assertEquals('Another title', $translations['deu']->get('title'));
  968. $this->assertEquals('Another body', $translations['eng']->get('body'));
  969. $this->assertEquals('Titulo', $translations['spa']->get('title'));
  970. $this->assertEquals('Titre', $translations['fre']->get('title'));
  971. }
  972. /**
  973. * Tests that iterating a resultset twice when using the translations finder
  974. * will not cause any errors nor information loss
  975. *
  976. * @return void
  977. */
  978. public function testUseCountInFindTranslations()
  979. {
  980. $table = $this->getTableLocator()->get('Articles');
  981. $table->addBehavior('Translate', ['fields' => ['title', 'body']]);
  982. $articles = $results = $table->find('translations');
  983. $all = $articles->all();
  984. $this->assertCount(3, $all);
  985. $article = $all->first();
  986. $this->assertNotEmpty($article->get('_translations'));
  987. }
  988. /**
  989. * Tests that multiple translations saved when having a default locale
  990. * are correctly saved
  991. *
  992. * @return void
  993. */
  994. public function testSavingWithNonDefaultLocale()
  995. {
  996. $table = $this->getTableLocator()->get('Articles');
  997. $table->addBehavior('Translate', ['fields' => ['title', 'body']]);
  998. $table->setEntityClass(TranslateArticle::class);
  999. I18n::setLocale('fra');
  1000. $translations = [
  1001. 'fra' => ['title' => 'Un article'],
  1002. 'spa' => ['title' => 'Un artículo'],
  1003. ];
  1004. $article = $table->get(1);
  1005. foreach ($translations as $lang => $data) {
  1006. $article->translation($lang)->set($data, ['guard' => false]);
  1007. }
  1008. $table->save($article);
  1009. $article = $table->find('translations')->where(['Articles.id' => 1])->first();
  1010. $this->assertEquals('Un article', $article->translation('fra')->title);
  1011. $this->assertEquals('Un artículo', $article->translation('spa')->title);
  1012. }
  1013. /**
  1014. * Tests that translation queries are added to union queries as well.
  1015. *
  1016. * @return void
  1017. */
  1018. public function testTranslationWithUnionQuery()
  1019. {
  1020. $table = $this->getTableLocator()->get('Comments');
  1021. $table->addBehavior('Translate', ['fields' => ['comment']]);
  1022. $table->setLocale('spa');
  1023. $query = $table->find()->where(['Comments.id' => 6]);
  1024. $query2 = $table->find()->where(['Comments.id' => 5]);
  1025. $query->union($query2);
  1026. $results = $query->sortBy('id', SORT_ASC)->toList();
  1027. $this->assertCount(2, $results);
  1028. $this->assertEquals('First Comment for Second Article', $results[0]->comment);
  1029. $this->assertEquals('Second Comment for Second Article', $results[1]->comment);
  1030. }
  1031. /**
  1032. * Tests the use of `referenceName` config option.
  1033. *
  1034. * @return void
  1035. */
  1036. public function testAutoReferenceName()
  1037. {
  1038. $table = $this->getTableLocator()->get('Articles');
  1039. $table->hasMany('OtherComments', ['className' => 'Comments']);
  1040. $table->OtherComments->addBehavior(
  1041. 'Translate',
  1042. ['fields' => ['comment']]
  1043. );
  1044. $items = $table->OtherComments->associations();
  1045. $association = $items->getByProperty('comment_translation');
  1046. $this->assertNotEmpty($association, 'Translation association not found');
  1047. $found = false;
  1048. foreach ($association->getConditions() as $key => $value) {
  1049. if (strpos($key, 'comment_translation.model') !== false) {
  1050. $found = true;
  1051. $this->assertEquals('Comments', $value);
  1052. break;
  1053. }
  1054. }
  1055. $this->assertTrue($found, '`referenceName` field condition on a Translation association was not found');
  1056. }
  1057. /**
  1058. * Tests the use of unconventional `referenceName` config option.
  1059. *
  1060. * @return void
  1061. */
  1062. public function testChangingReferenceName()
  1063. {
  1064. $table = $this->getTableLocator()->get('Articles');
  1065. $table->setAlias('FavoritePost');
  1066. $table->addBehavior(
  1067. 'Translate',
  1068. ['fields' => ['body'], 'referenceName' => 'Posts']
  1069. );
  1070. $items = $table->associations();
  1071. $association = $items->getByProperty('body_translation');
  1072. $this->assertNotEmpty($association, 'Translation association not found');
  1073. $found = false;
  1074. foreach ($association->getConditions() as $key => $value) {
  1075. if (strpos($key, 'body_translation.model') !== false) {
  1076. $found = true;
  1077. $this->assertEquals('Posts', $value);
  1078. break;
  1079. }
  1080. }
  1081. $this->assertTrue($found, '`referenceName` field condition on a Translation association was not found');
  1082. }
  1083. /**
  1084. * Tests that onlyTranslated will remove records from the result set
  1085. * if they are not fully translated
  1086. *
  1087. * @return void
  1088. */
  1089. public function testFilterUntranslated()
  1090. {
  1091. $table = $this->getTableLocator()->get('Articles');
  1092. $table->addBehavior('Translate', [
  1093. 'fields' => ['title', 'body'],
  1094. 'onlyTranslated' => true,
  1095. ]);
  1096. $table->setLocale('eng');
  1097. $results = $table->find()->where(['Articles.id' => 1])->all();
  1098. $this->assertCount(1, $results);
  1099. $table->setLocale('fr');
  1100. $results = $table->find()->where(['Articles.id' => 1])->all();
  1101. $this->assertCount(0, $results);
  1102. }
  1103. /**
  1104. * Tests that records not translated in the current locale will not be
  1105. * present in the results for the translations finder, and also proves
  1106. * that this can be overridden.
  1107. *
  1108. * @return void
  1109. */
  1110. public function testFilterUntranslatedWithFinder()
  1111. {
  1112. $table = $this->getTableLocator()->get('Comments');
  1113. $table->addBehavior('Translate', [
  1114. 'fields' => ['comment'],
  1115. 'onlyTranslated' => true,
  1116. ]);
  1117. $table->setLocale('eng');
  1118. $results = $table->find('translations')->all();
  1119. $this->assertCount(4, $results);
  1120. $table->setLocale('spa');
  1121. $results = $table->find('translations')->all();
  1122. $this->assertCount(1, $results);
  1123. $table->setLocale('spa');
  1124. $results = $table->find('translations', ['filterByCurrentLocale' => false])->all();
  1125. $this->assertCount(6, $results);
  1126. $table->setLocale('spa');
  1127. $results = $table->find('translations')->all();
  1128. $this->assertCount(1, $results);
  1129. }
  1130. /**
  1131. * Tests that allowEmptyTranslations takes effect
  1132. *
  1133. * @return void
  1134. */
  1135. public function testEmptyTranslations()
  1136. {
  1137. $table = $this->getTableLocator()->get('Articles');
  1138. $table->addBehavior('Translate', [
  1139. 'fields' => ['title', 'body', 'description'],
  1140. 'allowEmptyTranslations' => false,
  1141. ]);
  1142. $table->setLocale('spa');
  1143. $result = $table->find()->first();
  1144. $this->assertNull($result->description);
  1145. }
  1146. /**
  1147. * Test save with clean translate fields
  1148. *
  1149. * @return void
  1150. */
  1151. public function testSaveWithCleanFields()
  1152. {
  1153. $table = $this->getTableLocator()->get('Articles');
  1154. $table->addBehavior('Translate', ['fields' => ['title']]);
  1155. $table->setEntityClass(TranslateArticle::class);
  1156. I18n::setLocale('fra');
  1157. $article = $table->get(1);
  1158. $article->set('body', 'New Body');
  1159. $table->save($article);
  1160. $result = $table->get(1);
  1161. $this->assertEquals('New Body', $result->body);
  1162. $this->assertSame($article->title, $result->title);
  1163. }
  1164. /**
  1165. * Test save new entity with _translations field
  1166. *
  1167. * @return void
  1168. */
  1169. public function testSaveNewRecordWithTranslatesField()
  1170. {
  1171. $table = $this->getTableLocator()->get('Articles');
  1172. $table->addBehavior('Translate', [
  1173. 'fields' => ['title'],
  1174. 'validator' => (new \Cake\Validation\Validator())->add('title', 'notBlank', ['rule' => 'notBlank']),
  1175. ]);
  1176. $table->setEntityClass(TranslateArticle::class);
  1177. $data = [
  1178. 'author_id' => 1,
  1179. 'published' => 'N',
  1180. '_translations' => [
  1181. 'en' => [
  1182. 'title' => 'Title EN',
  1183. 'body' => 'Body EN',
  1184. ],
  1185. 'es' => [
  1186. 'title' => 'Title ES',
  1187. ],
  1188. ],
  1189. ];
  1190. $article = $table->patchEntity($table->newEntity(), $data);
  1191. $result = $table->save($article);
  1192. $this->assertNotFalse($result);
  1193. $expected = [
  1194. [
  1195. 'en' => [
  1196. 'title' => 'Title EN',
  1197. 'locale' => 'en',
  1198. ],
  1199. 'es' => [
  1200. 'title' => 'Title ES',
  1201. 'locale' => 'es',
  1202. ],
  1203. ],
  1204. ];
  1205. $result = $table->find('translations')->where(['id' => $result->id]);
  1206. $this->assertEquals($expected, $this->_extractTranslations($result)->toArray());
  1207. }
  1208. /**
  1209. * Tests adding new translation to a record where the only field is the translated one and it's not the default locale
  1210. *
  1211. * @return void
  1212. */
  1213. public function testSaveNewRecordWithOnlyTranslationsNotDefaultLocale()
  1214. {
  1215. $table = $this->getTableLocator()->get('Groups');
  1216. $table->addBehavior('Translate', [
  1217. 'fields' => ['title'],
  1218. 'validator' => (new \Cake\Validation\Validator())->add('title', 'notBlank', ['rule' => 'notBlank']),
  1219. ]);
  1220. $data = [
  1221. '_translations' => [
  1222. 'es' => [
  1223. 'title' => 'Title ES',
  1224. ],
  1225. ],
  1226. ];
  1227. $group = $table->newEntity($data);
  1228. $result = $table->save($group);
  1229. $this->assertNotFalse($result, 'Record should save.');
  1230. $expected = [
  1231. [
  1232. 'es' => [
  1233. 'title' => 'Title ES',
  1234. 'locale' => 'es',
  1235. ],
  1236. ],
  1237. ];
  1238. $result = $table->find('translations')->where(['id' => $result->id]);
  1239. $this->assertEquals($expected, $this->_extractTranslations($result)->toArray());
  1240. }
  1241. /**
  1242. * Test that existing records can be updated when only translations
  1243. * are modified/dirty.
  1244. *
  1245. * @return void
  1246. */
  1247. public function testSaveExistingRecordOnlyTranslations()
  1248. {
  1249. $table = $this->getTableLocator()->get('Articles');
  1250. $table->addBehavior('Translate', ['fields' => ['title', 'body']]);
  1251. $table->setEntityClass(TranslateArticle::class);
  1252. $data = [
  1253. '_translations' => [
  1254. 'es' => [
  1255. 'title' => 'Spanish Translation',
  1256. ],
  1257. ],
  1258. ];
  1259. $article = $table->find()->first();
  1260. $article = $table->patchEntity($article, $data);
  1261. $this->assertNotFalse($table->save($article));
  1262. $results = $this->_extractTranslations(
  1263. $table->find('translations')->where(['id' => 1])
  1264. )->first();
  1265. $this->assertArrayHasKey('es', $results, 'New translation added');
  1266. $this->assertArrayHasKey('eng', $results, 'Old translations present');
  1267. $this->assertEquals('Spanish Translation', $results['es']['title']);
  1268. }
  1269. /**
  1270. * Test update entity with _translations field.
  1271. *
  1272. * @return void
  1273. */
  1274. public function testSaveExistingRecordWithTranslatesField()
  1275. {
  1276. $table = $this->getTableLocator()->get('Articles');
  1277. $table->addBehavior('Translate', ['fields' => ['title', 'body']]);
  1278. $table->setEntityClass(TranslateArticle::class);
  1279. $data = [
  1280. 'author_id' => 1,
  1281. 'published' => 'Y',
  1282. '_translations' => [
  1283. 'eng' => [
  1284. 'title' => 'First Article1',
  1285. 'body' => 'First Article content has been updated',
  1286. ],
  1287. 'spa' => [
  1288. 'title' => 'Mi nuevo titulo',
  1289. 'body' => 'Contenido Actualizado',
  1290. ],
  1291. ],
  1292. ];
  1293. $article = $table->find()->first();
  1294. $article = $table->patchEntity($article, $data);
  1295. $this->assertNotFalse($table->save($article));
  1296. $results = $this->_extractTranslations(
  1297. $table->find('translations')->where(['id' => 1])
  1298. )->first();
  1299. $this->assertEquals('Mi nuevo titulo', $results['spa']['title']);
  1300. $this->assertEquals('Contenido Actualizado', $results['spa']['body']);
  1301. $this->assertEquals('First Article1', $results['eng']['title']);
  1302. $this->assertEquals('Description #1', $results['eng']['description']);
  1303. }
  1304. /**
  1305. * Tests that default locale saves ok.
  1306. *
  1307. * @return void
  1308. */
  1309. public function testSaveDefaultLocale()
  1310. {
  1311. $table = $this->getTableLocator()->get('Articles');
  1312. $table->hasMany('Comments');
  1313. $table->addBehavior('Translate', ['fields' => ['title', 'body']]);
  1314. $article = $table->get(1);
  1315. $data = [
  1316. 'title' => 'New title',
  1317. 'body' => 'New body',
  1318. ];
  1319. $article = $table->patchEntity($article, $data);
  1320. $table->save($article);
  1321. $this->assertNull($article->get('_i18n'));
  1322. $article = $table->get(1);
  1323. $this->assertEquals('New title', $article->get('title'));
  1324. $this->assertEquals('New body', $article->get('body'));
  1325. }
  1326. /**
  1327. * Tests that translations are added to the whitelist of associations to be
  1328. * saved
  1329. *
  1330. * @return void
  1331. */
  1332. public function testSaveTranslationDefaultLocale()
  1333. {
  1334. $table = $this->getTableLocator()->get('Articles');
  1335. $table->hasMany('Comments');
  1336. $table->addBehavior('Translate', ['fields' => ['title', 'body']]);
  1337. $article = $table->get(1);
  1338. $data = [
  1339. 'title' => 'New title',
  1340. 'body' => 'New body',
  1341. '_translations' => [
  1342. 'es' => [
  1343. 'title' => 'ES title',
  1344. 'body' => 'ES body',
  1345. ],
  1346. ],
  1347. ];
  1348. $article = $table->patchEntity($article, $data);
  1349. $table->save($article);
  1350. $this->assertNull($article->get('_i18n'));
  1351. $article = $table->find('translations')->where(['id' => 1])->first();
  1352. $this->assertEquals('New title', $article->get('title'));
  1353. $this->assertEquals('New body', $article->get('body'));
  1354. $this->assertEquals('ES title', $article->_translations['es']->title);
  1355. $this->assertEquals('ES body', $article->_translations['es']->body);
  1356. }
  1357. /**
  1358. * Test that no properties are enabled when the translations
  1359. * option is off.
  1360. *
  1361. * @return void
  1362. */
  1363. public function testBuildMarshalMapTranslationsOff()
  1364. {
  1365. $table = $this->getTableLocator()->get('Articles');
  1366. $table->addBehavior('Translate', ['fields' => ['title', 'body']]);
  1367. $marshaller = $table->marshaller();
  1368. $translate = $table->behaviors()->get('Translate');
  1369. $result = $translate->buildMarshalMap($marshaller, [], ['translations' => false]);
  1370. $this->assertSame([], $result);
  1371. }
  1372. /**
  1373. * Test building a marshal map with translations on.
  1374. *
  1375. * @return void
  1376. */
  1377. public function testBuildMarshalMapTranslationsOn()
  1378. {
  1379. $table = $this->getTableLocator()->get('Articles');
  1380. $table->addBehavior('Translate', ['fields' => ['title', 'body']]);
  1381. $marshaller = $table->marshaller();
  1382. $translate = $table->behaviors()->get('Translate');
  1383. $result = $translate->buildMarshalMap($marshaller, [], ['translations' => true]);
  1384. $this->assertArrayHasKey('_translations', $result);
  1385. $this->assertInstanceOf('Closure', $result['_translations']);
  1386. $result = $translate->buildMarshalMap($marshaller, [], []);
  1387. $this->assertArrayHasKey('_translations', $result);
  1388. $this->assertInstanceOf('Closure', $result['_translations']);
  1389. }
  1390. /**
  1391. * Test marshalling non-array data
  1392. *
  1393. * @return void
  1394. */
  1395. public function testBuildMarshalMapNonArrayData()
  1396. {
  1397. $table = $this->getTableLocator()->get('Articles');
  1398. $table->addBehavior('Translate', ['fields' => ['title', 'body']]);
  1399. $translate = $table->behaviors()->get('Translate');
  1400. $map = $translate->buildMarshalMap($table->marshaller(), [], []);
  1401. $entity = $table->newEntity();
  1402. $result = $map['_translations']('garbage', $entity);
  1403. $this->assertNull($result, 'Non-array should not error out.');
  1404. $this->assertEmpty($entity->getErrors());
  1405. $this->assertEmpty($entity->get('_translations'));
  1406. }
  1407. /**
  1408. * Test buildMarshalMap() builds new entities.
  1409. *
  1410. * @return void
  1411. */
  1412. public function testBuildMarshalMapBuildEntities()
  1413. {
  1414. $table = $this->getTableLocator()->get('Articles');
  1415. $table->addBehavior('Translate', ['fields' => ['title', 'body']]);
  1416. $translate = $table->behaviors()->get('Translate');
  1417. $map = $translate->buildMarshalMap($table->marshaller(), [], []);
  1418. $entity = $table->newEntity();
  1419. $data = [
  1420. 'en' => [
  1421. 'title' => 'English Title',
  1422. 'body' => 'English Content',
  1423. ],
  1424. 'es' => [
  1425. 'title' => 'Titulo Español',
  1426. 'body' => 'Contenido Español',
  1427. ],
  1428. ];
  1429. $result = $map['_translations']($data, $entity);
  1430. $this->assertEmpty($entity->getErrors(), 'No validation errors.');
  1431. $this->assertCount(2, $result);
  1432. $this->assertArrayHasKey('en', $result);
  1433. $this->assertArrayHasKey('es', $result);
  1434. $this->assertEquals('English Title', $result['en']->title);
  1435. $this->assertEquals('Titulo Español', $result['es']->title);
  1436. }
  1437. /**
  1438. * Test that validation errors are added to the original entity.
  1439. *
  1440. * @return void
  1441. */
  1442. public function testBuildMarshalMapBuildEntitiesValidationErrors()
  1443. {
  1444. $table = $this->getTableLocator()->get('Articles');
  1445. $table->addBehavior('Translate', [
  1446. 'fields' => ['title', 'body'],
  1447. 'validator' => 'custom',
  1448. ]);
  1449. $validator = (new Validator())->add('title', 'notBlank', ['rule' => 'notBlank']);
  1450. $table->setValidator('custom', $validator);
  1451. $translate = $table->behaviors()->get('Translate');
  1452. $entity = $table->newEntity();
  1453. $map = $translate->buildMarshalMap($table->marshaller(), [], []);
  1454. $data = [
  1455. 'en' => [
  1456. 'title' => 'English Title',
  1457. 'body' => 'English Content',
  1458. ],
  1459. 'es' => [
  1460. 'title' => '',
  1461. 'body' => 'Contenido Español',
  1462. ],
  1463. ];
  1464. $result = $map['_translations']($data, $entity);
  1465. $this->assertNotEmpty($entity->getErrors(), 'Needs validation errors.');
  1466. $expected = [
  1467. 'title' => [
  1468. '_empty' => 'This field cannot be left empty',
  1469. ],
  1470. ];
  1471. $this->assertEquals($expected, $entity->getError('es'));
  1472. $this->assertEquals('English Title', $result['en']->title);
  1473. $this->assertEquals('', $result['es']->title);
  1474. }
  1475. /**
  1476. * Test that marshalling updates existing translation entities.
  1477. *
  1478. * @return void
  1479. */
  1480. public function testBuildMarshalMapUpdateExistingEntities()
  1481. {
  1482. $table = $this->getTableLocator()->get('Articles');
  1483. $table->addBehavior('Translate', [
  1484. 'fields' => ['title', 'body'],
  1485. ]);
  1486. $translate = $table->behaviors()->get('Translate');
  1487. $entity = $table->newEntity();
  1488. $es = $table->newEntity(['title' => 'Old title', 'body' => 'Old body']);
  1489. $en = $table->newEntity(['title' => 'Old title', 'body' => 'Old body']);
  1490. $entity->set('_translations', [
  1491. 'es' => $es,
  1492. 'en' => $en,
  1493. ]);
  1494. $map = $translate->buildMarshalMap($table->marshaller(), [], []);
  1495. $data = [
  1496. 'en' => [
  1497. 'title' => 'English Title',
  1498. ],
  1499. 'es' => [
  1500. 'title' => 'Spanish Title',
  1501. ],
  1502. ];
  1503. $result = $map['_translations']($data, $entity);
  1504. $this->assertEmpty($entity->getErrors(), 'No validation errors.');
  1505. $this->assertSame($en, $result['en']);
  1506. $this->assertSame($es, $result['es']);
  1507. $this->assertSame($en, $entity->get('_translations')['en']);
  1508. $this->assertSame($es, $entity->get('_translations')['es']);
  1509. $this->assertEquals('English Title', $result['en']->title);
  1510. $this->assertEquals('Spanish Title', $result['es']->title);
  1511. $this->assertEquals('Old body', $result['en']->body);
  1512. $this->assertEquals('Old body', $result['es']->body);
  1513. }
  1514. /**
  1515. * Test that updating translation records works with validations.
  1516. *
  1517. * @return void
  1518. */
  1519. public function testBuildMarshalMapUpdateEntitiesValidationErrors()
  1520. {
  1521. $table = $this->getTableLocator()->get('Articles');
  1522. $table->addBehavior('Translate', [
  1523. 'fields' => ['title', 'body'],
  1524. 'validator' => 'custom',
  1525. ]);
  1526. $validator = (new Validator())->add('title', 'notBlank', ['rule' => 'notBlank']);
  1527. $table->setValidator('custom', $validator);
  1528. $translate = $table->behaviors()->get('Translate');
  1529. $entity = $table->newEntity();
  1530. $es = $table->newEntity(['title' => 'Old title', 'body' => 'Old body']);
  1531. $en = $table->newEntity(['title' => 'Old title', 'body' => 'Old body']);
  1532. $entity->set('_translations', [
  1533. 'es' => $es,
  1534. 'en' => $en,
  1535. ]);
  1536. $map = $translate->buildMarshalMap($table->marshaller(), [], []);
  1537. $data = [
  1538. 'en' => [
  1539. 'title' => 'English Title',
  1540. 'body' => 'English Content',
  1541. ],
  1542. 'es' => [
  1543. 'title' => '',
  1544. 'body' => 'Contenido Español',
  1545. ],
  1546. ];
  1547. $result = $map['_translations']($data, $entity);
  1548. $this->assertNotEmpty($entity->getErrors(), 'Needs validation errors.');
  1549. $expected = [
  1550. 'title' => [
  1551. '_empty' => 'This field cannot be left empty',
  1552. ],
  1553. ];
  1554. $this->assertEquals($expected, $entity->getError('es'));
  1555. }
  1556. /**
  1557. * Test that the behavior uses associations' locator.
  1558. *
  1559. * @return void
  1560. */
  1561. public function testDefaultTableLocator()
  1562. {
  1563. $locator = new TableLocator();
  1564. $table = $locator->get('Articles');
  1565. $table->addBehavior('Translate', [
  1566. 'fields' => ['title', 'body'],
  1567. 'validator' => 'custom',
  1568. ]);
  1569. $behaviorLocator = $table->behaviors()->get('Translate')->getTableLocator();
  1570. $this->assertSame($locator, $behaviorLocator);
  1571. $this->assertSame($table->associations()->getTableLocator(), $behaviorLocator);
  1572. $this->assertNotSame($this->getTableLocator(), $behaviorLocator);
  1573. }
  1574. /**
  1575. * Test that the behavior uses a custom locator.
  1576. *
  1577. * @return void
  1578. */
  1579. public function testCustomTableLocator()
  1580. {
  1581. $locator = new TableLocator();
  1582. $table = $this->getTableLocator()->get('Articles');
  1583. $table->addBehavior('Translate', [
  1584. 'fields' => ['title', 'body'],
  1585. 'validator' => 'custom',
  1586. 'tableLocator' => $locator,
  1587. ]);
  1588. $behaviorLocator = $table->behaviors()->get('Translate')->getTableLocator();
  1589. $this->assertSame($locator, $behaviorLocator);
  1590. $this->assertNotSame($table->associations()->getTableLocator(), $behaviorLocator);
  1591. $this->assertNotSame($this->getTableLocator(), $behaviorLocator);
  1592. }
  1593. }