Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
// This file is part of Moodle - http://moodle.org/
3
//
4
// Moodle is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8
//
9
// Moodle is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13
//
14
// You should have received a copy of the GNU General Public License
15
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
16
 
17
declare(strict_types=1);
18
 
19
namespace core_reportbuilder\local\filters;
20
 
21
use core_reportbuilder\local\helpers\database;
22
 
23
/**
24
 * Number report filter
25
 *
1441 ariadna 26
 * This filter accepts a number value to perform filtering on (note that the value will be cast to float prior to comparison)
27
 *
1 efrain 28
 * @package     core_reportbuilder
29
 * @copyright   2021 David Matamoros <davidmc@moodle.com>
30
 * @license     http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
31
 */
32
class number extends base {
33
 
34
    /** @var int Any value */
35
    public const ANY_VALUE = 0;
36
 
37
    /** @var int Is not empty */
38
    public const IS_NOT_EMPTY = 1;
39
 
40
    /** @var int Is empty */
41
    public const IS_EMPTY = 2;
42
 
43
    /** @var int Less than */
44
    public const LESS_THAN = 3;
45
 
46
    /** @var int Greater than */
47
    public const GREATER_THAN = 4;
48
 
49
    /** @var int Equal to */
50
    public const EQUAL_TO = 5;
51
 
52
    /** @var int Equal or less than */
53
    public const EQUAL_OR_LESS_THAN = 6;
54
 
55
    /** @var int Equal or greater than */
56
    public const EQUAL_OR_GREATER_THAN = 7;
57
 
58
    /** @var int Range */
59
    public const RANGE = 8;
60
 
61
    /**
62
     * Returns an array of comparison operators
63
     *
64
     * @return array of comparison operators
65
     */
66
    private function get_operators(): array {
67
        $operators = [
68
            self::ANY_VALUE => get_string('filterisanyvalue', 'core_reportbuilder'),
69
            self::IS_NOT_EMPTY => get_string('filterisnotempty', 'core_reportbuilder'),
70
            self::IS_EMPTY => get_string('filterisempty', 'core_reportbuilder'),
71
            self::LESS_THAN => get_string('filterlessthan', 'core_reportbuilder'),
72
            self::GREATER_THAN => get_string('filtergreaterthan', 'core_reportbuilder'),
73
            self::EQUAL_TO => get_string('filterisequalto', 'core_reportbuilder'),
74
            self::EQUAL_OR_LESS_THAN => get_string('filterequalorlessthan', 'core_reportbuilder'),
75
            self::EQUAL_OR_GREATER_THAN => get_string('filterequalorgreaterthan', 'core_reportbuilder'),
76
            self::RANGE => get_string('filterrange', 'core_reportbuilder'),
77
        ];
78
 
79
        return $this->filter->restrict_limited_operators($operators);
80
    }
81
 
82
    /**
83
     * Adds controls specific to this filter in the form.
84
     *
85
     * @param \MoodleQuickForm $mform
86
     */
87
    public function setup_form(\MoodleQuickForm $mform): void {
88
        $objs = [];
89
 
90
        $objs['select'] = $mform->createElement('select', $this->name . '_operator',
91
            get_string('filterfieldoperator', 'core_reportbuilder', $this->get_header()), $this->get_operators());
92
        $mform->setType($this->name . '_operator', PARAM_INT);
93
 
94
        $objs['text'] = $mform->createElement('text', $this->name . '_value1',
95
            get_string('filterfieldvalue', 'core_reportbuilder', $this->get_header()), ['size' => 3]);
1441 ariadna 96
        $mform->setType($this->name . '_value1', PARAM_LOCALISEDFLOAT);
1 efrain 97
        $mform->setDefault($this->name . '_value1', 0);
98
        $mform->hideIf($this->name . '_value1', $this->name . '_operator', 'in',
99
            [self::ANY_VALUE,  self::IS_NOT_EMPTY,  self::IS_EMPTY]);
100
 
101
        $objs['text2'] = $mform->createElement('text', $this->name . '_value2',
1441 ariadna 102
            get_string('filterfieldto', 'core_reportbuilder', $this->get_header()), ['size' => 3]);
103
        $mform->setType($this->name . '_value2', PARAM_LOCALISEDFLOAT);
1 efrain 104
        $mform->setDefault($this->name . '_value2', 0);
105
        $mform->hideIf($this->name . '_value2', $this->name . '_operator', 'noteq', self::RANGE);
106
 
107
        $mform->addGroup($objs, $this->name . '_grp', $this->get_header(), '', false)
108
            ->setHiddenLabel(true);
109
    }
110
 
111
    /**
112
     * Return filter SQL
113
     *
114
     * @param array $values
115
     * @return array array of two elements - SQL query and named parameters
116
     */
117
    public function get_sql_filter(array $values): array {
1441 ariadna 118
        global $DB;
119
 
1 efrain 120
        $operator = (int) ($values["{$this->name}_operator"] ?? self::ANY_VALUE);
121
 
1441 ariadna 122
        $value1 = $value2 = null;
123
        if (array_key_exists("{$this->name}_value1", $values)) {
124
            $value1 = unformat_float($values["{$this->name}_value1"]);
125
        }
126
        if (array_key_exists("{$this->name}_value2", $values)) {
127
            $value2 = unformat_float($values["{$this->name}_value2"]);
128
        }
1 efrain 129
 
130
        // Validate filter form values.
131
        if (!$this->validate_filter_values($operator, $value1, $value2)) {
132
            // Filter configuration is invalid. Ignore the filter.
133
            return ['', []];
134
        }
135
 
136
        [$param, $param2] = database::generate_param_names(2);
137
 
138
        $fieldsql = $this->filter->get_field_sql();
139
        $params = $this->filter->get_field_params();
140
 
141
        switch ($operator) {
142
            case self::ANY_VALUE:
143
                return ['', []];
144
            case self::IS_NOT_EMPTY:
145
                $res = "COALESCE({$fieldsql}, 0) <> 0";
146
                break;
147
            case self::IS_EMPTY:
148
                $res = "COALESCE({$fieldsql}, 0) = 0";
149
                break;
150
            case self::LESS_THAN:
1441 ariadna 151
                $res = $DB->sql_cast_char2real("({$fieldsql})") . " < :{$param}";
1 efrain 152
                $params[$param] = $value1;
153
                break;
154
            case self::GREATER_THAN:
1441 ariadna 155
                $res = $DB->sql_cast_char2real("({$fieldsql})") . " > :{$param}";
1 efrain 156
                $params[$param] = $value1;
157
                break;
158
            case self::EQUAL_TO:
1441 ariadna 159
                $res = $DB->sql_cast_char2real("({$fieldsql})") . " = :{$param}";
1 efrain 160
                $params[$param] = $value1;
161
                break;
162
            case self::EQUAL_OR_LESS_THAN:
1441 ariadna 163
                $res = $DB->sql_cast_char2real("({$fieldsql})") . " <= :{$param}";
1 efrain 164
                $params[$param] = $value1;
165
                break;
166
            case self::EQUAL_OR_GREATER_THAN:
1441 ariadna 167
                $res = $DB->sql_cast_char2real("({$fieldsql})") . " >= :{$param}";
1 efrain 168
                $params[$param] = $value1;
169
                break;
170
            case self::RANGE:
1441 ariadna 171
                $res = $DB->sql_cast_char2real("({$fieldsql})") . " BETWEEN :{$param} AND :{$param2}";
1 efrain 172
                $params[$param] = $value1;
173
                $params[$param2] = $value2;
174
                break;
175
            default:
176
                // Filter configuration is invalid. Ignore the filter.
177
                return ['', []];
178
        }
179
        return [$res, $params];
180
    }
181
 
182
    /**
183
     * Validate filter form values
184
     *
185
     * @param int $operator
1441 ariadna 186
     * @param float|null $value1
187
     * @param float|null $value2
1 efrain 188
     * @return bool
189
     */
1441 ariadna 190
    private function validate_filter_values(int $operator, ?float $value1, ?float $value2): bool {
1 efrain 191
        // Check that for any of these operators value1 can not be null.
192
        $requirescomparisonvalue = [
193
            self::LESS_THAN,
194
            self::GREATER_THAN,
195
            self::EQUAL_TO,
196
            self::EQUAL_OR_LESS_THAN,
197
            self::EQUAL_OR_GREATER_THAN
198
        ];
199
        if (in_array($operator, $requirescomparisonvalue) && $value1 === null) {
200
            return false;
201
        }
202
 
203
        // When operator is between $value1 and $value2, can not be null.
204
        if (($operator === self::RANGE) && ($value1 === null || $value2 === null)) {
205
            return false;
206
        }
207
 
208
        return true;
209
    }
210
 
211
    /**
212
     * Return sample filter values
213
     *
214
     * @return array
215
     */
216
    public function get_sample_values(): array {
217
        return [
218
            "{$this->name}_operator" => self::GREATER_THAN,
219
            "{$this->name}_value1" => 1,
220
        ];
221
    }
222
}