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
<?php
// example method in a controller doing a filtered search
private function _getSubscribersFromFilter($filter_id) {
    $this->Filter->id = $filter_id;
    $this->Filter->read();
 
    $sql = $this->Filter->getFilterFor('Subscriber');
   
    $subscribers = $this->Subscriber->find('all',array(
        'conditions'=> $sql
    ));
    return $subscribers;
}
 
//  belongs_to and foreign_id are used together to link this model to several others
//  CREATE TABLE `filters` (
//    `id` int(11) unsigned NOT NULL auto_increment,
//    `name` varchar(255) default NULL,
//    `foreign_id` int(11) unsigned default NULL,
//    `belongs_to` varchar(255) default NULL,
//    `created` datetime default NULL,
//    `modified` datetime default NULL,
//    PRIMARY KEY  (`id`)
//  ) ENGINE=MyISAM DEFAULT CHARSET=utf8
class Filter extends AppModel {
    var $name = 'Filter';
 
    var $hasMany = array(
        'Rule' => array(
            'className'     => 'Rule',
            'order'         => 'Rule.order ASC',
            'dependent'     => true
        )
    );
   
 
    function countHitsFor($model_name) {
        $sql = $this->getFilterFor($model_name);
       
        App::import('Model',$model_name);
        // if clause to handle Models in plugins: Plugin.Modelname
        if ( strrpos($model_name, ".") ) {
            $model_class = substr($model_name, strrpos($model_name, ".")+1, strlen($model_name)-1);
        }
        $model = new $model_class;
       
        $count = $model->find('count',array(
            'conditions'=> $sql
        ));
        return $count;
    }
   
   
    function getFilterFor($model_name) {
        $conditions = '';
        if ( !empty($this->data['Rule']) ) {
            foreach ( $this->data['Rule'] as $rule ) {
                $this->Rule->create(array('Rule' => $rule));
                $sql = $this->Rule->asSQLFor($model_name);
                if ($sql) {
                    $conditions .= $sql .' AND ';
                }
            }          
        }
        $conditions .= '1=1'; // easier than truncating, but not pretty.
        return $conditions;
    }
}
 
 
//  CREATE TABLE `rules` (
//    `id` int(11) unsigned NOT NULL auto_increment,
//    `filter_id` int(11) unsigned NOT NULL default '0',
//    `field` varchar(255) collate utf8_swedish_ci default NULL,
//    `match` varchar(255) collate utf8_swedish_ci default NULL,
//    `value` varchar(255) collate utf8_swedish_ci default NULL,
//    `created` datetime default NULL,
//    `order` int(11) default NULL,
//    PRIMARY KEY  (`id`)
//  ) ENGINE=MyISAM DEFAULT CHARSET=utf8
class Rule extends AppModel {
    var $name = 'Rule';
 
    var $types = array(); // All take 2 sprint args: 1=field, 2=phrase
 
    function __construct() {
        parent::__construct();
 
        $this->types['Default']['true'] = '1=1';
        $this->types['Default']['false'] = '1=0';
       
        $this->types['Number']['equals'] = '%s = %s';
        $this->types['Number']['equals_not'] = '%s <> %s';
        $this->types['Number']['more_than'] = '%s > %s';
        $this->types['Number']['less_than'] = '%s < %s';
        $this->types['Number']['equals_any_of'] = '%s IN(%s)';
 
        $this->types['Text']['equals'] = '%s LIKE \'%s\'';
        $this->types['Text']['contains'] = '%s LIKE \'%%%s%%\'';
        $this->types['Text']['starts_with'] = '%s LIKE \'%s%%\'';
        $this->types['Text']['ends_with'] = '%s LIKE \'%%%s\'';
 
        $this->types['Email']['from_domain'] = '%s LIKE \'%%%s\'';
        $this->types['Email']['contains'] = '%s LIKE \'%%%s%%\'';
 
        $this->types['Phone']['contains'] = '%s LIKE \'%%%s%%\'';
 
        $this->types['Date']['within_next_n_days'] = 'CURDATE() <= DATE(%1$s) AND DATE(%1$s) <= ADDDATE(CURDATE(), INTERVAL %2$s DAY)';
        $this->types['Date']['within_last_n_days'] = 'CURDATE() >= (%1$s) AND DATE(%1$s) >= SUBDATE(CURDATE(), INTERVAL %2$s DAY)';
        $this->types['Date']['exactly'] = 'DATEDIFF(%s,\'%s\') = 0';
        $this->types['Date']['before'] = 'DATEDIFF(%s,\'%s\') < 0';
        $this->types['Date']['after'] = 'DATEDIFF(%s,\'%s\') > 0';
        $this->types['Date']['days_ago'] = 'FLOOR(DATEDIFF(CURDATE(), DATE(%s))) = \'%s\'';
        $this->types['Date']['weeks_ago'] = 'FLOOR(DATEDIFF(CURDATE(), DATE(%s))/7) = \'%s\'';
        $this->types['Date']['in_days'] = 'FLOOR(DATEDIFF(DATE(%s), CURDATE())) = \'%s\'';
        $this->types['Date']['in_weeks'] = 'FLOOR(DATEDIFF(DATE(%s), CURDATE())/7) = \'%s\'';
    }
 
    // creates SQL fragment to put in a where clause.
    // this has not been updated to create Cake 1.2 array conditions
    function asSQLFor($model_name) {
        if ( empty($this->data['Rule']['value']) ) {
            return $this->types['Default']['false'];
        }
       
        if ( strrpos($model_name, ".") ) {
            $model_class = substr($model_name, strrpos($model_name, ".")+1, strlen($model_name)-1);
        }
       
        // this can of-course be hard-coded, read from the schema or handled in some other way.
        // I store the fields in a table with their corresponding "type"
        App::import('Model','Field');
        $field = new Field();
        $res = $field->find('first',array(
            'conditions'=>array(
                'Field.field_name'=>$this->data['Rule']['field'],
                'Field.model'=>$model_class
            )
        ));
       
        if (isset($res['Field'])) {
            $fieldType = $res['Field']['type'];
            return sprintf($this->types[$fieldType][$this->data['Rule']['match']], $model_class.'.'.$this->data['Rule']['field'], $this->data['Rule']['value']);
        }
        return $this->types['Default']['false'];
    }
}