LinkableBehavior.php 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. <?php
  2. App::uses('ModelBehavior', 'Model');
  3. /**
  4. * LinkableBehavior
  5. * Light-weight approach for data mining on deep relations between models.
  6. * Join tables based on model relations to easily enable right to left find operations.
  7. * Original behavior by rafaelbandeira3 on GitHub.
  8. * Includes modifications from Terr, n8man, and Chad Jablonski
  9. *
  10. * Licensed under The MIT License
  11. * Redistributions of files must retain the above copyright notice.
  12. *
  13. * GiulianoB ( https://github.com/giulianob/linkable )
  14. *
  15. * @version 1.0;
  16. *
  17. * @version 1.1:
  18. * -Brought in improvements and test cases from Terr. However, THIS VERSION OF LINKABLE IS NOT DROP IN COMPATIBLE WITH Terr's VERSION!
  19. * -If fields aren't specified, will now return all columns of that model
  20. * -No need to specify the foreign key condition if a custom condition is given. Linkable will automatically include the foreign key relationship.
  21. * -Ability to specify the exact condition Linkable should use (e.g. $this->Post->find('first', array('link' => array('User' => array('conditions' => array('exactly' => 'User.last_post_id = Post.id'))))) )
  22. * This is usually required when doing on-the-fly joins since Linkable generally assumes a belongsTo relationship when no specific relationship is found and may produce invalid foreign key conditions.
  23. * -Linkable will no longer break queries that use SQL COUNTs
  24. *
  25. * @version 1.2:
  26. * @modified Mark Scherer
  27. * - works with cakephp2.x (89.84 test coverage)
  28. */
  29. class LinkableBehavior extends ModelBehavior {
  30. protected $_key = 'link';
  31. protected $_options = array(
  32. 'type' => true, 'table' => true, 'alias' => true,
  33. 'conditions' => true, 'fields' => true, 'reference' => true,
  34. 'class' => true, 'defaults' => true
  35. );
  36. protected $_defaults = array('type' => 'LEFT');
  37. public function beforeFind(Model $Model, $query) {
  38. if (isset($query[$this->_key])) {
  39. $optionsDefaults = $this->_defaults + array('reference' => $Model->alias, $this->_key => array());
  40. $optionsKeys = $this->_options + array($this->_key => true);
  41. // If containable is being used, then let it set the recursive!
  42. if (empty($query['contain'])) {
  43. $query = array_merge(array('joins' => array()), $query, array('recursive' => -1));
  44. } else {
  45. $query = array_merge(array('joins' => array()), $query);
  46. }
  47. $iterators[] = $query[$this->_key];
  48. $cont = 0;
  49. do {
  50. $iterator = $iterators[$cont];
  51. $defaults = $optionsDefaults;
  52. if (isset($iterator['defaults'])) {
  53. $defaults = array_merge($defaults, $iterator['defaults']);
  54. unset($iterator['defaults']);
  55. }
  56. $iterations = Set::normalize($iterator);
  57. foreach ($iterations as $alias => $options) {
  58. if (is_null($options)) {
  59. $options = array();
  60. }
  61. $options = array_merge($defaults, compact('alias'), $options);
  62. if (empty($options['alias'])) {
  63. throw new InvalidArgumentException(sprintf('%s::%s must receive aliased links', get_class($this), __FUNCTION__));
  64. }
  65. if (empty($options['table']) && empty($options['class'])) {
  66. $options['class'] = $options['alias'];
  67. } elseif (!empty($options['table']) && empty($options['class'])) {
  68. $options['class'] = Inflector::classify($options['table']);
  69. }
  70. // the incoming model to be linked in query
  71. $_Model = ClassRegistry::init($options['class']);
  72. // the already in query model that links to $_Model
  73. $Reference = ClassRegistry::init($options['reference']);
  74. $db = $_Model->getDataSource();
  75. $associations = $_Model->getAssociated();
  76. if (isset($Reference->belongsTo[$_Model->alias])) {
  77. $type = 'hasOne';
  78. $association = $Reference->belongsTo[$_Model->alias];
  79. } elseif (isset($Reference->hasOne[$_Model->alias])) {
  80. $type = 'belongsTo';
  81. $association = $Reference->hasOne[$_Model->alias];
  82. } elseif (isset($Reference->hasMany[$_Model->alias])) {
  83. $type = 'belongsTo';
  84. $association = $Reference->hasMany[$_Model->alias];
  85. } elseif (isset($associations[$Reference->alias])) {
  86. $type = $associations[$Reference->alias];
  87. $association = $_Model->{$type}[$Reference->alias];
  88. } else {
  89. $_Model->bindModel(array('belongsTo' => array($Reference->alias)));
  90. $type = 'belongsTo';
  91. $association = $_Model->{$type}[$Reference->alias];
  92. $_Model->unbindModel(array('belongsTo' => array($Reference->alias)));
  93. }
  94. if (!isset($options['conditions'])) {
  95. $options['conditions'] = array();
  96. } elseif (!is_array($options['conditions'])) {
  97. // Support for string conditions
  98. $options['conditions'] = array($options['conditions']);
  99. }
  100. if (isset($options['conditions']['exactly'])) {
  101. if (is_array($options['conditions']['exactly']))
  102. $options['conditions'] = reset($options['conditions']['exactly']);
  103. else
  104. $options['conditions'] = array($options['conditions']['exactly']);
  105. } else {
  106. if ($type === 'belongsTo') {
  107. $modelKey = $_Model->escapeField($association['foreignKey']);
  108. $modelKey = str_replace($_Model->alias, $options['alias'], $modelKey);
  109. $referenceKey = $Reference->escapeField($Reference->primaryKey);
  110. $options['conditions'][] = "{$referenceKey} = {$modelKey}";
  111. } elseif ($type === 'hasAndBelongsToMany') {
  112. if (isset($association['with'])) {
  113. $Link = $_Model->{$association['with']};
  114. if (isset($Link->belongsTo[$_Model->alias])) {
  115. $modelLink = $Link->escapeField($Link->belongsTo[$_Model->alias]['foreignKey']);
  116. }
  117. if (isset($Link->belongsTo[$Reference->alias])) {
  118. $referenceLink = $Link->escapeField($Link->belongsTo[$Reference->alias]['foreignKey']);
  119. }
  120. } else {
  121. $Link = $_Model->{Inflector::classify($association['joinTable'])};
  122. }
  123. if (empty($modelLink)) {
  124. $modelLink = $Link->escapeField(Inflector::underscore($_Model->alias) . '_id');
  125. }
  126. if (empty($referenceLink)) {
  127. $referenceLink = $Link->escapeField(Inflector::underscore($Reference->alias) . '_id');
  128. }
  129. $referenceKey = $Reference->escapeField();
  130. $query['joins'][] = array(
  131. 'alias' => $Link->alias,
  132. 'table' => $Link->table, //$Link->getDataSource()->fullTableName($Link),
  133. 'conditions' => "{$referenceLink} = {$referenceKey}",
  134. 'type' => 'LEFT'
  135. );
  136. $modelKey = $_Model->escapeField();
  137. $modelKey = str_replace($_Model->alias, $options['alias'], $modelKey);
  138. $options['conditions'][] = "{$modelLink} = {$modelKey}";
  139. } else {
  140. $referenceKey = $Reference->escapeField($association['foreignKey']);
  141. $modelKey = $_Model->escapeField($_Model->primaryKey);
  142. $modelKey = str_replace($_Model->alias, $options['alias'], $modelKey);
  143. $options['conditions'][] = "{$modelKey} = {$referenceKey}";
  144. }
  145. }
  146. if (empty($options['table'])) {
  147. $options['table'] = $_Model->table;
  148. }
  149. // Decide whether we should mess with the fields or not
  150. // If this query is a COUNT query then we just leave it alone
  151. if (!isset($query['fields']) || is_array($query['fields']) || strpos($query['fields'], 'COUNT(*)') === FALSE) {
  152. if (!empty($options['fields'])) {
  153. if ($options['fields'] === true && !empty($association['fields'])) {
  154. $options['fields'] = $db->fields($_Model, null, $association['fields']);
  155. } elseif ($options['fields'] === true) {
  156. $options['fields'] = $db->fields($_Model);
  157. } else {
  158. $options['fields'] = $db->fields($_Model, null, $options['fields']);
  159. }
  160. } elseif (!isset($options['fields']) || (isset($options['fields']) && !is_array($options['fields']))) {
  161. if (!empty($association['fields'])) {
  162. $options['fields'] = $db->fields($_Model, null, $association['fields']);
  163. } else {
  164. $options['fields'] = $db->fields($_Model);
  165. }
  166. }
  167. if (!empty($options['class']) && $options['class'] !== $alias) {
  168. //$options['fields'] = str_replace($options['class'], $alias, $options['fields']);
  169. }
  170. if (is_array($query['fields'])) {
  171. $query['fields'] = array_merge($query['fields'], $options['fields']);
  172. } else {
  173. // If user didn't specify any fields then select all fields by default (just as find would)
  174. $query['fields'] = array_merge($db->fields($Model), $options['fields']);
  175. }
  176. }
  177. $options[$this->_key] = array_merge($options[$this->_key], array_diff_key($options, $optionsKeys));
  178. $options = array_intersect_key($options, $optionsKeys);
  179. if (!empty($options[$this->_key])) {
  180. $iterators[] = $options[$this->_key] + array('defaults' => array_merge($defaults, array('reference' => $options['class'])));
  181. }
  182. $query['joins'][] = array_intersect_key($options, array('type' => true, 'alias' => true, 'table' => true, 'conditions' => true));
  183. }
  184. $cont++;
  185. $notDone = isset($iterators[$cont]);
  186. } while ($notDone);
  187. }
  188. unset($query['link']);
  189. return $query;
  190. }
  191. }