public
Description: Behavior for CakePHP that allows use of named scopes with model's find() method.
Homepage: http://codetunes.com/2008/09/05/named-scope-in-cakephp/
Clone URL: git://github.com/netguru/namedscopebehavior.git
namedscopebehavior / named_scope.php
100644 66 lines (57 sloc) 2.315 kb
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
<?php
class NamedScopeBehavior extends ModelBehavior {
static $__settings = array();
 
function setup(&$model, $settings = array()) {
self::$__settings[$model->name] = $settings;
}
 
function beforeFind(&$model, $queryData) {
$scopes = array();
// passed as scopes
    if (!empty($queryData['scopes'])) {
      $scope = !is_array($queryData['scopes']) ? array($queryData['scopes']) : $queryData['scopes'];
      $scopes = am($scopes, $scope);
    }
    
    // passed as conditions['scopes']
    if (is_array($queryData['conditions']) && !empty($queryData['conditions']['scopes'])) {
      $scope = !is_array($queryData['conditions']['scopes']) ? array($queryData['conditions']['scopes']) : $queryData['conditions']['scopes'];
      unset($queryData['conditions']['scopes']);
      $scopes = am($scopes, $scope);
    }
 
    // if there are scopes defined, we need to get rid of possible condition set earlier by find() method if model->id was set
    if (!empty($scopes) && !empty($model->id) && !empty($queryData['conditions']["`{$model->alias}`.`{$model->primaryKey}`"]) && $queryData['conditions']["`{$model->alias}`.`{$model->primaryKey}`"] == $model->id) {
      unset($queryData['conditions']["`{$model->alias}`.`{$model->primaryKey}`"]);
    }
    
    foreach ($this->_conditions($scopes, $model->name) as $condition) {
      $queryData['conditions'][] = $condition;
    }
    
    return $queryData;
}
 
function _conditions($scopes = array(), $modelName = '') {
if (!is_array($scopes)) {
$scopes = array($scopes);
}
$_conditions = array();
foreach ($scopes as $scope) {
      if (strpos($scope, '.')) {
        list($scopeModel, $scope) = explode('.', $scope);
      } else {
        $scopeModel = $modelName;
      }
      if (!empty(self::$__settings[$scopeModel][$scope])) {
        $conditions = self::$__settings[$scopeModel][$scope];
        if (!is_array($conditions)) {
          $conditions = array($conditions);
        }
        foreach ($conditions as $condition) {
          $_conditions[] = $condition;
        }
      }
    }
    
    return $_conditions;
}
 
function scopeSql(&$model, $scope) {
$db =& ConnectionManager::getDataSource($model->useDbConfig);
    return $db->conditions($this->_conditions($scope, $model->name), false, $model);
}
}
?>