Localisation updates from http://translatewiki.net.
[mediawiki.git] / includes / db / ORMRow.php
blob6f19fe13027fe577bd1aa47f5f35282f303bd559
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.
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.
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.
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
23 * @since 1.20
25 * @file ORMRow.php
26 * @ingroup ORM
28 * @licence GNU GPL v2 or later
29 * @author Jeroen De Dauw < jeroendedauw@gmail.com >
32 abstract class ORMRow implements IORMRow {
34 /**
35 * The fields of the object.
36 * field name (w/o prefix) => value
38 * @since 1.20
39 * @var array
41 protected $fields = array( 'id' => null );
43 /**
44 * @since 1.20
45 * @var ORMTable
47 protected $table;
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.
55 * @since 1.20
56 * @var bool
58 protected $updateSummaries = true;
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.
65 * @since 1.20
66 * @var bool
68 protected $inSummaryMode = false;
70 /**
71 * Constructor.
73 * @since 1.20
75 * @param IORMTable $table
76 * @param array|null $fields
77 * @param boolean $loadDefaults
79 public function __construct( IORMTable $table, $fields = null, $loadDefaults = false ) {
80 $this->table = $table;
82 if ( !is_array( $fields ) ) {
83 $fields = array();
86 if ( $loadDefaults ) {
87 $fields = array_merge( $this->table->getDefaults(), $fields );
90 $this->setFields( $fields );
93 /**
94 * Load the specified fields from the database.
96 * @since 1.20
98 * @param array|null $fields
99 * @param boolean $override
100 * @param boolean $skipLoaded
102 * @return bool Success indicator
104 public function loadFields( $fields = null, $override = true, $skipLoaded = false ) {
105 if ( is_null( $this->getId() ) ) {
106 return false;
109 if ( is_null( $fields ) ) {
110 $fields = array_keys( $this->table->getFields() );
113 if ( $skipLoaded ) {
114 $fields = array_diff( $fields, array_keys( $this->fields ) );
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 )
124 if ( $result !== false ) {
125 $this->setFields( $this->table->getFieldsFromDBResult( $result ), $override );
126 return true;
128 return false;
131 return true;
135 * Gets the value of a field.
137 * @since 1.20
139 * @param string $name
140 * @param mixed $default
142 * @throws MWException
143 * @return mixed
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 );
156 * Gets the value of a field but first loads it if not done so already.
158 * @since 1.20
160 * @param string$name
162 * @return mixed
164 public function loadAndGetField( $name ) {
165 if ( !$this->hasField( $name ) ) {
166 $this->loadFields( array( $name ) );
169 return $this->getField( $name );
173 * Remove a field.
175 * @since 1.20
177 * @param string $name
179 public function removeField( $name ) {
180 unset( $this->fields[$name] );
184 * Returns the objects database id.
186 * @since 1.20
188 * @return integer|null
190 public function getId() {
191 return $this->getField( 'id' );
195 * Sets the objects database id.
197 * @since 1.20
199 * @param integer|null $id
201 public function setId( $id ) {
202 $this->setField( 'id', $id );
206 * Gets if a certain field is set.
208 * @since 1.20
210 * @param string $name
212 * @return boolean
214 public function hasField( $name ) {
215 return array_key_exists( $name, $this->fields );
219 * Gets if the id field is set.
221 * @since 1.20
223 * @return boolean
225 public function hasIdField() {
226 return $this->hasField( 'id' )
227 && !is_null( $this->getField( 'id' ) );
231 * Sets multiple fields.
233 * @since 1.20
235 * @param array $fields The fields to set
236 * @param boolean $override Override already set fields with the provided values?
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 );
247 * Gets the fields => values to write to the table.
249 * @since 1.20
251 * @return array
253 protected function getWriteValues() {
254 $values = array();
256 foreach ( $this->table->getFields() as $name => $type ) {
257 if ( array_key_exists( $name, $this->fields ) ) {
258 $value = $this->fields[$name];
260 switch ( $type ) {
261 case 'array':
262 $value = (array)$value;
263 case 'blob':
264 $value = serialize( $value );
267 $values[$this->table->getPrefixedField( $name )] = $value;
271 return $values;
275 * Serializes the object to an associative array which
276 * can then easily be converted into JSON or similar.
278 * @since 1.20
280 * @param null|array $fields
281 * @param boolean $incNullId
283 * @return array
285 public function toArray( $fields = null, $incNullId = false ) {
286 $data = array();
287 $setFields = array();
289 if ( !is_array( $fields ) ) {
290 $setFields = $this->getSetFieldNames();
291 } else {
292 foreach ( $fields as $field ) {
293 if ( $this->hasField( $field ) ) {
294 $setFields[] = $field;
299 foreach ( $setFields as $field ) {
300 if ( $incNullId || $field != 'id' || $this->hasIdField() ) {
301 $data[$field] = $this->getField( $field );
305 return $data;
309 * Load the default values, via getDefaults.
311 * @since 1.20
313 * @param boolean $override
315 public function loadDefaults( $override = true ) {
316 $this->setFields( $this->table->getDefaults(), $override );
320 * Writes the answer to the database, either updating it
321 * when it already exists, or inserting it when it doesn't.
323 * @since 1.20
325 * @param string|null $functionName
327 * @return boolean Success indicator
329 public function save( $functionName = null ) {
330 if ( $this->hasIdField() ) {
331 return $this->saveExisting( $functionName );
332 } else {
333 return $this->insert( $functionName );
338 * Updates the object in the database.
340 * @since 1.20
342 * @param string|null $functionName
344 * @return boolean Success indicator
346 protected function saveExisting( $functionName = null ) {
347 $dbw = wfGetDB( DB_MASTER );
349 $success = $dbw->update(
350 $this->table->getName(),
351 $this->getWriteValues(),
352 $this->table->getPrefixedValues( $this->getUpdateConditions() ),
353 is_null( $functionName ) ? __METHOD__ : $functionName
356 // DatabaseBase::update does not always return true for success as documented...
357 return $success !== false;
361 * Returns the WHERE considtions needed to identify this object so
362 * it can be updated.
364 * @since 1.20
366 * @return array
368 protected function getUpdateConditions() {
369 return array( 'id' => $this->getId() );
373 * Inserts the object into the database.
375 * @since 1.20
377 * @param string|null $functionName
378 * @param array|null $options
380 * @return boolean Success indicator
382 protected function insert( $functionName = null, array $options = null ) {
383 $dbw = wfGetDB( DB_MASTER );
385 $success = $dbw->insert(
386 $this->table->getName(),
387 $this->getWriteValues(),
388 is_null( $functionName ) ? __METHOD__ : $functionName,
389 is_null( $options ) ? array( 'IGNORE' ) : $options
392 // DatabaseBase::insert does not always return true for success as documented...
393 $success = $success !== false;
395 if ( $success ) {
396 $this->setField( 'id', $dbw->insertId() );
399 return $success;
403 * Removes the object from the database.
405 * @since 1.20
407 * @return boolean Success indicator
409 public function remove() {
410 $this->beforeRemove();
412 $success = $this->table->delete( array( 'id' => $this->getId() ) );
414 // DatabaseBase::delete does not always return true for success as documented...
415 $success = $success !== false;
417 if ( $success ) {
418 $this->onRemoved();
421 return $success;
425 * Gets called before an object is removed from the database.
427 * @since 1.20
429 protected function beforeRemove() {
430 $this->loadFields( $this->getBeforeRemoveFields(), false, true );
434 * Before removal of an object happens, @see beforeRemove gets called.
435 * This method loads the fields of which the names have been returned by this one (or all fields if null is returned).
436 * This allows for loading info needed after removal to get rid of linked data and the like.
438 * @since 1.20
440 * @return array|null
442 protected function getBeforeRemoveFields() {
443 return array();
447 * Gets called after successfull removal.
448 * Can be overriden to get rid of linked data.
450 * @since 1.20
452 protected function onRemoved() {
453 $this->setField( 'id', null );
457 * Return the names and values of the fields.
459 * @since 1.20
461 * @return array
463 public function getFields() {
464 return $this->fields;
468 * Return the names of the fields.
470 * @since 1.20
472 * @return array
474 public function getSetFieldNames() {
475 return array_keys( $this->fields );
479 * Sets the value of a field.
480 * Strings can be provided for other types,
481 * so this method can be called from unserialization handlers.
483 * @since 1.20
485 * @param string $name
486 * @param mixed $value
488 * @throws MWException
490 public function setField( $name, $value ) {
491 $fields = $this->table->getFields();
493 if ( array_key_exists( $name, $fields ) ) {
494 switch ( $fields[$name] ) {
495 case 'int':
496 $value = (int)$value;
497 break;
498 case 'float':
499 $value = (float)$value;
500 break;
501 case 'bool':
502 if ( is_string( $value ) ) {
503 $value = $value !== '0';
504 } elseif ( is_int( $value ) ) {
505 $value = $value !== 0;
507 break;
508 case 'array':
509 if ( is_string( $value ) ) {
510 $value = unserialize( $value );
513 if ( !is_array( $value ) ) {
514 $value = array();
516 break;
517 case 'blob':
518 if ( is_string( $value ) ) {
519 $value = unserialize( $value );
521 break;
522 case 'id':
523 if ( is_string( $value ) ) {
524 $value = (int)$value;
526 break;
529 $this->fields[$name] = $value;
530 } else {
531 throw new MWException( 'Attempted to set unknown field ' . $name );
536 * Add an amount (can be negative) to the specified field (needs to be numeric).
537 * TODO: most off this stuff makes more sense in the table class
539 * @since 1.20
541 * @param string $field
542 * @param integer $amount
544 * @return boolean Success indicator
546 public function addToField( $field, $amount ) {
547 if ( $amount == 0 ) {
548 return true;
551 if ( !$this->hasIdField() ) {
552 return false;
555 $absoluteAmount = abs( $amount );
556 $isNegative = $amount < 0;
558 $dbw = wfGetDB( DB_MASTER );
560 $fullField = $this->table->getPrefixedField( $field );
562 $success = $dbw->update(
563 $this->table->getName(),
564 array( "$fullField=$fullField" . ( $isNegative ? '-' : '+' ) . $absoluteAmount ),
565 array( $this->table->getPrefixedField( 'id' ) => $this->getId() ),
566 __METHOD__
569 if ( $success && $this->hasField( $field ) ) {
570 $this->setField( $field, $this->getField( $field ) + $amount );
573 return $success;
577 * Return the names of the fields.
579 * @since 1.20
581 * @return array
583 public function getFieldNames() {
584 return array_keys( $this->table->getFields() );
588 * Computes and updates the values of the summary fields.
590 * @since 1.20
592 * @param array|string|null $summaryFields
594 public function loadSummaryFields( $summaryFields = null ) {
599 * Sets the value for the @see $updateSummaries field.
601 * @since 1.20
603 * @param boolean $update
605 public function setUpdateSummaries( $update ) {
606 $this->updateSummaries = $update;
610 * Sets the value for the @see $inSummaryMode field.
612 * @since 1.20
614 * @param boolean $summaryMode
616 public function setSummaryMode( $summaryMode ) {
617 $this->inSummaryMode = $summaryMode;
621 * Return if any fields got changed.
623 * @since 1.20
625 * @param IORMRow $object
626 * @param boolean|array $excludeSummaryFields
627 * When set to true, summary field changes are ignored.
628 * Can also be an array of fields to ignore.
630 * @return boolean
632 protected function fieldsChanged( IORMRow $object, $excludeSummaryFields = false ) {
633 $exclusionFields = array();
635 if ( $excludeSummaryFields !== false ) {
636 $exclusionFields = is_array( $excludeSummaryFields ) ? $excludeSummaryFields : $this->table->getSummaryFields();
639 foreach ( $this->fields as $name => $value ) {
640 $excluded = $excludeSummaryFields && in_array( $name, $exclusionFields );
642 if ( !$excluded && $object->getField( $name ) !== $value ) {
643 return true;
647 return false;
651 * Returns the table this IORMRow is a row in.
653 * @since 1.20
655 * @return IORMTable
657 public function getTable() {
658 return $this->table;