1: <?php
2:
3: namespace Charcoal\Source\Database;
4:
5:
6: use \Charcoal\Source\Filter;
7:
8: 9: 10:
11: class DatabaseFilter extends Filter
12: {
13: 14: 15: 16: 17:
18: public function sql()
19: {
20: $raw = $this->string();
21: if ($raw) {
22: return $raw;
23: }
24:
25: $fields = $this->sqlFields();
26: if (empty($fields)) {
27: return '';
28: }
29:
30: $filter = '';
31:
32: foreach ($fields as $field) {
33: $val = $this->val();
34:
35:
36: $operator = $this->operator();
37:
38:
39: $function = $this->func();
40:
41:
42: $tableName = $this->tableName();
43:
44: if ($function) {
45: $target = sprintf('%1$s(%2$s.%3$s)', $function, $tableName, $field);
46: } else {
47: $target = sprintf('%1$s.%2$s', $tableName, $field);
48: }
49:
50: switch ($operator) {
51: case 'FIND_IN_SET':
52: if (is_array($val)) {
53: $val = implode(',', $val);
54: }
55:
56: $filter .= sprintf('%1$s(\'%2$s\', %3$s)', $operator, $val, $target);
57: break;
58:
59: case 'IS NULL':
60: case 'IS NOT NULL':
61: $filter .= sprintf('(%1$s %2$s)', $target, $operator);
62: break;
63:
64: case 'IN':
65: case 'NOT IN':
66: if (is_array($val)) {
67: $val = implode('\',\'', $val);
68: }
69:
70: $filter .= sprintf('(%1$s %2$s (\'%3$s\'))', $target, $operator, $val);
71: break;
72:
73: default:
74: $filter .= sprintf('(%1$s %2$s \'%3$s\')', $target, $operator, $val);
75: break;
76: }
77: }
78:
79: return $filter;
80: }
81:
82: 83: 84:
85: private function sqlFields()
86: {
87: $property = $this->property();
88: if ($property) {
89:
90: return [$property];
91: }
92:
93: return [];
94: }
95: }
96: