LinkableBehavior.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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. * @deprecated Not actively maintained anymore, please see https://github.com/lorenzo/linkable for the most revent version.
  30. */
  31. class LinkableBehavior extends ModelBehavior {
  32. protected $_key = 'link';
  33. protected $_options = [
  34. 'type' => true, 'table' => true, 'alias' => true,
  35. 'conditions' => true, 'fields' => true, 'reference' => true,
  36. 'class' => true, 'defaults' => true
  37. ];
  38. protected $_defaultConfig = ['type' => 'LEFT'];
  39. public function beforeFind(Model $Model, $query) {
  40. if (isset($query[$this->_key])) {
  41. $optionsDefaults = $this->_defaultConfig + ['reference' => $Model->alias, $this->_key => []];
  42. $optionsKeys = $this->_options + [$this->_key => true];
  43. // If containable is being used, then let it set the recursive!
  44. if (empty($query['contain'])) {
  45. $query = array_merge(['joins' => []], $query, ['recursive' => -1]);
  46. } else {
  47. $query = array_merge(['joins' => []], $query);
  48. }
  49. $iterators[] = $query[$this->_key];
  50. $cont = 0;
  51. do {
  52. $iterator = $iterators[$cont];
  53. $defaults = $optionsDefaults;
  54. if (isset($iterator['defaults'])) {
  55. $defaults = array_merge($defaults, $iterator['defaults']);
  56. unset($iterator['defaults']);
  57. }
  58. $iterations = Set::normalize($iterator);
  59. foreach ($iterations as $alias => $options) {
  60. if ($options === null) {
  61. $options = [];
  62. }
  63. $options = array_merge($defaults, compact('alias'), $options);
  64. if (empty($options['alias'])) {
  65. throw new InvalidArgumentException(sprintf('%s::%s must receive aliased links', get_class($this), __FUNCTION__));
  66. }
  67. // try to find the class name - important for aliased relations
  68. foreach ($Model->belongsTo as $relationAlias => $relation) {
  69. if (empty($relation['className']) || $relationAlias !== $options['alias']) {
  70. continue;
  71. }
  72. $options['class'] = $relation['className'];
  73. break;
  74. }
  75. foreach ($Model->hasOne as $relationAlias => $relation) {
  76. if (empty($relation['className']) || $relationAlias !== $options['alias']) {
  77. continue;
  78. }
  79. $options['class'] = $relation['className'];
  80. break;
  81. }
  82. foreach ($Model->hasMany as $relationAlias => $relation) {
  83. if (empty($relation['className']) || $relationAlias !== $options['alias']) {
  84. continue;
  85. }
  86. $options['class'] = $relation['className'];
  87. break;
  88. }
  89. // guess it then
  90. if (empty($options['table']) && empty($options['class'])) {
  91. $options['class'] = $options['alias'];
  92. } elseif (!empty($options['table']) && empty($options['class'])) {
  93. $options['class'] = Inflector::classify($options['table']);
  94. }
  95. // the incoming model to be linked in query using class and alias
  96. $_Model = ClassRegistry::init(['class' => $options['class'], 'alias' => $options['alias']]);
  97. // the already in query model that links to $_Model
  98. $Reference = ClassRegistry::init($options['reference']);
  99. $db = $_Model->getDataSource();
  100. $associations = $_Model->getAssociated();
  101. if (isset($Reference->belongsTo[$_Model->alias])) {
  102. $type = 'hasOne';
  103. $association = $Reference->belongsTo[$_Model->alias];
  104. } elseif (isset($Reference->hasOne[$_Model->alias])) {
  105. $type = 'belongsTo';
  106. $association = $Reference->hasOne[$_Model->alias];
  107. } elseif (isset($Reference->hasMany[$_Model->alias])) {
  108. $type = 'belongsTo';
  109. $association = $Reference->hasMany[$_Model->alias];
  110. } elseif (isset($associations[$Reference->alias])) {
  111. $type = $associations[$Reference->alias];
  112. $association = $_Model->{$type}[$Reference->alias];
  113. } else {
  114. $_Model->bindModel(['belongsTo' => [$Reference->alias]]);
  115. $type = 'belongsTo';
  116. $association = $_Model->{$type}[$Reference->alias];
  117. $_Model->unbindModel(['belongsTo' => [$Reference->alias]]);
  118. }
  119. if (!isset($options['conditions'])) {
  120. $options['conditions'] = [];
  121. } elseif (!is_array($options['conditions'])) {
  122. // Support for string conditions
  123. $options['conditions'] = [$options['conditions']];
  124. }
  125. if (isset($options['conditions']['exactly'])) {
  126. if (is_array($options['conditions']['exactly'])) {
  127. $options['conditions'] = reset($options['conditions']['exactly']);
  128. } else {
  129. $options['conditions'] = [$options['conditions']['exactly']];
  130. }
  131. } else {
  132. if ($type === 'belongsTo') {
  133. $modelKey = $_Model->escapeField($association['foreignKey']);
  134. $modelKey = str_replace($_Model->alias, $options['alias'], $modelKey);
  135. $referenceKey = $Reference->escapeField($Reference->primaryKey);
  136. $options['conditions'][] = "{$referenceKey} = {$modelKey}";
  137. } elseif ($type === 'hasAndBelongsToMany') {
  138. // try to determine fields by HABTM model
  139. if (isset($association['with'])) {
  140. $Link = $_Model->{$association['with']};
  141. if (isset($Link->belongsTo[$_Model->alias])) {
  142. $modelLink = $Link->escapeField($Link->belongsTo[$_Model->alias]['foreignKey']);
  143. }
  144. if (isset($Link->belongsTo[$Reference->alias])) {
  145. $referenceLink = $Link->escapeField($Link->belongsTo[$Reference->alias]['foreignKey']);
  146. }
  147. } else {
  148. $Link = $_Model->{Inflector::classify($association['joinTable'])};
  149. }
  150. // try to determine fields by current model relation settings
  151. if (empty($modelLink) && !empty($_Model->{$type}[$Reference->alias]['foreignKey'])) {
  152. $modelLink = $Link->escapeField($_Model->{$type}[$Reference->alias]['foreignKey']);
  153. }
  154. if (empty($referenceLink) && !empty($_Model->{$type}[$Reference->alias]['associationForeignKey'])) {
  155. $referenceLink = $Link->escapeField($_Model->{$type}[$Reference->alias]['associationForeignKey']);
  156. }
  157. // fallback to defaults otherwise
  158. if (empty($modelLink)) {
  159. $modelLink = $Link->escapeField($association['foreignKey']);
  160. }
  161. if (empty($referenceLink)) {
  162. $referenceLink = $Link->escapeField($association['associationForeignKey']);
  163. }
  164. $referenceKey = $Reference->escapeField();
  165. $query['joins'][] = [
  166. 'alias' => $Link->alias,
  167. 'table' => $Link->table, //$Link->getDataSource()->fullTableName($Link),
  168. 'conditions' => "{$referenceLink} = {$referenceKey}",
  169. 'type' => 'LEFT',
  170. ];
  171. $modelKey = $_Model->escapeField();
  172. $modelKey = str_replace($_Model->alias, $options['alias'], $modelKey);
  173. $options['conditions'][] = "{$modelLink} = {$modelKey}";
  174. } else {
  175. $referenceKey = $Reference->escapeField($association['foreignKey']);
  176. $modelKey = $_Model->escapeField($_Model->primaryKey);
  177. $modelKey = str_replace($_Model->alias, $options['alias'], $modelKey);
  178. $options['conditions'][] = "{$modelKey} = {$referenceKey}";
  179. }
  180. }
  181. if (empty($options['table'])) {
  182. $options['table'] = $_Model->table;
  183. }
  184. // Decide whether we should mess with the fields or not
  185. // If this query is a COUNT query then we just leave it alone
  186. if (!isset($query['fields']) || is_array($query['fields']) || strpos($query['fields'], 'COUNT(*)') === false) {
  187. if (!empty($options['fields'])) {
  188. if ($options['fields'] === true && !empty($association['fields'])) {
  189. $options['fields'] = $db->fields($_Model, null, $association['fields']);
  190. } elseif ($options['fields'] === true) {
  191. $options['fields'] = $db->fields($_Model);
  192. } else {
  193. $options['fields'] = $db->fields($_Model, null, $options['fields']);
  194. }
  195. } elseif (!isset($options['fields']) || (isset($options['fields']) && !is_array($options['fields']))) {
  196. if (!empty($association['fields'])) {
  197. $options['fields'] = $db->fields($_Model, null, $association['fields']);
  198. } else {
  199. $options['fields'] = $db->fields($_Model);
  200. }
  201. }
  202. if (!empty($options['class']) && $options['class'] !== $alias) {
  203. //$options['fields'] = str_replace($options['class'], $alias, $options['fields']);
  204. }
  205. if (is_array($query['fields'])) {
  206. $query['fields'] = array_merge($query['fields'], $options['fields']);
  207. } else {
  208. // If user didn't specify any fields then select all fields by default (just as find would)
  209. $query['fields'] = array_merge($db->fields($Model), $options['fields']);
  210. }
  211. }
  212. $options[$this->_key] = array_merge($options[$this->_key], array_diff_key($options, $optionsKeys));
  213. $options = array_intersect_key($options, $optionsKeys);
  214. if (!empty($options[$this->_key])) {
  215. $iterators[] = $options[$this->_key] + ['defaults' => array_merge($defaults, ['reference' => $options['class']])];
  216. }
  217. $query['joins'][] = array_intersect_key($options, ['type' => true, 'alias' => true, 'table' => true, 'conditions' => true]);
  218. }
  219. $cont++;
  220. $notDone = isset($iterators[$cont]);
  221. } while ($notDone);
  222. }
  223. unset($query['link']);
  224. return $query;
  225. }
  226. }