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