MDL-30995 completion: Fixed up PHPdocs for activity completion
[moodle.git] / lib / completion / data_object.php
CommitLineData
2be4d090 1<?php
836375ec
SH
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/>.
2be4d090 16
836375ec
SH
17/**
18 * Course completion critieria aggregation
19 *
20 * @package core_completion
21 * @category completion
22 * @copyright 2009 Catalyst IT Ltd
23 * @author Aaron Barnes <aaronb@catalyst.net.nz>
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 */
26
27defined('MOODLE_INTERNAL') || die();
2be4d090
MD
28
29/**
30 * A data abstraction object that holds methods and attributes
836375ec
SH
31 *
32 * @package core_completion
33 * @category completion
34 * @copyright 2009 Catalyst IT Ltd
35 * @author Aaron Barnes <aaronb@catalyst.net.nz>
36 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2be4d090
MD
37 */
38abstract class data_object {
836375ec 39
2be4d090
MD
40 /**
41 * Table that the class maps to in the database
836375ec 42 * @var string
2be4d090
MD
43 */
44 public $table;
45
46 /**
47 * Array of required table fields, must start with 'id'.
836375ec 48 * @var array
2be4d090
MD
49 */
50 public $required_fields = array('id');
51
52 /**
53 * Array of optional fields with default values - usually long text information that is not always needed.
54 * If you want to create an instance without optional fields use: new data_object($only_required_fields, false);
836375ec 55 * @var array
2be4d090
MD
56 */
57 public $optional_fields = array();
58
59 /**
836375ec 60 * The primary key
2be4d090
MD
61 * @var int $id
62 */
63 public $id;
64
65 /**
66 * Constructor. Optionally (and by default) attempts to fetch corresponding row from DB.
836375ec 67 *
2be4d090 68 * @param array $params an array with required parameters for this data object.
836375ec 69 * @param bool $fetch Whether to fetch corresponding row from DB or not,
2be4d090
MD
70 * optional fields might not be defined if false used
71 */
836375ec 72 public function __construct($params = NULL, $fetch = true) {
2be4d090
MD
73 if (!empty($params) and (is_array($params) or is_object($params))) {
74 if ($fetch) {
75 if ($data = $this->fetch($params)) {
76 self::set_properties($this, $data);
77 } else {
78 self::set_properties($this, $this->optional_fields);//apply defaults for optional fields
79 self::set_properties($this, $params);
80 }
81
82 } else {
83 self::set_properties($this, $params);
84 }
85
86 } else {
87 self::set_properties($this, $this->optional_fields);//apply defaults for optional fields
88 }
89 }
90
91 /**
92 * Makes sure all the optional fields are loaded.
836375ec 93 *
2be4d090
MD
94 * If id present (==instance exists in db) fetches data from db.
95 * Defaults are used for new instances.
96 */
97 public function load_optional_fields() {
98 global $DB;
99 foreach ($this->optional_fields as $field=>$default) {
4cc977a6 100 if (property_exists($this, $field)) {
2be4d090
MD
101 continue;
102 }
103 if (empty($this->id)) {
104 $this->$field = $default;
105 } else {
106 $this->$field = $DB->get_field($this->table, $field, array('id', $this->id));
107 }
108 }
109 }
110
111 /**
112 * Finds and returns a data_object instance based on params.
2be4d090 113 *
836375ec
SH
114 * This function MUST be overridden by all deriving classes.
115 *
116 * @param array $params associative arrays varname => value
117 * @throws coding_exception This function MUST be overridden
118 * @return data_object instance of data_object or false if none found.
2be4d090 119 */
7c109ea3
PS
120 public static function fetch($params) {
121 throw new coding_exception('fetch() method needs to be overridden in each subclass of data_object');
122 }
2be4d090
MD
123
124 /**
125 * Finds and returns all data_object instances based on params.
126 *
836375ec
SH
127 * This function MUST be overridden by all deriving classes.
128 *
129 * @param array $params associative arrays varname => value
130 * @throws coding_exception This function MUST be overridden
7c109ea3 131 * @return array array of data_object instances or false if none found.
2be4d090 132 */
7c109ea3
PS
133 public static function fetch_all($params) {
134 throw new coding_exception('fetch_all() method needs to be overridden in each subclass of data_object');
135 }
2be4d090
MD
136
137 /**
138 * Factory method - uses the parameters to retrieve matching instance from the DB.
836375ec
SH
139 *
140 * @final
141 * @param string $table The table name to fetch from
142 * @param string $classname The class that you want the result instantiated as
143 * @param array $params Any params required to select the desired row
144 * @return object Instance of $classname or false.
2be4d090
MD
145 */
146 protected static function fetch_helper($table, $classname, $params) {
147 if ($instances = self::fetch_all_helper($table, $classname, $params)) {
148 if (count($instances) > 1) {
149 // we should not tolerate any errors here - problems might appear later
150 print_error('morethanonerecordinfetch','debug');
151 }
152 return reset($instances);
153 } else {
154 return false;
155 }
156 }
157
158 /**
159 * Factory method - uses the parameters to retrieve all matching instances from the DB.
836375ec
SH
160 *
161 * @final
162 * @param string $table The table name to fetch from
163 * @param string $classname The class that you want the result instantiated as
164 * @param array $params Any params required to select the desired row
2be4d090
MD
165 * @return mixed array of object instances or false if not found
166 */
167 public static function fetch_all_helper($table, $classname, $params) {
168 $instance = new $classname();
169
170 $classvars = (array)$instance;
171 $params = (array)$params;
172
173 $wheresql = array();
174
175 foreach ($params as $var=>$value) {
176 if (!in_array($var, $instance->required_fields) and !array_key_exists($var, $instance->optional_fields)) {
177 continue;
178 }
179 if (is_null($value)) {
180 $wheresql[] = " $var IS NULL ";
181 } else {
182 $wheresql[] = " $var = ? ";
183 $params[] = $value;
184 }
185 }
186
187 if (empty($wheresql)) {
188 $wheresql = '';
189 } else {
190 $wheresql = implode("AND", $wheresql);
191 }
192
193 global $DB;
194 if ($datas = $DB->get_records_select($table, $wheresql, $params)) {
6142a4a5 195
2be4d090
MD
196 $result = array();
197 foreach($datas as $data) {
198 $instance = new $classname();
199 self::set_properties($instance, $data);
200 $result[$instance->id] = $instance;
201 }
202 return $result;
203
204 } else {
6142a4a5 205
2be4d090
MD
206 return false;
207 }
208 }
209
210 /**
211 * Updates this object in the Database, based on its object variables. ID must be set.
836375ec 212 *
2be4d090
MD
213 * @return boolean success
214 */
215 public function update() {
216 global $DB;
217
218 if (empty($this->id)) {
219 debugging('Can not update data object, no id!');
220 return false;
221 }
222
223 $data = $this->get_record_data();
224
225 $DB->update_record($this->table, $data);
226
227 $this->notify_changed(false);
228 return true;
229 }
230
231 /**
232 * Deletes this object from the database.
836375ec 233 *
2be4d090
MD
234 * @return boolean success
235 */
236 public function delete() {
237 global $DB;
238
239 if (empty($this->id)) {
240 debugging('Can not delete data object, no id!');
241 return false;
242 }
243
244 $data = $this->get_record_data();
245
246 if ($DB->delete_records($this->table, array('id'=>$this->id))) {
247 $this->notify_changed(true);
248 return true;
249
250 } else {
251 return false;
252 }
253 }
254
255 /**
256 * Returns object with fields and values that are defined in database
836375ec
SH
257 *
258 * @return stdClass
2be4d090
MD
259 */
260 public function get_record_data() {
365a5941 261 $data = new stdClass();
2be4d090
MD
262
263 foreach ($this as $var=>$value) {
264 if (in_array($var, $this->required_fields) or array_key_exists($var, $this->optional_fields)) {
265 if (is_object($value) or is_array($value)) {
266 debugging("Incorrect property '$var' found when inserting data object");
267 } else {
268 $data->$var = $value;
269 }
270 }
271 }
272 return $data;
273 }
274
275 /**
276 * Records this object in the Database, sets its id to the returned value, and returns that value.
277 * If successful this function also fetches the new object data from database and stores it
278 * in object properties.
836375ec 279 *
2be4d090
MD
280 * @return int PK ID if successful, false otherwise
281 */
282 public function insert() {
283 global $DB;
284
285 if (!empty($this->id)) {
286 debugging("Data object already exists!");
287 return false;
288 }
289
290 $data = $this->get_record_data();
291
292 $this->id = $DB->insert_record($this->table, $data);
293
294 // set all object properties from real db data
295 $this->update_from_db();
296
297 $this->notify_changed(false);
298 return $this->id;
299 }
300
301 /**
302 * Using this object's id field, fetches the matching record in the DB, and looks at
303 * each variable in turn. If the DB has different data, the db's data is used to update
304 * the object. This is different from the update() function, which acts on the DB record
305 * based on the object.
836375ec
SH
306 *
307 * @return bool True for success, false otherwise.
2be4d090
MD
308 */
309 public function update_from_db() {
310 if (empty($this->id)) {
311 debugging("The object could not be used in its state to retrieve a matching record from the DB, because its id field is not set.");
312 return false;
313 }
314 global $DB;
315 if (!$params = $DB->get_record($this->table, array('id' => $this->id))) {
316 debugging("Object with this id:{$this->id} does not exist in table:{$this->table}, can not update from db!");
317 return false;
318 }
319
320 self::set_properties($this, $params);
321
322 return true;
323 }
324
325 /**
326 * Given an associated array or object, cycles through each key/variable
327 * and assigns the value to the corresponding variable in this object.
836375ec
SH
328 *
329 * @final
330 * @param data_object $instance
331 * @param array $params
2be4d090
MD
332 */
333 public static function set_properties(&$instance, $params) {
334 $params = (array) $params;
335 foreach ($params as $var => $value) {
336 if (in_array($var, $instance->required_fields) or array_key_exists($var, $instance->optional_fields)) {
337 $instance->$var = $value;
338 }
339 }
340 }
341
342 /**
6142a4a5
PS
343 * Called immediately after the object data has been inserted, updated, or
344 * deleted in the database. Default does nothing, can be overridden to
2be4d090
MD
345 * hook in special behaviour.
346 *
836375ec 347 * @param bool $deleted Set this to true if it has been deleted.
2be4d090 348 */
836375ec
SH
349 function notify_changed($deleted) {}
350}