Bin will be removed on June 1, 2014 in favor of http://gist.github.com. Please save all your pastes before then. So long, and thanks for all the fish!×
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
<?php
/* SVN FILE: $Id$ */
/**
 * Behavior for binding and joining management.
 *
 * Behavior to simplify manipulating a model's bindings and conditional joins when doing a find operation
 *
 * PHP versions 4 and 5
 *
 * CakePHP(tm) :  Rapid Development Framework (http://www.cakephp.org)
 * Copyright 2005-2008, Cake Software Foundation, Inc. (http://www.cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 */
/**
 * Behavior to allow for dynamic and atomic manipulation of a Model's associations used for a find call. Most useful for limiting
 * the amount of associations and data returned.
 *
 * @package       cake
 * @subpackage    cake.cake.console.libs
 */
class ContainableBehavior extends ModelBehavior {
/**
 * Types of relationships available for models
 *
 * @var array
 * @access private
 */
    var $types = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany');
/**
 * Runtime configuration for this behavior
 *
 * @var array
 * @access private
 */
    var $runtime = array();
/**
 * Initiate behavior for the model using specified settings.
 *
 * Available settings:
 *
 * - recursive: (boolean, optional) set to true to allow containable to automatically
 *   determine the recursiveness level needed to fetch specified models,
 *   and set the model recursiveness to this level. setting it to false
 *   disables this feature. DEFAULTS TO: true
 * - notices: (boolean, optional) issues E_NOTICES for bindings referenced in a
 *   containable call that are not valid. DEFAULTS TO: true
 * - autoFields: (boolean, optional) auto-add needed fields to fetch requested
 *   bindings. DEFAULTS TO: true
 *
 * @param object $Model Model using the behavior
 * @param array $settings Settings to override for model.
 * @access public
 */
    function setup(&$Model, $settings = array()) {
        if (!isset($this->settings[$Model->alias])) {
            $this->settings[$Model->alias] = array('recursive' => true, 'notices' => true, 'autoFields' => true);
        }
        if (!is_array($settings)) {
            $settings = array();
        }
        $this->settings[$Model->alias] = array_merge($this->settings[$Model->alias], $settings);
    }
/**
 * Runs before a find() operation. Used to allow 'contain' setting
 * as part of the find call, like this:
 *
 * Model->find('all', array('contain' => array('Model1', 'Model2')));
 *
 * Model->find('all', array('contain' => array(
 *  'Model1' => array('Model11', 'Model12'),
 *  'Model2',
 *  'Model3' => array(
 *      'Model31' => 'Model311',
 *      'Model32',
 *      'Model33' => array('Model331', 'Model332')
 * )));
 *
 * @param object $Model Model using the behavior
 * @param array $query Query parameters as set by cake
 * @return array
 * @access public
 */
    function beforeFind(&$Model, $query) {
debug($query);
        $reset = (isset($query['reset']) ? $query['reset'] : true);
        $noContain = ((isset($this->runtime[$Model->alias]['contain']) && empty($this->runtime[$Model->alias]['contain'])) || (isset($query['contain']) && empty($query['contain'])));
        $contain = array();
        if (isset($this->runtime[$Model->alias]['contain'])) {
            $contain = $this->runtime[$Model->alias]['contain'];
            unset($this->runtime[$Model->alias]['contain']);
        }
        if (isset($query['contain'])) {
            $contain = array_merge($contain, (array)$query['contain']);
        }
        if ($noContain || !$contain || in_array($contain, array(null, false), true) || (isset($contain[0]) && $contain[0] === null)) {
            if ($noContain) {
                $query['recursive'] = -1;
            }
            // JAA: Added joins when a condition contains another model than the current!
         $joins = $this->joinsFromConditions( $Model, $query, array() );
        if ( $joins != array() )
        {
           $query['joins'] = $joins;
        }
            return $query;
        }
        if ((isset($contain[0]) && is_bool($contain[0])) || is_bool(end($contain))) {
            $reset = is_bool(end($contain))
                ? array_pop($contain)
                : array_shift($contain);
        }
        $conditions = array();
        $containments = $this->containments($Model, $contain);
        $map = $this->containmentsMap($containments);
 
      // JAA: Added joins when a condition contains another model than the mapped ones!
      $joins = $this->joinsFromConditions( $Model, $query, $map );
        if ( $joins != array() )
        {
           $query['joins'] = $joins;
        }
 
        $mandatory = array();
        foreach ($containments['models'] as $name => $model) {
            $instance =& $model['instance'];
            $needed = $this->fieldDependencies($instance, $map, false);
            if (!empty($needed)) {
                $mandatory = array_merge($mandatory, $needed);
            }
            if ($contain) {
                $backupBindings = array();
                foreach ($this->types as $relation) {
                    $backupBindings[$relation] = $instance->{$relation};
                }
                foreach ($this->types as $type) {
                    $unbind = array();
                    foreach ($instance->{$type} as $assoc => $options) {
                        if (!isset($model['keep'][$assoc])) {
                            $unbind[] = $assoc;
                        }
                    }
                    if (!empty($unbind)) {
                        if (!$reset && empty($instance->__backOriginalAssociation)) {
                            $instance->__backOriginalAssociation = $backupBindings;
                        } else if ($reset && empty($instance->__backContainableAssociation)) {
                            $instance->__backContainableAssociation = $backupBindings;
                        }
                        $instance->unbindModel(array($type => $unbind), $reset);
                    }
                    foreach ($instance->{$type} as $assoc => $options) {
                        if (isset($model['keep'][$assoc]) && !empty($model['keep'][$assoc])) {
                            if (isset($model['keep'][$assoc]['fields'])) {
                                $model['keep'][$assoc]['fields'] = $this->fieldDependencies($containments['models'][$assoc]['instance'], $map, $model['keep'][$assoc]['fields']);
                            }
                            if (!$reset && empty($instance->__backOriginalAssociation)) {
                                $instance->__backOriginalAssociation = $backupBindings;
                            } else if ($reset) {
                                $instance->__backAssociation[$type] = $instance->{$type};
                            }
                            $instance->{$type}[$assoc] = array_merge($instance->{$type}[$assoc], $model['keep'][$assoc]);
                        }
                        if (!$reset) {
                            $instance->__backInnerAssociation[] = $assoc;
                        }
                    }
                }
            }
        }
 
        if ($this->settings[$Model->alias]['recursive']) {
            $query['recursive'] = (isset($query['recursive'])) ? $query['recursive'] : $containments['depth'];
        }
 
        $autoFields = ($this->settings[$Model->alias]['autoFields']
                    && !in_array($Model->findQueryType, array('list', 'count'))
                    && !empty($query['fields']));
debug($query);
        if (!$autoFields) {
            return $query;
        }
 
        $query['fields'] = (array)$query['fields'];
 
        if (!empty($Model->belongsTo)) {
            foreach ($Model->belongsTo as $assoc => $data) {
                if (!empty($data['fields'])) {
                    foreach ((array) $data['fields'] as $field) {
                        $query['fields'][] = (strpos($field, '.') === false ? $assoc . '.' : '') . $field;
                    }
                }
            }
        }
        if (!empty($mandatory[$Model->alias])) {
            foreach ($mandatory[$Model->alias] as $field) {
                if ($field == '--primaryKey--') {
                    $field = $Model->primaryKey;
                } else if (preg_match('/^.+\.\-\-[^-]+\-\-$/', $field)) {
                    list($modelName, $field) = explode('.', $field);
                    $field = $modelName . '.' . (($field === '--primaryKey--') ? $Model->$modelName->primaryKey : $field);
                }
                $query['fields'][] = $field;
            }
        }
        $query['fields'] = array_unique($query['fields']);
        return $query;
    }
/**
 * Resets original associations on models that may have receive multiple,
 * subsequent unbindings.
 *
 * @param object $Model Model on which we are resetting
 * @param array $results Results of the find operation
 * @param bool $primary true if this is the primary model that issued the find operation, false otherwise
 * @access public
 */
    function afterFind(&$Model, $results, $primary) {
        if (!empty($Model->__backContainableAssociation)) {
            foreach ($Model->__backContainableAssociation as $relation => $bindings) {
                $Model->{$relation} = $bindings;
                unset($Model->__backContainableAssociation);
            }
        }
    }
/**
 * Unbinds all relations from a model except the specified ones. Calling this function without
 * parameters unbinds all related models.
 *
 * @param object $Model Model on which binding restriction is being applied
 * @return void
 * @access public
 */
    function contain(&$Model) {
        $args = func_get_args();
        $contain = call_user_func_array('am', array_slice($args, 1));
        $this->runtime[$Model->alias]['contain'] = $contain;
    }
/**
 * Permanently restore the original binding settings of given model, useful
 * for restoring the bindings after using 'reset' => false as part of the
 * contain call.
 *
 * @param object $Model Model on which to reset bindings
 * @return void
 * @access public
 */
    function resetBindings(&$Model) {
        if (!empty($Model->__backOriginalAssociation)) {
            $Model->__backAssociation = $Model->__backOriginalAssociation;
            unset($Model->__backOriginalAssociation);
        }
        $Model->resetAssociations();
        if (!empty($Model->__backInnerAssociation)) {
            $assocs = $Model->__backInnerAssociation;
            unset($Model->__backInnerAssociation);
            foreach ($assocs as $currentModel) {
                $this->resetBindings($Model->$currentModel);
            }
        }
    }
/**
 * Process containments for model.
 *
 * @param object $Model Model on which binding restriction is being applied
 * @param array $contain Parameters to use for restricting this model
 * @param array $containments Current set of containments
 * @param bool $throwErrors Wether unexisting bindings show throw errors
 * @return array Containments
 * @access public
 */
    function containments(&$Model, $contain, $containments = array(), $throwErrors = null) {
        $options = array('className', 'joinTable', 'with', 'foreignKey', 'associationForeignKey', 'conditions', 'fields', 'order', 'limit', 'offset', 'unique', 'finderQuery', 'deleteQuery', 'insertQuery');
        $keep = array();
        $depth = array();
        if ($throwErrors === null) {
            $throwErrors = (empty($this->settings[$Model->alias]) ? true : $this->settings[$Model->alias]['notices']);
        }
        foreach ((array)$contain as $name => $children) {
            if (is_numeric($name)) {
                $name = $children;
                $children = array();
            }
            if (preg_match('/(?<!\.)\(/', $name)) {
                $name = str_replace('(', '.(', $name);
            }
            if (strpos($name, '.') !== false) {
                $chain = explode('.', $name);
                $name = array_shift($chain);
                $children = array(join('.', $chain) => $children);
            }
 
            $children = (array)$children;
            foreach ($children as $key => $val) {
                if (is_string($key) && is_string($val) && !in_array($key, $options, true)) {
                    $children[$key] = (array) $val;
                }
            }
 
            $keys = array_keys($children);
            if ($keys && isset($children[0])) {
                $keys = array_merge(array_values($children), $keys);
            }
 
            foreach ($keys as $i => $key) {
                if (is_array($key)) {
                    continue;
                }
                $optionKey = in_array($key, $options, true);
                if (!$optionKey && is_string($key) && preg_match('/^[a-z(]/', $key) && (!isset($Model->{$key}) || !is_object($Model->{$key}))) {
                    $option = 'fields';
                    $val = array($key);
                    if ($key{0} == '(') {
                        $val = preg_split('/\s*,\s*/', substr(substr($key, 1), 0, -1));
                    } elseif (preg_match('/ASC|DESC$/', $key)) {
                        $option = 'order';
                        $val = $Model->{$name}->alias.'.'.$key;
                    } elseif (preg_match('/[ =!]/', $key)) {
                        $option = 'conditions';
                        $val = $Model->{$name}->alias.'.'.$key;
                    }
                    $children[$option] = is_array($val) ? $val : array($val);
                    $newChildren = null;
                    if (!empty($name) && !empty($children[$key])) {
                        $newChildren = $children[$key];
                    }
                    unset($children[$key], $children[$i]);
                    $key = $option;
                    $optionKey = true;
                    if (!empty($newChildren)) {
                        $children = Set::merge($children, $newChildren);
                    }
                }
                if ($optionKey && isset($children[$key])) {
                    if (!empty($keep[$name][$key]) && is_array($keep[$name][$key])) {
                        $keep[$name][$key] = array_merge((isset($keep[$name][$key]) ? $keep[$name][$key] : array()), (array) $children[$key]);
                    } else {
                        $keep[$name][$key] = $children[$key];
                    }
                    unset($children[$key]);
                }
            }
 
            if (!isset($Model->{$name}) || !is_object($Model->{$name})) {
                if ($throwErrors) {
                    trigger_error(sprintf(__('Model "%s" is not associated with model "%s"', true), $Model->alias, $name), E_USER_WARNING);
                }
                continue;
            }
 
            $containments = $this->containments($Model->{$name}, $children, $containments);
            $depths[] = $containments['depth'] + 1;
            if (!isset($keep[$name])) {
                $keep[$name] = array();
            }
        }
 
        if (!isset($containments['models'][$Model->alias])) {
            $containments['models'][$Model->alias] = array('keep' => array(),'instance' => &$Model);
        }
 
        $containments['models'][$Model->alias]['keep'] = array_merge($containments['models'][$Model->alias]['keep'], $keep);
        $containments['depth'] = empty($depths) ? 0 : max($depths);
        return $containments;
    }
/**
 * Calculate needed fields to fetch the required bindings for the given model.
 *
 * @param object $Model Model
 * @param array $map Map of relations for given model
 * @param mixed $fields If array, fields to initially load, if false use $Model as primary model
 * @return array Fields
 * @access public
 */
    function fieldDependencies(&$Model, $map, $fields = array()) {
        if ($fields === false) {
            foreach ($map as $parent => $children) {
                foreach ($children as $type => $bindings) {
                    foreach ($bindings as $dependency) {
                        if ($type == 'hasAndBelongsToMany') {
                            $fields[$parent][] = '--primaryKey--';
                        } else if ($type == 'belongsTo') {
                            $fields[$parent][] = $dependency . '.--primaryKey--';
                        }
                    }
                }
            }
            return $fields;
        }
        if (empty($map[$Model->alias])) {
            return $fields;
        }
        foreach ($map[$Model->alias] as $type => $bindings) {
            foreach ($bindings as $dependency) {
                $innerFields = array();
                switch ($type) {
                    case 'belongsTo':
                        $fields[] = $Model->{$type}[$dependency]['foreignKey'];
                        break;
                    case 'hasOne':
                    case 'hasMany':
                        $innerFields[] = $Model->$dependency->primaryKey;
                        $fields[] = $Model->primaryKey;
                        break;
                }
                if (!empty($innerFields) && !empty($Model->{$type}[$dependency]['fields'])) {
                    $Model->{$type}[$dependency]['fields'] = array_unique(array_merge($Model->{$type}[$dependency]['fields'], $innerFields));
                }
            }
        }
        return array_unique($fields);
    }
/**
 * Build the map of containments
 *
 * @param array $containments Containments
 * @return array Built containments
 * @access public
 */
    function containmentsMap($containments) {
        $map = array();
        foreach ($containments['models'] as $name => $model) {
            $instance =& $model['instance'];
            foreach ($this->types as $type) {
                foreach ($instance->{$type} as $assoc => $options) {
                    if (isset($model['keep'][$assoc])) {
                        $map[$name][$type] = isset($map[$name][$type]) ? array_merge($map[$name][$type], (array)$assoc) : (array)$assoc;
                    }
                }
            }
        }
        return $map;
    }
 
/**
 * Build the condition joins for belongsTo and hasAndBelongsToMany associations
 *
 * @param object $Model Model using the behavior
 * @param array $query Query parameters as set by cake
 * @param array $map Map of relations for given model
 * @return array Built joins
 * @access private
 */
   private function joinsFromConditions( &$Model, $query, $map = array() )
   {
      $joins = array();
        if ( isset($query['conditions']) ) {
           $conditionModels = $this->modelsFromConditions( $query['conditions'], $map );
           $joinNo = 0;
           foreach( $conditionModels as $no => $modelName )
           {
              foreach( $this->types as $type )
              {
               if ( isset($Model->{$type}[$modelName]) )
               {
                  $options = $Model->{$type}[$modelName];
                  switch( $type )
                  {
                     case 'belongsTo' :
                        $joins[$joinNo]['table'] = Inflector::tableize($options['className']);
                        $joins[$joinNo]['alias'] = $options['className'];
                        $joins[$joinNo]['type'] = 'INNER';
                        $joins[$joinNo]['foreignKey'] = false;
                        $joins[$joinNo]['conditions'] = array(
                           $joins[$joinNo]['alias'].'.id = '.
                           $Model->name.'.'.
                           $options['foreignKey']
                        );
                        $joinNo++;
                        break;
                     case 'hasAndBelongsToMany' :
                        $joins[$joinNo]['table'] = $options['joinTable'];
                        $joins[$joinNo]['alias'] = $options['with'];
                        $joins[$joinNo]['type'] = 'INNER';
                        $joins[$joinNo]['foreignKey'] = false;
                        $joins[$joinNo]['conditions'] = array(
                           $options['with'].'.'.
                           $options['foreignKey'].' = '.
                           $Model->alias.'.id'
                        );
                        $joinNo++;
                        $joins[$joinNo]['table'] = Inflector::tableize($options['className']);
                        $joins[$joinNo]['alias'] = $options['className'];
                        $joins[$joinNo]['type'] = 'INNER';
                        $joins[$joinNo]['foreignKey'] = false;
                        $joins[$joinNo]['conditions'] = array(
                           $joins[$joinNo]['alias'].'.id = '.
                           $options['with'].'.'.
                           $options['associationForeignKey']
                        );
                        $joinNo++;
                        break;
                  }
               }
            }
         }
        }
      return( $joins );
   }
 
/**
 * Identify the models in the condition which are not already mapped
 *
 * @param array $conditions The conditions from the query
 * @param array $map Map of relations for given model
 * @return array $models Identified additional models
 * @access private
 */
    function modelsFromConditions( $conditions, $map = array() )
    {
       $models = array();
        foreach ((array)$conditions as $name => $values) {
            if (strpos($name, '.') === false) {
               continue;
            }
        $chain = explode('.', $name);
        $modelName = array_shift($chain);
        if ( in_array($modelName, $map) == false && in_array($modelName, $models) == false ) {
           $models[] = $modelName;
        }
      }
       return( $models );
    }
}
?>