TranslateTrait.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://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. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 3.0.0
  13. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  14. */
  15. namespace Cake\Model\Behavior\Translate;
  16. use Cake\ORM\Entity;
  17. /**
  18. * Contains a translation method aimed to help managing multiple translations
  19. * for an entity.
  20. */
  21. trait TranslateTrait {
  22. /**
  23. * Returns the entity containing the translated fields for this object and for
  24. * the specified language. If the translation for the passed language is not
  25. * present, a new empty entity will be created so that values can be added to
  26. * it.
  27. *
  28. * @param string $language Language to return entity for.
  29. * @return \Cake\ORM\Entity
  30. */
  31. public function translation($language) {
  32. if ($language === $this->get('_locale')) {
  33. return $this;
  34. }
  35. $i18n = $this->get('_translations');
  36. $created = false;
  37. if (empty($i18n)) {
  38. $i18n = [];
  39. $created = true;
  40. }
  41. if ($created || empty($i18n[$language]) || !($i18n[$language] instanceof Entity)) {
  42. $i18n[$language] = new Entity();
  43. $created = true;
  44. }
  45. if ($created) {
  46. $this->set('_translations', $i18n);
  47. }
  48. // Assume the user will modify any of the internal translations, helps with saving
  49. $this->dirty('_translations', true);
  50. return $i18n[$language];
  51. }
  52. }