follow up to r111264; split up class into one representing a table and one representi...
[lhc/web/wiklou.git] / includes / DBDataObject.php
1 <?php
2
3 /**
4 * Abstract base class for representing objects that are stored in some DB table.
5 * This is basically an ORM-like wrapper around rows in database tables that
6 * aims to be both simple and very flexible. It is centered around an associative
7 * array of fields and various methods to do common interaction with the database.
8 *
9 * These methods must be implemented in deriving classes:
10 * * getDBTable
11 * * getFieldPrefix
12 * * getFieldTypes
13 *
14 * These methods are likely candidates for overriding:
15 * * getDefaults
16 * * remove
17 * * insert
18 * * saveExisting
19 * * loadSummaryFields
20 * * getSummaryFields
21 *
22 * Main instance methods:
23 * * getField(s)
24 * * setField(s)
25 * * save
26 * * remove
27 *
28 * Main static methods:
29 * * select
30 * * update
31 * * delete
32 * * count
33 * * has
34 * * selectRow
35 * * selectFields
36 * * selectFieldsRow
37 *
38 * @since 1.20
39 *
40 * @file DBDataObject.php
41 *
42 * @licence GNU GPL v2 or later
43 * @author Jeroen De Dauw < jeroendedauw@gmail.com >
44 */
45 abstract class DBDataObject {
46
47 /**
48 * The fields of the object.
49 * field name (w/o prefix) => value
50 *
51 * @since 1.20
52 * @var array
53 */
54 protected $fields = array( 'id' => null );
55
56 /**
57 * @since 1.20
58 * @var DBTable
59 */
60 protected $table;
61
62 /**
63 * If the object should update summaries of linked items when changed.
64 * For example, update the course_count field in universities when a course in courses is deleted.
65 * Settings this to false can prevent needless updating work in situations
66 * such as deleting a university, which will then delete all it's courses.
67 *
68 * @since 1.20
69 * @var bool
70 */
71 protected $updateSummaries = true;
72
73 /**
74 * Indicates if the object is in summary mode.
75 * This mode indicates that only summary fields got updated,
76 * which allows for optimizations.
77 *
78 * @since 1.20
79 * @var bool
80 */
81 protected $inSummaryMode = false;
82
83 /**
84 * The database connection to use for read operations.
85 * Can be changed via @see setReadDb.
86 *
87 * @since 1.20
88 * @var integer DB_ enum
89 */
90 protected $readDb = DB_SLAVE;
91
92 /**
93 * Constructor.
94 *
95 * @since 1.20
96 *
97 * @param array|null $fields
98 * @param boolean $loadDefaults
99 */
100 public function __construct( DBTable $table, $fields = null, $loadDefaults = false ) {
101 $this->table = $table;
102
103 if ( !is_array( $fields ) ) {
104 $fields = array();
105 }
106
107 if ( $loadDefaults ) {
108 $fields = array_merge( $this->table->getDefaults(), $fields );
109 }
110
111 $this->setFields( $fields );
112 }
113
114 /**
115 * Load the specified fields from the database.
116 *
117 * @since 1.20
118 *
119 * @param array|null $fields
120 * @param boolean $override
121 * @param boolean $skipLoaded
122 *
123 * @return bool Success indicator
124 */
125 public function loadFields( $fields = null, $override = true, $skipLoaded = false ) {
126 if ( is_null( $this->getId() ) ) {
127 return false;
128 }
129
130 if ( is_null( $fields ) ) {
131 $fields = array_keys( $this->getFieldTypes() );
132 }
133
134 if ( $skipLoaded ) {
135 $fields = array_diff( $fields, array_keys( $this->fields ) );
136 }
137
138 if ( count( $fields ) > 0 ) {
139 $result = $this->rawSelectRow(
140 $this->getPrefixedFields( $fields ),
141 array( $this->getPrefixedField( 'id' ) => $this->getId() ),
142 array( 'LIMIT' => 1 )
143 );
144
145 if ( $result !== false ) {
146 $this->setFields( $this->getFieldsFromDBResult( $result ), $override );
147 return true;
148 }
149
150 return false;
151 }
152
153 return true;
154 }
155
156 /**
157 * Gets the value of a field.
158 *
159 * @since 1.20
160 *
161 * @param string $name
162 * @param mixed $default
163 *
164 * @throws MWException
165 * @return mixed
166 */
167 public function getField( $name, $default = null ) {
168 if ( $this->hasField( $name ) ) {
169 return $this->fields[$name];
170 } elseif ( !is_null( $default ) ) {
171 return $default;
172 } else {
173 throw new MWException( 'Attempted to get not-set field ' . $name );
174 }
175 }
176
177 /**
178 * Gets the value of a field but first loads it if not done so already.
179 *
180 * @since 1.20
181 *
182 * @param string$name
183 *
184 * @return mixed
185 */
186 public function loadAndGetField( $name ) {
187 if ( !$this->hasField( $name ) ) {
188 $this->loadFields( array( $name ) );
189 }
190
191 return $this->getField( $name );
192 }
193
194 /**
195 * Remove a field.
196 *
197 * @since 1.20
198 *
199 * @param string $name
200 */
201 public function removeField( $name ) {
202 unset( $this->fields[$name] );
203 }
204
205 /**
206 * Returns the objects database id.
207 *
208 * @since 1.20
209 *
210 * @return integer|null
211 */
212 public function getId() {
213 return $this->getField( 'id' );
214 }
215
216 /**
217 * Sets the objects database id.
218 *
219 * @since 1.20
220 *
221 * @param integer|null $id
222 */
223 public function setId( $id ) {
224 return $this->setField( 'id', $id );
225 }
226
227 /**
228 * Gets if a certain field is set.
229 *
230 * @since 1.20
231 *
232 * @param string $name
233 *
234 * @return boolean
235 */
236 public function hasField( $name ) {
237 return array_key_exists( $name, $this->fields );
238 }
239
240 /**
241 * Gets if the id field is set.
242 *
243 * @since 1.20
244 *
245 * @return boolean
246 */
247 public function hasIdField() {
248 return $this->hasField( 'id' )
249 && !is_null( $this->getField( 'id' ) );
250 }
251
252 /**
253 * Sets multiple fields.
254 *
255 * @since 1.20
256 *
257 * @param array $fields The fields to set
258 * @param boolean $override Override already set fields with the provided values?
259 */
260 public function setFields( array $fields, $override = true ) {
261 foreach ( $fields as $name => $value ) {
262 if ( $override || !$this->hasField( $name ) ) {
263 $this->setField( $name, $value );
264 }
265 }
266 }
267
268 /**
269 * Gets the fields => values to write to the table.
270 *
271 * @since 1.20
272 *
273 * @return array
274 */
275 protected function getWriteValues() {
276 $values = array();
277
278 foreach ( $this->getFieldTypes() as $name => $type ) {
279 if ( array_key_exists( $name, $this->fields ) ) {
280 $value = $this->fields[$name];
281
282 switch ( $type ) {
283 case 'array':
284 $value = (array)$value;
285 case 'blob':
286 $value = serialize( $value );
287 }
288
289 $values[$this->getFieldPrefix() . $name] = $value;
290 }
291 }
292
293 return $values;
294 }
295
296 /**
297 * Serializes the object to an associative array which
298 * can then easily be converted into JSON or similar.
299 *
300 * @since 1.20
301 *
302 * @param null|array $fields
303 * @param boolean $incNullId
304 *
305 * @return array
306 */
307 public function toArray( $fields = null, $incNullId = false ) {
308 $data = array();
309 $setFields = array();
310
311 if ( !is_array( $fields ) ) {
312 $setFields = $this->getSetFieldNames();
313 } else {
314 foreach ( $fields as $field ) {
315 if ( $this->hasField( $field ) ) {
316 $setFields[] = $field;
317 }
318 }
319 }
320
321 foreach ( $setFields as $field ) {
322 if ( $incNullId || $field != 'id' || $this->hasIdField() ) {
323 $data[$field] = $this->getField( $field );
324 }
325 }
326
327 return $data;
328 }
329
330 /**
331 * Load the default values, via getDefaults.
332 *
333 * @since 1.20
334 *
335 * @param boolean $override
336 */
337 public function loadDefaults( $override = true ) {
338 $this->setFields( $this->getDefaults(), $override );
339 }
340
341 /**
342 * Writes the answer to the database, either updating it
343 * when it already exists, or inserting it when it doesn't.
344 *
345 * @since 1.20
346 *
347 * @return boolean Success indicator
348 */
349 public function save() {
350 if ( $this->hasIdField() ) {
351 return $this->saveExisting();
352 } else {
353 return $this->insert();
354 }
355 }
356
357 /**
358 * Updates the object in the database.
359 *
360 * @since 1.20
361 *
362 * @return boolean Success indicator
363 */
364 protected function saveExisting() {
365 $dbw = wfGetDB( DB_MASTER );
366
367 $success = $dbw->update(
368 $this->getDBTable(),
369 $this->getWriteValues(),
370 array( $this->getFieldPrefix() . 'id' => $this->getId() ),
371 __METHOD__
372 );
373
374 return $success;
375 }
376
377 /**
378 * Inserts the object into the database.
379 *
380 * @since 1.20
381 *
382 * @return boolean Success indicator
383 */
384 protected function insert() {
385 $dbw = wfGetDB( DB_MASTER );
386
387 $result = $dbw->insert(
388 $this->getDBTable(),
389 $this->getWriteValues(),
390 __METHOD__,
391 array( 'IGNORE' )
392 );
393
394 if ( $result ) {
395 $this->setField( 'id', $dbw->insertId() );
396 }
397
398 return $result;
399 }
400
401 /**
402 * Removes the object from the database.
403 *
404 * @since 1.20
405 *
406 * @return boolean Success indicator
407 */
408 public function remove() {
409 $this->beforeRemove();
410
411 $success = static::delete( array( 'id' => $this->getId() ) );
412
413 if ( $success ) {
414 $this->onRemoved();
415 }
416
417 return $success;
418 }
419
420 /**
421 * Gets called before an object is removed from the database.
422 *
423 * @since 1.20
424 */
425 protected function beforeRemove() {
426 $this->loadFields( $this->getBeforeRemoveFields(), false, true );
427 }
428
429 /**
430 * Before removal of an object happens, @see beforeRemove gets called.
431 * This method loads the fields of which the names have been returned by this one (or all fields if null is returned).
432 * This allows for loading info needed after removal to get rid of linked data and the like.
433 *
434 * @since 1.20
435 *
436 * @return array|null
437 */
438 protected function getBeforeRemoveFields() {
439 return array();
440 }
441
442 /**
443 * Gets called after successfull removal.
444 * Can be overriden to get rid of linked data.
445 *
446 * @since 1.20
447 */
448 protected function onRemoved() {
449 $this->setField( 'id', null );
450 }
451
452 /**
453 * Return the names and values of the fields.
454 *
455 * @since 1.20
456 *
457 * @return array
458 */
459 public function getFields() {
460 return $this->fields;
461 }
462
463 /**
464 * Return the names of the fields.
465 *
466 * @since 1.20
467 *
468 * @return array
469 */
470 public function getSetFieldNames() {
471 return array_keys( $this->fields );
472 }
473
474 /**
475 * Sets the value of a field.
476 * Strings can be provided for other types,
477 * so this method can be called from unserialization handlers.
478 *
479 * @since 1.20
480 *
481 * @param string $name
482 * @param mixed $value
483 *
484 * @throws MWException
485 */
486 public function setField( $name, $value ) {
487 $fields = $this->table->getFieldTypes();
488
489 if ( array_key_exists( $name, $fields ) ) {
490 switch ( $fields[$name] ) {
491 case 'int':
492 $value = (int)$value;
493 break;
494 case 'float':
495 $value = (float)$value;
496 break;
497 case 'bool':
498 if ( is_string( $value ) ) {
499 $value = $value !== '0';
500 } elseif ( is_int( $value ) ) {
501 $value = $value !== 0;
502 }
503 break;
504 case 'array':
505 if ( is_string( $value ) ) {
506 $value = unserialize( $value );
507 }
508
509 if ( !is_array( $value ) ) {
510 $value = array();
511 }
512 break;
513 case 'blob':
514 if ( is_string( $value ) ) {
515 $value = unserialize( $value );
516 }
517 break;
518 case 'id':
519 if ( is_string( $value ) ) {
520 $value = (int)$value;
521 }
522 break;
523 }
524
525 $this->fields[$name] = $value;
526 } else {
527 throw new MWException( 'Attempted to set unknown field ' . $name );
528 }
529 }
530
531 /**
532 * Get a new instance of the class from an array.
533 *
534 * @since 1.20
535 *
536 * @param array $data
537 * @param boolean $loadDefaults
538 *
539 * @return DBDataObject
540 */
541 public function newFromArray( array $data, $loadDefaults = false ) {
542 return new self( $data, $loadDefaults );
543 }
544
545 /**
546 * Get the database type used for read operations.
547 *
548 * @since 1.20
549 *
550 * @return integer DB_ enum
551 */
552 public function getReadDb() {
553 return $this->readDb;
554 }
555
556 /**
557 * Set the database type to use for read operations.
558 *
559 * @param integer $db
560 *
561 * @since 1.20
562 */
563 public function setReadDb( $db ) {
564 $this->readDb = $db;
565 }
566
567 /**
568 * Gets if the object can take a certain field.
569 *
570 * @since 1.20
571 *
572 * @param string $name
573 *
574 * @return boolean
575 */
576 public function canHaveField( $name ) {
577 return array_key_exists( $name, $this->table->getFieldTypes() );
578 }
579
580 /**
581 * Add an amount (can be negative) to the specified field (needs to be numeric).
582 *
583 * @since 1.20
584 *
585 * @param string $field
586 * @param integer $amount
587 *
588 * @return boolean Success indicator
589 */
590 public function addToField( $field, $amount ) {
591 if ( $amount == 0 ) {
592 return true;
593 }
594
595 if ( !$this->hasIdField() ) {
596 return false;
597 }
598
599 $absoluteAmount = abs( $amount );
600 $isNegative = $amount < 0;
601
602 $dbw = wfGetDB( DB_MASTER );
603
604 $fullField = $this->getPrefixedField( $field );
605
606 $success = $dbw->update(
607 $this->getDBTable(),
608 array( "$fullField=$fullField" . ( $isNegative ? '-' : '+' ) . $absoluteAmount ),
609 array( $this->getPrefixedField( 'id' ) => $this->getId() ),
610 __METHOD__
611 );
612
613 if ( $success && static::hasField( $field ) ) {
614 static::setField( $field, static::getField( $field ) + $amount );
615 }
616
617 return $success;
618 }
619
620 /**
621 * Selects the the specified fields of the records matching the provided
622 * conditions. Field names do NOT get prefixed.
623 *
624 * @since 1.20
625 *
626 * @param array $fields
627 * @param array $conditions
628 * @param array $options
629 *
630 * @return ResultWrapper
631 */
632 protected static function rawSelectRow( array $fields, array $conditions = array(), array $options = array() ) {
633 $dbr = wfGetDB( static::getReadDb() );
634
635 return $dbr->selectRow(
636 static::getDBTable(),
637 $fields,
638 $conditions,
639 __METHOD__,
640 $options
641 );
642 }
643
644 /**
645 * Return the names of the fields.
646 *
647 * @since 1.20
648 *
649 * @return array
650 */
651 public function getFieldNames() {
652 return array_keys( $this->table->getFieldTypes() );
653 }
654
655 /**
656 * Computes and updates the values of the summary fields.
657 *
658 * @since 1.20
659 *
660 * @param array|string|null $summaryFields
661 */
662 public function loadSummaryFields( $summaryFields = null ) {
663
664 }
665
666 /**
667 * Sets the value for the @see $updateSummaries field.
668 *
669 * @since 1.20
670 *
671 * @param boolean $update
672 */
673 public function setUpdateSummaries( $update ) {
674 $this->updateSummaries = $update;
675 }
676
677 /**
678 * Sets the value for the @see $inSummaryMode field.
679 *
680 * @since 1.20
681 *
682 * @param boolean $summaryMode
683 */
684 public function setSummaryMode( $summaryMode ) {
685 $this->inSummaryMode = $summaryMode;
686 }
687
688 /**
689 * Return if any fields got changed.
690 *
691 * @since 1.20
692 *
693 * @param DBDataObject $object
694 * @param boolean $excludeSummaryFields When set to true, summary field changes are ignored.
695 *
696 * @return boolean
697 */
698 protected function fieldsChanged( DBDataObject $object, $excludeSummaryFields = false ) {
699 foreach ( $this->fields as $name => $value ) {
700 $excluded = $excludeSummaryFields && in_array( $name, $this->getSummaryFields() );
701
702 if ( !$excluded && $object->getField( $name ) !== $value ) {
703 return true;
704 }
705 }
706
707 return false;
708 }
709
710 protected function getDBTable() {
711 return $this->table->getDBTable();
712 }
713
714 /**
715 * Get an array with fields from a database result,
716 * that can be fed directly to the constructor or
717 * to setFields.
718 *
719 * @since 1.20
720 *
721 * @param object $result
722 *
723 * @return array
724 */
725 public function getFieldsFromDBResult( $result ) {
726 $result = (array)$result;
727 return array_combine(
728 $this->unprefixFieldNames( array_keys( $result ) ),
729 array_values( $result )
730 );
731 }
732
733 /**
734 * Get a new instance of the class from a database result.
735 *
736 * @since 1.20
737 *
738 * @param stdClass $result
739 *
740 * @return DBDataObject
741 */
742 public function newFromDBResult( stdClass $result ) {
743 return $this->newFromArray( $this->getFieldsFromDBResult( $result ) );
744 }
745
746 /**
747 * Returns the table this DBDataObject is a row in.
748 *
749 * @since 1.20
750 *
751 * @return DBTable
752 */
753 public function getTable() {
754 return $this->table;
755 }
756
757 }