Localisation updates from http://translatewiki.net.
[mediawiki.git] / includes / db / ORMRow.php
blob4ac41cceb72b7c7a46b2af54aee32775b20dc49e
1 <?php
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.
9 * These methods are likely candidates for overriding:
10 * * getDefaults
11 * * remove
12 * * insert
13 * * saveExisting
14 * * loadSummaryFields
15 * * getSummaryFields
17 * Main instance methods:
18 * * getField(s)
19 * * setField(s)
20 * * save
21 * * remove
23 * Main static methods:
24 * * select
25 * * update
26 * * delete
27 * * count
28 * * has
29 * * selectRow
30 * * selectFields
31 * * selectFieldsRow
33 * @since 1.20
35 * @file ORMRow.php
37 * @licence GNU GPL v2 or later
38 * @author Jeroen De Dauw < jeroendedauw@gmail.com >
40 abstract class ORMRow {
42 /**
43 * The fields of the object.
44 * field name (w/o prefix) => value
46 * @since 1.20
47 * @var array
49 protected $fields = array( 'id' => null );
51 /**
52 * @since 1.20
53 * @var ORMTable
55 protected $table;
57 /**
58 * If the object should update summaries of linked items when changed.
59 * For example, update the course_count field in universities when a course in courses is deleted.
60 * Settings this to false can prevent needless updating work in situations
61 * such as deleting a university, which will then delete all it's courses.
63 * @since 1.20
64 * @var bool
66 protected $updateSummaries = true;
68 /**
69 * Indicates if the object is in summary mode.
70 * This mode indicates that only summary fields got updated,
71 * which allows for optimizations.
73 * @since 1.20
74 * @var bool
76 protected $inSummaryMode = false;
78 /**
79 * Constructor.
81 * @since 1.20
83 * @param ORMTable $table
84 * @param array|null $fields
85 * @param boolean $loadDefaults
87 public function __construct( ORMTable $table, $fields = null, $loadDefaults = false ) {
88 $this->table = $table;
90 if ( !is_array( $fields ) ) {
91 $fields = array();
94 if ( $loadDefaults ) {
95 $fields = array_merge( $this->table->getDefaults(), $fields );
98 $this->setFields( $fields );
102 * Load the specified fields from the database.
104 * @since 1.20
106 * @param array|null $fields
107 * @param boolean $override
108 * @param boolean $skipLoaded
110 * @return bool Success indicator
112 public function loadFields( $fields = null, $override = true, $skipLoaded = false ) {
113 if ( is_null( $this->getId() ) ) {
114 return false;
117 if ( is_null( $fields ) ) {
118 $fields = array_keys( $this->table->getFields() );
121 if ( $skipLoaded ) {
122 $fields = array_diff( $fields, array_keys( $this->fields ) );
125 if ( !empty( $fields ) ) {
126 $result = $this->table->rawSelectRow(
127 $this->table->getPrefixedFields( $fields ),
128 array( $this->table->getPrefixedField( 'id' ) => $this->getId() ),
129 array( 'LIMIT' => 1 )
132 if ( $result !== false ) {
133 $this->setFields( $this->table->getFieldsFromDBResult( $result ), $override );
134 return true;
136 return false;
139 return true;
143 * Gets the value of a field.
145 * @since 1.20
147 * @param string $name
148 * @param mixed $default
150 * @throws MWException
151 * @return mixed
153 public function getField( $name, $default = null ) {
154 if ( $this->hasField( $name ) ) {
155 return $this->fields[$name];
156 } elseif ( !is_null( $default ) ) {
157 return $default;
158 } else {
159 throw new MWException( 'Attempted to get not-set field ' . $name );
164 * Gets the value of a field but first loads it if not done so already.
166 * @since 1.20
168 * @param string$name
170 * @return mixed
172 public function loadAndGetField( $name ) {
173 if ( !$this->hasField( $name ) ) {
174 $this->loadFields( array( $name ) );
177 return $this->getField( $name );
181 * Remove a field.
183 * @since 1.20
185 * @param string $name
187 public function removeField( $name ) {
188 unset( $this->fields[$name] );
192 * Returns the objects database id.
194 * @since 1.20
196 * @return integer|null
198 public function getId() {
199 return $this->getField( 'id' );
203 * Sets the objects database id.
205 * @since 1.20
207 * @param integer|null $id
209 public function setId( $id ) {
210 $this->setField( 'id', $id );
214 * Gets if a certain field is set.
216 * @since 1.20
218 * @param string $name
220 * @return boolean
222 public function hasField( $name ) {
223 return array_key_exists( $name, $this->fields );
227 * Gets if the id field is set.
229 * @since 1.20
231 * @return boolean
233 public function hasIdField() {
234 return $this->hasField( 'id' )
235 && !is_null( $this->getField( 'id' ) );
239 * Sets multiple fields.
241 * @since 1.20
243 * @param array $fields The fields to set
244 * @param boolean $override Override already set fields with the provided values?
246 public function setFields( array $fields, $override = true ) {
247 foreach ( $fields as $name => $value ) {
248 if ( $override || !$this->hasField( $name ) ) {
249 $this->setField( $name, $value );
255 * Gets the fields => values to write to the table.
257 * @since 1.20
259 * @return array
261 protected function getWriteValues() {
262 $values = array();
264 foreach ( $this->table->getFields() as $name => $type ) {
265 if ( array_key_exists( $name, $this->fields ) ) {
266 $value = $this->fields[$name];
268 switch ( $type ) {
269 case 'array':
270 $value = (array)$value;
271 case 'blob':
272 $value = serialize( $value );
275 $values[$this->table->getPrefixedField( $name )] = $value;
279 return $values;
283 * Serializes the object to an associative array which
284 * can then easily be converted into JSON or similar.
286 * @since 1.20
288 * @param null|array $fields
289 * @param boolean $incNullId
291 * @return array
293 public function toArray( $fields = null, $incNullId = false ) {
294 $data = array();
295 $setFields = array();
297 if ( !is_array( $fields ) ) {
298 $setFields = $this->getSetFieldNames();
299 } else {
300 foreach ( $fields as $field ) {
301 if ( $this->hasField( $field ) ) {
302 $setFields[] = $field;
307 foreach ( $setFields as $field ) {
308 if ( $incNullId || $field != 'id' || $this->hasIdField() ) {
309 $data[$field] = $this->getField( $field );
313 return $data;
317 * Load the default values, via getDefaults.
319 * @since 1.20
321 * @param boolean $override
323 public function loadDefaults( $override = true ) {
324 $this->setFields( $this->table->getDefaults(), $override );
328 * Writes the answer to the database, either updating it
329 * when it already exists, or inserting it when it doesn't.
331 * @since 1.20
333 * @param string|null $functionName
335 * @return boolean Success indicator
337 public function save( $functionName = null ) {
338 if ( $this->hasIdField() ) {
339 return $this->saveExisting( $functionName );
340 } else {
341 return $this->insert( $functionName );
346 * Updates the object in the database.
348 * @since 1.20
350 * @param string|null $functionName
352 * @return boolean Success indicator
354 protected function saveExisting( $functionName = null ) {
355 $dbw = wfGetDB( DB_MASTER );
357 $success = $dbw->update(
358 $this->table->getName(),
359 $this->getWriteValues(),
360 $this->table->getPrefixedValues( $this->getUpdateConditions() ),
361 is_null( $functionName ) ? __METHOD__ : $functionName
364 return $success;
368 * Returns the WHERE considtions needed to identify this object so
369 * it can be updated.
371 * @since 1.20
373 * @return array
375 protected function getUpdateConditions() {
376 return array( 'id' => $this->getId() );
380 * Inserts the object into the database.
382 * @since 1.20
384 * @param string|null $functionName
385 * @param array|null $options
387 * @return boolean Success indicator
389 protected function insert( $functionName = null, array $options = null ) {
390 $dbw = wfGetDB( DB_MASTER );
392 $result = $dbw->insert(
393 $this->table->getName(),
394 $this->getWriteValues(),
395 is_null( $functionName ) ? __METHOD__ : $functionName,
396 is_null( $options ) ? array( 'IGNORE' ) : $options
399 if ( $result ) {
400 $this->setField( 'id', $dbw->insertId() );
403 return $result;
407 * Removes the object from the database.
409 * @since 1.20
411 * @return boolean Success indicator
413 public function remove() {
414 $this->beforeRemove();
416 $success = $this->table->delete( array( 'id' => $this->getId() ) );
418 if ( $success ) {
419 $this->onRemoved();
422 return $success;
426 * Gets called before an object is removed from the database.
428 * @since 1.20
430 protected function beforeRemove() {
431 $this->loadFields( $this->getBeforeRemoveFields(), false, true );
435 * Before removal of an object happens, @see beforeRemove gets called.
436 * This method loads the fields of which the names have been returned by this one (or all fields if null is returned).
437 * This allows for loading info needed after removal to get rid of linked data and the like.
439 * @since 1.20
441 * @return array|null
443 protected function getBeforeRemoveFields() {
444 return array();
448 * Gets called after successfull removal.
449 * Can be overriden to get rid of linked data.
451 * @since 1.20
453 protected function onRemoved() {
454 $this->setField( 'id', null );
458 * Return the names and values of the fields.
460 * @since 1.20
462 * @return array
464 public function getFields() {
465 return $this->fields;
469 * Return the names of the fields.
471 * @since 1.20
473 * @return array
475 public function getSetFieldNames() {
476 return array_keys( $this->fields );
480 * Sets the value of a field.
481 * Strings can be provided for other types,
482 * so this method can be called from unserialization handlers.
484 * @since 1.20
486 * @param string $name
487 * @param mixed $value
489 * @throws MWException
491 public function setField( $name, $value ) {
492 $fields = $this->table->getFields();
494 if ( array_key_exists( $name, $fields ) ) {
495 switch ( $fields[$name] ) {
496 case 'int':
497 $value = (int)$value;
498 break;
499 case 'float':
500 $value = (float)$value;
501 break;
502 case 'bool':
503 if ( is_string( $value ) ) {
504 $value = $value !== '0';
505 } elseif ( is_int( $value ) ) {
506 $value = $value !== 0;
508 break;
509 case 'array':
510 if ( is_string( $value ) ) {
511 $value = unserialize( $value );
514 if ( !is_array( $value ) ) {
515 $value = array();
517 break;
518 case 'blob':
519 if ( is_string( $value ) ) {
520 $value = unserialize( $value );
522 break;
523 case 'id':
524 if ( is_string( $value ) ) {
525 $value = (int)$value;
527 break;
530 $this->fields[$name] = $value;
531 } else {
532 throw new MWException( 'Attempted to set unknown field ' . $name );
537 * Add an amount (can be negative) to the specified field (needs to be numeric).
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 ORMRow $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( ORMRow $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 ORMRow is a row in.
653 * @since 1.20
655 * @return ORMTable
657 public function getTable() {
658 return $this->table;