Merge "Adding interfaces for ORM row and table classes so these can be used for type...
[lhc/web/wiklou.git] / includes / db / ORMRow.php
1 <?php
2 /**
3 * Abstract base class for representing objects that are stored in some DB table.
4 * This is basically an ORM-like wrapper around rows in database tables that
5 * aims to be both simple and very flexible. It is centered around an associative
6 * array of fields and various methods to do common interaction with the database.
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
22 *
23 * @since 1.20
24 *
25 * @file ORMRow.php
26 * @ingroup ORM
27 *
28 * @licence GNU GPL v2 or later
29 * @author Jeroen De Dauw < jeroendedauw@gmail.com >
30 */
31
32 abstract class ORMRow implements IORMRow {
33
34 /**
35 * The fields of the object.
36 * field name (w/o prefix) => value
37 *
38 * @since 1.20
39 * @var array
40 */
41 protected $fields = array( 'id' => null );
42
43 /**
44 * @since 1.20
45 * @var ORMTable
46 */
47 protected $table;
48
49 /**
50 * If the object should update summaries of linked items when changed.
51 * For example, update the course_count field in universities when a course in courses is deleted.
52 * Settings this to false can prevent needless updating work in situations
53 * such as deleting a university, which will then delete all it's courses.
54 *
55 * @since 1.20
56 * @var bool
57 */
58 protected $updateSummaries = true;
59
60 /**
61 * Indicates if the object is in summary mode.
62 * This mode indicates that only summary fields got updated,
63 * which allows for optimizations.
64 *
65 * @since 1.20
66 * @var bool
67 */
68 protected $inSummaryMode = false;
69
70 /**
71 * Constructor.
72 *
73 * @since 1.20
74 *
75 * @param IORMTable $table
76 * @param array|null $fields
77 * @param boolean $loadDefaults
78 */
79 public function __construct( IORMTable $table, $fields = null, $loadDefaults = false ) {
80 $this->table = $table;
81
82 if ( !is_array( $fields ) ) {
83 $fields = array();
84 }
85
86 if ( $loadDefaults ) {
87 $fields = array_merge( $this->table->getDefaults(), $fields );
88 }
89
90 $this->setFields( $fields );
91 }
92
93 /**
94 * Load the specified fields from the database.
95 *
96 * @since 1.20
97 *
98 * @param array|null $fields
99 * @param boolean $override
100 * @param boolean $skipLoaded
101 *
102 * @return bool Success indicator
103 */
104 public function loadFields( $fields = null, $override = true, $skipLoaded = false ) {
105 if ( is_null( $this->getId() ) ) {
106 return false;
107 }
108
109 if ( is_null( $fields ) ) {
110 $fields = array_keys( $this->table->getFields() );
111 }
112
113 if ( $skipLoaded ) {
114 $fields = array_diff( $fields, array_keys( $this->fields ) );
115 }
116
117 if ( !empty( $fields ) ) {
118 $result = $this->table->rawSelectRow(
119 $this->table->getPrefixedFields( $fields ),
120 array( $this->table->getPrefixedField( 'id' ) => $this->getId() ),
121 array( 'LIMIT' => 1 )
122 );
123
124 if ( $result !== false ) {
125 $this->setFields( $this->table->getFieldsFromDBResult( $result ), $override );
126 return true;
127 }
128 return false;
129 }
130
131 return true;
132 }
133
134 /**
135 * Gets the value of a field.
136 *
137 * @since 1.20
138 *
139 * @param string $name
140 * @param mixed $default
141 *
142 * @throws MWException
143 * @return mixed
144 */
145 public function getField( $name, $default = null ) {
146 if ( $this->hasField( $name ) ) {
147 return $this->fields[$name];
148 } elseif ( !is_null( $default ) ) {
149 return $default;
150 } else {
151 throw new MWException( 'Attempted to get not-set field ' . $name );
152 }
153 }
154
155 /**
156 * Gets the value of a field but first loads it if not done so already.
157 *
158 * @since 1.20
159 *
160 * @param string$name
161 *
162 * @return mixed
163 */
164 public function loadAndGetField( $name ) {
165 if ( !$this->hasField( $name ) ) {
166 $this->loadFields( array( $name ) );
167 }
168
169 return $this->getField( $name );
170 }
171
172 /**
173 * Remove a field.
174 *
175 * @since 1.20
176 *
177 * @param string $name
178 */
179 public function removeField( $name ) {
180 unset( $this->fields[$name] );
181 }
182
183 /**
184 * Returns the objects database id.
185 *
186 * @since 1.20
187 *
188 * @return integer|null
189 */
190 public function getId() {
191 return $this->getField( 'id' );
192 }
193
194 /**
195 * Sets the objects database id.
196 *
197 * @since 1.20
198 *
199 * @param integer|null $id
200 */
201 public function setId( $id ) {
202 $this->setField( 'id', $id );
203 }
204
205 /**
206 * Gets if a certain field is set.
207 *
208 * @since 1.20
209 *
210 * @param string $name
211 *
212 * @return boolean
213 */
214 public function hasField( $name ) {
215 return array_key_exists( $name, $this->fields );
216 }
217
218 /**
219 * Gets if the id field is set.
220 *
221 * @since 1.20
222 *
223 * @return boolean
224 */
225 public function hasIdField() {
226 return $this->hasField( 'id' )
227 && !is_null( $this->getField( 'id' ) );
228 }
229
230 /**
231 * Sets multiple fields.
232 *
233 * @since 1.20
234 *
235 * @param array $fields The fields to set
236 * @param boolean $override Override already set fields with the provided values?
237 */
238 public function setFields( array $fields, $override = true ) {
239 foreach ( $fields as $name => $value ) {
240 if ( $override || !$this->hasField( $name ) ) {
241 $this->setField( $name, $value );
242 }
243 }
244 }
245
246 /**
247 * Gets the fields => values to write to the table.
248 *
249 * @since 1.20
250 *
251 * @return array
252 */
253 protected function getWriteValues() {
254 $values = array();
255
256 foreach ( $this->table->getFields() as $name => $type ) {
257 if ( array_key_exists( $name, $this->fields ) ) {
258 $value = $this->fields[$name];
259
260 switch ( $type ) {
261 case 'array':
262 $value = (array)$value;
263 case 'blob':
264 $value = serialize( $value );
265 }
266
267 $values[$this->table->getPrefixedField( $name )] = $value;
268 }
269 }
270
271 return $values;
272 }
273
274 /**
275 * Serializes the object to an associative array which
276 * can then easily be converted into JSON or similar.
277 *
278 * @since 1.20
279 *
280 * @param null|array $fields
281 * @param boolean $incNullId
282 *
283 * @return array
284 */
285 public function toArray( $fields = null, $incNullId = false ) {
286 $data = array();
287 $setFields = array();
288
289 if ( !is_array( $fields ) ) {
290 $setFields = $this->getSetFieldNames();
291 } else {
292 foreach ( $fields as $field ) {
293 if ( $this->hasField( $field ) ) {
294 $setFields[] = $field;
295 }
296 }
297 }
298
299 foreach ( $setFields as $field ) {
300 if ( $incNullId || $field != 'id' || $this->hasIdField() ) {
301 $data[$field] = $this->getField( $field );
302 }
303 }
304
305 return $data;
306 }
307
308 /**
309 * Load the default values, via getDefaults.
310 *
311 * @since 1.20
312 *
313 * @param boolean $override
314 */
315 public function loadDefaults( $override = true ) {
316 $this->setFields( $this->table->getDefaults(), $override );
317 }
318
319 /**
320 * Writes the answer to the database, either updating it
321 * when it already exists, or inserting it when it doesn't.
322 *
323 * @since 1.20
324 *
325 * @param string|null $functionName
326 *
327 * @return boolean Success indicator
328 */
329 public function save( $functionName = null ) {
330 if ( $this->hasIdField() ) {
331 return $this->saveExisting( $functionName );
332 } else {
333 return $this->insert( $functionName );
334 }
335 }
336
337 /**
338 * Updates the object in the database.
339 *
340 * @since 1.20
341 *
342 * @param string|null $functionName
343 *
344 * @return boolean Success indicator
345 */
346 protected function saveExisting( $functionName = null ) {
347 $dbw = wfGetDB( DB_MASTER );
348
349 $success = $dbw->update(
350 $this->table->getName(),
351 $this->getWriteValues(),
352 $this->table->getPrefixedValues( $this->getUpdateConditions() ),
353 is_null( $functionName ) ? __METHOD__ : $functionName
354 );
355
356 return $success;
357 }
358
359 /**
360 * Returns the WHERE considtions needed to identify this object so
361 * it can be updated.
362 *
363 * @since 1.20
364 *
365 * @return array
366 */
367 protected function getUpdateConditions() {
368 return array( 'id' => $this->getId() );
369 }
370
371 /**
372 * Inserts the object into the database.
373 *
374 * @since 1.20
375 *
376 * @param string|null $functionName
377 * @param array|null $options
378 *
379 * @return boolean Success indicator
380 */
381 protected function insert( $functionName = null, array $options = null ) {
382 $dbw = wfGetDB( DB_MASTER );
383
384 $result = $dbw->insert(
385 $this->table->getName(),
386 $this->getWriteValues(),
387 is_null( $functionName ) ? __METHOD__ : $functionName,
388 is_null( $options ) ? array( 'IGNORE' ) : $options
389 );
390
391 if ( $result ) {
392 $this->setField( 'id', $dbw->insertId() );
393 }
394
395 return $result;
396 }
397
398 /**
399 * Removes the object from the database.
400 *
401 * @since 1.20
402 *
403 * @return boolean Success indicator
404 */
405 public function remove() {
406 $this->beforeRemove();
407
408 $success = $this->table->delete( array( 'id' => $this->getId() ) );
409
410 if ( $success ) {
411 $this->onRemoved();
412 }
413
414 return $success;
415 }
416
417 /**
418 * Gets called before an object is removed from the database.
419 *
420 * @since 1.20
421 */
422 protected function beforeRemove() {
423 $this->loadFields( $this->getBeforeRemoveFields(), false, true );
424 }
425
426 /**
427 * Before removal of an object happens, @see beforeRemove gets called.
428 * This method loads the fields of which the names have been returned by this one (or all fields if null is returned).
429 * This allows for loading info needed after removal to get rid of linked data and the like.
430 *
431 * @since 1.20
432 *
433 * @return array|null
434 */
435 protected function getBeforeRemoveFields() {
436 return array();
437 }
438
439 /**
440 * Gets called after successfull removal.
441 * Can be overriden to get rid of linked data.
442 *
443 * @since 1.20
444 */
445 protected function onRemoved() {
446 $this->setField( 'id', null );
447 }
448
449 /**
450 * Return the names and values of the fields.
451 *
452 * @since 1.20
453 *
454 * @return array
455 */
456 public function getFields() {
457 return $this->fields;
458 }
459
460 /**
461 * Return the names of the fields.
462 *
463 * @since 1.20
464 *
465 * @return array
466 */
467 public function getSetFieldNames() {
468 return array_keys( $this->fields );
469 }
470
471 /**
472 * Sets the value of a field.
473 * Strings can be provided for other types,
474 * so this method can be called from unserialization handlers.
475 *
476 * @since 1.20
477 *
478 * @param string $name
479 * @param mixed $value
480 *
481 * @throws MWException
482 */
483 public function setField( $name, $value ) {
484 $fields = $this->table->getFields();
485
486 if ( array_key_exists( $name, $fields ) ) {
487 switch ( $fields[$name] ) {
488 case 'int':
489 $value = (int)$value;
490 break;
491 case 'float':
492 $value = (float)$value;
493 break;
494 case 'bool':
495 if ( is_string( $value ) ) {
496 $value = $value !== '0';
497 } elseif ( is_int( $value ) ) {
498 $value = $value !== 0;
499 }
500 break;
501 case 'array':
502 if ( is_string( $value ) ) {
503 $value = unserialize( $value );
504 }
505
506 if ( !is_array( $value ) ) {
507 $value = array();
508 }
509 break;
510 case 'blob':
511 if ( is_string( $value ) ) {
512 $value = unserialize( $value );
513 }
514 break;
515 case 'id':
516 if ( is_string( $value ) ) {
517 $value = (int)$value;
518 }
519 break;
520 }
521
522 $this->fields[$name] = $value;
523 } else {
524 throw new MWException( 'Attempted to set unknown field ' . $name );
525 }
526 }
527
528 /**
529 * Add an amount (can be negative) to the specified field (needs to be numeric).
530 * TODO: most off this stuff makes more sense in the table class
531 *
532 * @since 1.20
533 *
534 * @param string $field
535 * @param integer $amount
536 *
537 * @return boolean Success indicator
538 */
539 public function addToField( $field, $amount ) {
540 if ( $amount == 0 ) {
541 return true;
542 }
543
544 if ( !$this->hasIdField() ) {
545 return false;
546 }
547
548 $absoluteAmount = abs( $amount );
549 $isNegative = $amount < 0;
550
551 $dbw = wfGetDB( DB_MASTER );
552
553 $fullField = $this->table->getPrefixedField( $field );
554
555 $success = $dbw->update(
556 $this->table->getName(),
557 array( "$fullField=$fullField" . ( $isNegative ? '-' : '+' ) . $absoluteAmount ),
558 array( $this->table->getPrefixedField( 'id' ) => $this->getId() ),
559 __METHOD__
560 );
561
562 if ( $success && $this->hasField( $field ) ) {
563 $this->setField( $field, $this->getField( $field ) + $amount );
564 }
565
566 return $success;
567 }
568
569 /**
570 * Return the names of the fields.
571 *
572 * @since 1.20
573 *
574 * @return array
575 */
576 public function getFieldNames() {
577 return array_keys( $this->table->getFields() );
578 }
579
580 /**
581 * Computes and updates the values of the summary fields.
582 *
583 * @since 1.20
584 *
585 * @param array|string|null $summaryFields
586 */
587 public function loadSummaryFields( $summaryFields = null ) {
588
589 }
590
591 /**
592 * Sets the value for the @see $updateSummaries field.
593 *
594 * @since 1.20
595 *
596 * @param boolean $update
597 */
598 public function setUpdateSummaries( $update ) {
599 $this->updateSummaries = $update;
600 }
601
602 /**
603 * Sets the value for the @see $inSummaryMode field.
604 *
605 * @since 1.20
606 *
607 * @param boolean $summaryMode
608 */
609 public function setSummaryMode( $summaryMode ) {
610 $this->inSummaryMode = $summaryMode;
611 }
612
613 /**
614 * Return if any fields got changed.
615 *
616 * @since 1.20
617 *
618 * @param IORMRow $object
619 * @param boolean|array $excludeSummaryFields
620 * When set to true, summary field changes are ignored.
621 * Can also be an array of fields to ignore.
622 *
623 * @return boolean
624 */
625 protected function fieldsChanged( IORMRow $object, $excludeSummaryFields = false ) {
626 $exclusionFields = array();
627
628 if ( $excludeSummaryFields !== false ) {
629 $exclusionFields = is_array( $excludeSummaryFields ) ? $excludeSummaryFields : $this->table->getSummaryFields();
630 }
631
632 foreach ( $this->fields as $name => $value ) {
633 $excluded = $excludeSummaryFields && in_array( $name, $exclusionFields );
634
635 if ( !$excluded && $object->getField( $name ) !== $value ) {
636 return true;
637 }
638 }
639
640 return false;
641 }
642
643 /**
644 * Returns the table this IORMRow is a row in.
645 *
646 * @since 1.20
647 *
648 * @return IORMTable
649 */
650 public function getTable() {
651 return $this->table;
652 }
653
654 }