TranslateBehavior.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707
  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. * @package Cake.Model.Behavior
  13. * @since CakePHP(tm) v 1.2.0.4525
  14. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  15. */
  16. App::uses('ModelBehavior', 'Model');
  17. App::uses('I18n', 'I18n');
  18. App::uses('I18nModel', 'Model');
  19. /**
  20. * Translate behavior
  21. *
  22. * @package Cake.Model.Behavior
  23. * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/translate.html
  24. */
  25. class TranslateBehavior extends ModelBehavior {
  26. /**
  27. * Used for runtime configuration of model
  28. *
  29. * @var array
  30. */
  31. public $runtime = array();
  32. /**
  33. * Stores the joinTable object for generating joins.
  34. *
  35. * @var object
  36. */
  37. protected $_joinTable;
  38. /**
  39. * Stores the runtime model for generating joins.
  40. *
  41. * @var Model
  42. */
  43. protected $_runtimeModel;
  44. /**
  45. * Callback
  46. *
  47. * $config for TranslateBehavior should be
  48. * array('fields' => array('field_one',
  49. * 'field_two' => 'FieldAssoc', 'field_three'))
  50. *
  51. * With above example only one permanent hasMany will be joined (for field_two
  52. * as FieldAssoc)
  53. *
  54. * $config could be empty - and translations configured dynamically by
  55. * bindTranslation() method
  56. *
  57. * @param Model $Model Model the behavior is being attached to.
  58. * @param array $config Array of configuration information.
  59. * @return mixed
  60. */
  61. public function setup(Model $Model, $config = array()) {
  62. $db = ConnectionManager::getDataSource($Model->useDbConfig);
  63. if (!$db->connected) {
  64. trigger_error(
  65. __d('cake_dev', 'Datasource %s for TranslateBehavior of model %s is not connected', $Model->useDbConfig, $Model->alias),
  66. E_USER_ERROR
  67. );
  68. return false;
  69. }
  70. $this->settings[$Model->alias] = array();
  71. $this->runtime[$Model->alias] = array('fields' => array());
  72. $this->translateModel($Model);
  73. return $this->bindTranslation($Model, $config, false);
  74. }
  75. /**
  76. * Cleanup Callback unbinds bound translations and deletes setting information.
  77. *
  78. * @param Model $Model Model being detached.
  79. * @return void
  80. */
  81. public function cleanup(Model $Model) {
  82. $this->unbindTranslation($Model);
  83. unset($this->settings[$Model->alias]);
  84. unset($this->runtime[$Model->alias]);
  85. }
  86. /**
  87. * beforeFind Callback
  88. *
  89. * @param Model $Model Model find is being run on.
  90. * @param array $query Array of Query parameters.
  91. * @return array Modified query
  92. */
  93. public function beforeFind(Model $Model, $query) {
  94. $this->runtime[$Model->alias]['virtualFields'] = $Model->virtualFields;
  95. $locale = $this->_getLocale($Model);
  96. if (empty($locale)) {
  97. return $query;
  98. }
  99. $db = $Model->getDataSource();
  100. $RuntimeModel = $this->translateModel($Model);
  101. if (!empty($RuntimeModel->tablePrefix)) {
  102. $tablePrefix = $RuntimeModel->tablePrefix;
  103. } else {
  104. $tablePrefix = $db->config['prefix'];
  105. }
  106. $joinTable = new StdClass();
  107. $joinTable->tablePrefix = $tablePrefix;
  108. $joinTable->table = $RuntimeModel->table;
  109. $joinTable->schemaName = $RuntimeModel->getDataSource()->getSchemaName();
  110. $this->_joinTable = $joinTable;
  111. $this->_runtimeModel = $RuntimeModel;
  112. if (is_string($query['fields']) && $query['fields'] === "COUNT(*) AS {$db->name('count')}") {
  113. $query['fields'] = "COUNT(DISTINCT({$db->name($Model->escapeField())})) {$db->alias}count";
  114. $query['joins'][] = array(
  115. 'type' => 'INNER',
  116. 'alias' => $RuntimeModel->alias,
  117. 'table' => $joinTable,
  118. 'conditions' => array(
  119. $Model->escapeField() => $db->identifier($RuntimeModel->escapeField('foreign_key')),
  120. $RuntimeModel->escapeField('model') => $Model->name,
  121. $RuntimeModel->escapeField('locale') => $locale
  122. )
  123. );
  124. $conditionFields = $this->_checkConditions($Model, $query);
  125. foreach ($conditionFields as $field) {
  126. $query = $this->_addJoin($Model, $query, $field, $field, $locale);
  127. }
  128. unset($this->_joinTable, $this->_runtimeModel);
  129. return $query;
  130. } elseif (is_string($query['fields'])) {
  131. $query['fields'] = String::tokenize($query['fields']);
  132. }
  133. $fields = array_merge(
  134. $this->settings[$Model->alias],
  135. $this->runtime[$Model->alias]['fields']
  136. );
  137. $addFields = array();
  138. if (empty($query['fields'])) {
  139. $addFields = $fields;
  140. } elseif (is_array($query['fields'])) {
  141. $isAllFields = (
  142. in_array($Model->alias . '.' . '*', $query['fields']) ||
  143. in_array($Model->escapeField('*'), $query['fields'])
  144. );
  145. foreach ($fields as $key => $value) {
  146. $field = (is_numeric($key)) ? $value : $key;
  147. if (
  148. $isAllFields ||
  149. in_array($Model->alias . '.' . $field, $query['fields']) ||
  150. in_array($field, $query['fields'])
  151. ) {
  152. $addFields[] = $field;
  153. }
  154. }
  155. }
  156. $this->runtime[$Model->alias]['virtualFields'] = $Model->virtualFields;
  157. if ($addFields) {
  158. foreach ($addFields as $_f => $field) {
  159. $aliasField = is_numeric($_f) ? $field : $_f;
  160. foreach (array($aliasField, $Model->alias . '.' . $aliasField) as $_field) {
  161. $key = array_search($_field, (array)$query['fields']);
  162. if ($key !== false) {
  163. unset($query['fields'][$key]);
  164. }
  165. }
  166. $query = $this->_addJoin($Model, $query, $field, $aliasField, $locale);
  167. }
  168. }
  169. $this->runtime[$Model->alias]['beforeFind'] = $addFields;
  170. unset($this->_joinTable, $this->_runtimeModel);
  171. return $query;
  172. }
  173. /**
  174. * Check a query's conditions for translated fields.
  175. * Return an array of translated fields found in the conditions.
  176. *
  177. * @param Model $Model The model being read.
  178. * @param array $query The query array.
  179. * @return array The list of translated fields that are in the conditions.
  180. */
  181. protected function _checkConditions(Model $Model, $query) {
  182. $conditionFields = array();
  183. if (empty($query['conditions']) || (!empty($query['conditions']) && !is_array($query['conditions']))) {
  184. return $conditionFields;
  185. }
  186. foreach ($query['conditions'] as $col => $val) {
  187. foreach ($this->settings[$Model->alias] as $field => $assoc) {
  188. if (is_numeric($field)) {
  189. $field = $assoc;
  190. }
  191. if (strpos($col, $field) !== false) {
  192. $conditionFields[] = $field;
  193. }
  194. }
  195. }
  196. return $conditionFields;
  197. }
  198. /**
  199. * Appends a join for translated fields.
  200. *
  201. * @param Model $Model The model being worked on.
  202. * @param array $query The query array to append a join to.
  203. * @param string $field The field name being joined.
  204. * @param string $aliasField The aliased field name being joined.
  205. * @param string|array $locale The locale(s) having joins added.
  206. * @return array The modified query
  207. */
  208. protected function _addJoin(Model $Model, $query, $field, $aliasField, $locale) {
  209. $db = ConnectionManager::getDataSource($Model->useDbConfig);
  210. $RuntimeModel = $this->_runtimeModel;
  211. $joinTable = $this->_joinTable;
  212. $aliasVirtual = "i18n_{$field}";
  213. $alias = "I18n__{$field}";
  214. if (is_array($locale)) {
  215. foreach ($locale as $_locale) {
  216. $aliasVirtualLocale = "{$aliasVirtual}_{$_locale}";
  217. $aliasLocale = "{$alias}__{$_locale}";
  218. $Model->virtualFields[$aliasVirtualLocale] = "{$aliasLocale}.content";
  219. if (!empty($query['fields']) && is_array($query['fields'])) {
  220. $query['fields'][] = $aliasVirtualLocale;
  221. }
  222. $query['joins'][] = array(
  223. 'type' => 'LEFT',
  224. 'alias' => $aliasLocale,
  225. 'table' => $joinTable,
  226. 'conditions' => array(
  227. $Model->escapeField() => $db->identifier("{$aliasLocale}.foreign_key"),
  228. "{$aliasLocale}.model" => $Model->name,
  229. "{$aliasLocale}.{$RuntimeModel->displayField}" => $aliasField,
  230. "{$aliasLocale}.locale" => $_locale
  231. )
  232. );
  233. }
  234. } else {
  235. $Model->virtualFields[$aliasVirtual] = "{$alias}.content";
  236. if (!empty($query['fields']) && is_array($query['fields'])) {
  237. $query['fields'][] = $aliasVirtual;
  238. }
  239. $query['joins'][] = array(
  240. 'type' => 'INNER',
  241. 'alias' => $alias,
  242. 'table' => $joinTable,
  243. 'conditions' => array(
  244. "{$Model->alias}.{$Model->primaryKey}" => $db->identifier("{$alias}.foreign_key"),
  245. "{$alias}.model" => $Model->name,
  246. "{$alias}.{$RuntimeModel->displayField}" => $aliasField,
  247. "{$alias}.locale" => $locale
  248. )
  249. );
  250. }
  251. return $query;
  252. }
  253. /**
  254. * afterFind Callback
  255. *
  256. * @param Model $Model Model find was run on
  257. * @param array $results Array of model results.
  258. * @param bool $primary Did the find originate on $model.
  259. * @return array Modified results
  260. */
  261. public function afterFind(Model $Model, $results, $primary = false) {
  262. $Model->virtualFields = $this->runtime[$Model->alias]['virtualFields'];
  263. $this->runtime[$Model->alias]['virtualFields'] = $this->runtime[$Model->alias]['fields'] = array();
  264. if (!empty($this->runtime[$Model->alias]['restoreFields'])) {
  265. $this->runtime[$Model->alias]['fields'] = $this->runtime[$Model->alias]['restoreFields'];
  266. unset($this->runtime[$Model->alias]['restoreFields']);
  267. }
  268. $locale = $this->_getLocale($Model);
  269. if (empty($locale) || empty($results) || empty($this->runtime[$Model->alias]['beforeFind'])) {
  270. return $results;
  271. }
  272. $beforeFind = $this->runtime[$Model->alias]['beforeFind'];
  273. foreach ($results as $key => &$row) {
  274. $results[$key][$Model->alias]['locale'] = (is_array($locale)) ? current($locale) : $locale;
  275. foreach ($beforeFind as $_f => $field) {
  276. $aliasField = is_numeric($_f) ? $field : $_f;
  277. $aliasVirtual = "i18n_{$field}";
  278. if (is_array($locale)) {
  279. foreach ($locale as $_locale) {
  280. $aliasVirtualLocale = "{$aliasVirtual}_{$_locale}";
  281. if (!isset($row[$Model->alias][$aliasField]) && !empty($row[$Model->alias][$aliasVirtualLocale])) {
  282. $row[$Model->alias][$aliasField] = $row[$Model->alias][$aliasVirtualLocale];
  283. $row[$Model->alias]['locale'] = $_locale;
  284. }
  285. unset($row[$Model->alias][$aliasVirtualLocale]);
  286. }
  287. if (!isset($row[$Model->alias][$aliasField])) {
  288. $row[$Model->alias][$aliasField] = '';
  289. }
  290. } else {
  291. $value = '';
  292. if (isset($row[$Model->alias][$aliasVirtual])) {
  293. $value = $row[$Model->alias][$aliasVirtual];
  294. }
  295. $row[$Model->alias][$aliasField] = $value;
  296. unset($row[$Model->alias][$aliasVirtual]);
  297. }
  298. }
  299. }
  300. return $results;
  301. }
  302. /**
  303. * beforeValidate Callback
  304. *
  305. * @param Model $Model Model invalidFields was called on.
  306. * @param array $options Options passed from Model::save().
  307. * @return bool
  308. * @see Model::save()
  309. */
  310. public function beforeValidate(Model $Model, $options = array()) {
  311. unset($this->runtime[$Model->alias]['beforeSave']);
  312. $this->_setRuntimeData($Model);
  313. return true;
  314. }
  315. /**
  316. * beforeSave callback.
  317. *
  318. * Copies data into the runtime property when `$options['validate']` is
  319. * disabled. Or the runtime data hasn't been set yet.
  320. *
  321. * @param Model $Model Model save was called on.
  322. * @param array $options Options passed from Model::save().
  323. * @return bool true.
  324. * @see Model::save()
  325. */
  326. public function beforeSave(Model $Model, $options = array()) {
  327. if (isset($options['validate']) && !$options['validate']) {
  328. unset($this->runtime[$Model->alias]['beforeSave']);
  329. }
  330. if (isset($this->runtime[$Model->alias]['beforeSave'])) {
  331. return true;
  332. }
  333. $this->_setRuntimeData($Model);
  334. return true;
  335. }
  336. /**
  337. * Sets the runtime data.
  338. *
  339. * Used from beforeValidate() and beforeSave() for compatibility issues,
  340. * and to allow translations to be persisted even when validation
  341. * is disabled.
  342. *
  343. * @param Model $Model Model using this behavior.
  344. * @return void
  345. */
  346. protected function _setRuntimeData(Model $Model) {
  347. $locale = $this->_getLocale($Model);
  348. if (empty($locale)) {
  349. return true;
  350. }
  351. $fields = array_merge($this->settings[$Model->alias], $this->runtime[$Model->alias]['fields']);
  352. $tempData = array();
  353. foreach ($fields as $key => $value) {
  354. $field = (is_numeric($key)) ? $value : $key;
  355. if (isset($Model->data[$Model->alias][$field])) {
  356. $tempData[$field] = $Model->data[$Model->alias][$field];
  357. if (is_array($Model->data[$Model->alias][$field])) {
  358. if (is_string($locale) && !empty($Model->data[$Model->alias][$field][$locale])) {
  359. $Model->data[$Model->alias][$field] = $Model->data[$Model->alias][$field][$locale];
  360. } else {
  361. $values = array_values($Model->data[$Model->alias][$field]);
  362. $Model->data[$Model->alias][$field] = $values[0];
  363. }
  364. }
  365. }
  366. }
  367. $this->runtime[$Model->alias]['beforeSave'] = $tempData;
  368. }
  369. /**
  370. * Restores model data to the original data.
  371. * This solves issues with saveAssociated and validate = first.
  372. *
  373. * @param Model $Model Model using this behavior.
  374. * @return void
  375. */
  376. public function afterValidate(Model $Model) {
  377. $Model->data[$Model->alias] = array_merge(
  378. $Model->data[$Model->alias],
  379. $this->runtime[$Model->alias]['beforeSave']
  380. );
  381. return true;
  382. }
  383. /**
  384. * afterSave Callback
  385. *
  386. * @param Model $Model Model the callback is called on
  387. * @param bool $created Whether or not the save created a record.
  388. * @param array $options Options passed from Model::save().
  389. * @return void
  390. */
  391. public function afterSave(Model $Model, $created, $options = array()) {
  392. if (!isset($this->runtime[$Model->alias]['beforeValidate']) && !isset($this->runtime[$Model->alias]['beforeSave'])) {
  393. return true;
  394. }
  395. if (isset($this->runtime[$Model->alias]['beforeValidate'])) {
  396. $tempData = $this->runtime[$Model->alias]['beforeValidate'];
  397. } else {
  398. $tempData = $this->runtime[$Model->alias]['beforeSave'];
  399. }
  400. unset($this->runtime[$Model->alias]['beforeValidate'], $this->runtime[$Model->alias]['beforeSave']);
  401. $conditions = array('model' => $Model->name, 'foreign_key' => $Model->id);
  402. $RuntimeModel = $this->translateModel($Model);
  403. if ($created) {
  404. $tempData = $this->_prepareTranslations($Model, $tempData);
  405. }
  406. $locale = $this->_getLocale($Model);
  407. foreach ($tempData as $field => $value) {
  408. unset($conditions['content']);
  409. $conditions['field'] = $field;
  410. if (is_array($value)) {
  411. $conditions['locale'] = array_keys($value);
  412. } else {
  413. $conditions['locale'] = $locale;
  414. if (is_array($locale)) {
  415. $value = array($locale[0] => $value);
  416. } else {
  417. $value = array($locale => $value);
  418. }
  419. }
  420. $translations = $RuntimeModel->find('list', array(
  421. 'conditions' => $conditions,
  422. 'fields' => array(
  423. $RuntimeModel->alias . '.locale',
  424. $RuntimeModel->alias . '.id'
  425. )
  426. ));
  427. foreach ($value as $_locale => $_value) {
  428. $RuntimeModel->create();
  429. $conditions['locale'] = $_locale;
  430. $conditions['content'] = $_value;
  431. if (array_key_exists($_locale, $translations)) {
  432. $RuntimeModel->save(array(
  433. $RuntimeModel->alias => array_merge(
  434. $conditions, array('id' => $translations[$_locale])
  435. )
  436. ));
  437. } else {
  438. $RuntimeModel->save(array($RuntimeModel->alias => $conditions));
  439. }
  440. }
  441. }
  442. }
  443. /**
  444. * Prepares the data to be saved for translated records.
  445. * Add blank fields, and populates data for multi-locale saves.
  446. *
  447. * @param Model $Model Model using this behavior
  448. * @param array $data The sparse data that was provided.
  449. * @return array The fully populated data to save.
  450. */
  451. protected function _prepareTranslations(Model $Model, $data) {
  452. $fields = array_merge($this->settings[$Model->alias], $this->runtime[$Model->alias]['fields']);
  453. $locales = array();
  454. foreach ($data as $key => $value) {
  455. if (is_array($value)) {
  456. $locales = array_merge($locales, array_keys($value));
  457. }
  458. }
  459. $locales = array_unique($locales);
  460. $hasLocales = count($locales) > 0;
  461. foreach ($fields as $key => $field) {
  462. if (!is_numeric($key)) {
  463. $field = $key;
  464. }
  465. if ($hasLocales && !isset($data[$field])) {
  466. $data[$field] = array_fill_keys($locales, '');
  467. } elseif (!isset($data[$field])) {
  468. $data[$field] = '';
  469. }
  470. }
  471. return $data;
  472. }
  473. /**
  474. * afterDelete Callback
  475. *
  476. * @param Model $Model Model the callback was run on.
  477. * @return void
  478. */
  479. public function afterDelete(Model $Model) {
  480. $RuntimeModel = $this->translateModel($Model);
  481. $conditions = array('model' => $Model->name, 'foreign_key' => $Model->id);
  482. $RuntimeModel->deleteAll($conditions);
  483. }
  484. /**
  485. * Get selected locale for model
  486. *
  487. * @param Model $Model Model the locale needs to be set/get on.
  488. * @return mixed string or false
  489. */
  490. protected function _getLocale(Model $Model) {
  491. if (!isset($Model->locale) || $Model->locale === null) {
  492. $I18n = I18n::getInstance();
  493. $I18n->l10n->get(Configure::read('Config.language'));
  494. $Model->locale = $I18n->l10n->locale;
  495. }
  496. return $Model->locale;
  497. }
  498. /**
  499. * Get instance of model for translations.
  500. *
  501. * If the model has a translateModel property set, this will be used as the class
  502. * name to find/use. If no translateModel property is found 'I18nModel' will be used.
  503. *
  504. * @param Model $Model Model to get a translatemodel for.
  505. * @return Model
  506. */
  507. public function translateModel(Model $Model) {
  508. if (!isset($this->runtime[$Model->alias]['model'])) {
  509. if (!isset($Model->translateModel) || empty($Model->translateModel)) {
  510. $className = 'I18nModel';
  511. } else {
  512. $className = $Model->translateModel;
  513. }
  514. $this->runtime[$Model->alias]['model'] = ClassRegistry::init($className);
  515. }
  516. if (!empty($Model->translateTable) && $Model->translateTable !== $this->runtime[$Model->alias]['model']->useTable) {
  517. $this->runtime[$Model->alias]['model']->setSource($Model->translateTable);
  518. } elseif (empty($Model->translateTable) && empty($Model->translateModel)) {
  519. $this->runtime[$Model->alias]['model']->setSource('i18n');
  520. }
  521. return $this->runtime[$Model->alias]['model'];
  522. }
  523. /**
  524. * Bind translation for fields, optionally with hasMany association for
  525. * fake field.
  526. *
  527. * *Note* You should avoid binding translations that overlap existing model properties.
  528. * This can cause un-expected and un-desirable behavior.
  529. *
  530. * @param Model $Model using this behavior of model
  531. * @param string|array $fields string with field or array(field1, field2=>AssocName, field3)
  532. * @param bool $reset Leave true to have the fields only modified for the next operation.
  533. * if false the field will be added for all future queries.
  534. * @return bool
  535. * @throws CakeException when attempting to bind a translating called name. This is not allowed
  536. * as it shadows Model::$name.
  537. */
  538. public function bindTranslation(Model $Model, $fields, $reset = true) {
  539. if (is_string($fields)) {
  540. $fields = array($fields);
  541. }
  542. $associations = array();
  543. $RuntimeModel = $this->translateModel($Model);
  544. $default = array(
  545. 'className' => $RuntimeModel->alias,
  546. 'foreignKey' => 'foreign_key'
  547. );
  548. foreach ($fields as $key => $value) {
  549. if (is_numeric($key)) {
  550. $field = $value;
  551. $association = null;
  552. } else {
  553. $field = $key;
  554. $association = $value;
  555. }
  556. if ($association === 'name') {
  557. throw new CakeException(
  558. __d('cake_dev', 'You cannot bind a translation named "name".')
  559. );
  560. }
  561. $this->_removeField($Model, $field);
  562. if ($association === null) {
  563. if ($reset) {
  564. $this->runtime[$Model->alias]['fields'][] = $field;
  565. } else {
  566. $this->settings[$Model->alias][] = $field;
  567. }
  568. } else {
  569. if ($reset) {
  570. $this->runtime[$Model->alias]['fields'][$field] = $association;
  571. $this->runtime[$Model->alias]['restoreFields'][] = $field;
  572. } else {
  573. $this->settings[$Model->alias][$field] = $association;
  574. }
  575. foreach (array('hasOne', 'hasMany', 'belongsTo', 'hasAndBelongsToMany') as $type) {
  576. if (isset($Model->{$type}[$association]) || isset($Model->__backAssociation[$type][$association])) {
  577. trigger_error(
  578. __d('cake_dev', 'Association %s is already bound to model %s', $association, $Model->alias),
  579. E_USER_ERROR
  580. );
  581. return false;
  582. }
  583. }
  584. $associations[$association] = array_merge($default, array('conditions' => array(
  585. 'model' => $Model->name,
  586. $RuntimeModel->displayField => $field
  587. )));
  588. }
  589. }
  590. if (!empty($associations)) {
  591. $Model->bindModel(array('hasMany' => $associations), $reset);
  592. }
  593. return true;
  594. }
  595. /**
  596. * Update runtime setting for a given field.
  597. *
  598. * @param Model $Model Model using this behavior
  599. * @param string $field The field to update.
  600. * @return void
  601. */
  602. protected function _removeField(Model $Model, $field) {
  603. if (array_key_exists($field, $this->settings[$Model->alias])) {
  604. unset($this->settings[$Model->alias][$field]);
  605. } elseif (in_array($field, $this->settings[$Model->alias])) {
  606. $this->settings[$Model->alias] = array_merge(array_diff($this->settings[$Model->alias], array($field)));
  607. }
  608. if (array_key_exists($field, $this->runtime[$Model->alias]['fields'])) {
  609. unset($this->runtime[$Model->alias]['fields'][$field]);
  610. } elseif (in_array($field, $this->runtime[$Model->alias]['fields'])) {
  611. $this->runtime[$Model->alias]['fields'] = array_merge(array_diff($this->runtime[$Model->alias]['fields'], array($field)));
  612. }
  613. }
  614. /**
  615. * Unbind translation for fields, optionally unbinds hasMany association for
  616. * fake field
  617. *
  618. * @param Model $Model using this behavior of model
  619. * @param string|array $fields string with field, or array(field1, field2=>AssocName, field3), or null for
  620. * unbind all original translations
  621. * @return bool
  622. */
  623. public function unbindTranslation(Model $Model, $fields = null) {
  624. if (empty($fields) && empty($this->settings[$Model->alias])) {
  625. return false;
  626. }
  627. if (empty($fields)) {
  628. return $this->unbindTranslation($Model, $this->settings[$Model->alias]);
  629. }
  630. if (is_string($fields)) {
  631. $fields = array($fields);
  632. }
  633. $associations = array();
  634. foreach ($fields as $key => $value) {
  635. if (is_numeric($key)) {
  636. $field = $value;
  637. $association = null;
  638. } else {
  639. $field = $key;
  640. $association = $value;
  641. }
  642. $this->_removeField($Model, $field);
  643. if ($association !== null && (isset($Model->hasMany[$association]) || isset($Model->__backAssociation['hasMany'][$association]))) {
  644. $associations[] = $association;
  645. }
  646. }
  647. if (!empty($associations)) {
  648. $Model->unbindModel(array('hasMany' => $associations), false);
  649. }
  650. return true;
  651. }
  652. }