TranslateBehaviorTest.php 57 KB

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