Abstract handler for data writing.

Data writers focus on writing a unit of data to the database, including verifying all data to the application rules (including those set by the owner) and doing denormalized updates as necessary.

The writer may also interact with the cache, if required.

package XenForo_Core

 Methods

Constructor.

__construct(\constant $errorHandler, array $inject) 

Parameters

$errorHandler

\constant

Error handler. See {@link ERROR_EXCEPTION} and related.

$inject

arraynull

Dependency injector. Array keys available: db, cache.

Helper method to bulk set values from an array.

bulkSet(array $fields, array $options) 

Parameters

$fields

array

Key-value pairs of fields and values.

$options

array

Options to pass into {@link set()}. See {@link $_setOptions}.

Factory method to get the named data writer.

create(string $class, \constant $errorHandler, array $inject) : \XenForo_DataWriter
Static

The class must exist or be autoloadable or an exception will be thrown.

Parameters

$class

string

Class to load

$errorHandler

\constant

Error handler. See {@link ERROR_EXCEPTION} and related.

$inject

arraynull

Dependencies to inject. See {@link __construct()}.

Returns

Deletes the record that was selected by a call to {@link setExistingData()}.

delete() : boolean

Returns

booleanTrue on success

Trigger an error with the specified string (or phrase object).

error(string | \XenForo_Phrase $error, string | false $errorKey, boolean $specificError) 

Depending on the type of error handler chosen, this may throw an exception.

Parameters

$error

string\XenForo_Phrase

Error message

$errorKey

stringfalse

Unique key for the error. Used to prevent multiple errors from the same field being displayed.

$specificError

boolean

If true and error key specified, overwrites an existing error with this name

Gets data related to this object regardless of where it is defined (new or old).

get(string $field, string $tableName) : mixed

Parameters

$field

string

Field name

$tableName

string

Table name, if empty loops through tables until first match

Returns

mixedReturns null if the specified field could not be found.

Gets the specific named error if reported.

getError(string $errorKey) : string

Parameters

$errorKey

string

Returns

string

Gets all errors that have been triggered.

getErrors() : array

If preSave() has been called and this returns an empty array, a save() should go through.

Returns

array

Explictly gets data from the existing data array.

getExisting(string $field, string $tableName) : mixed

Returns null if not set.

Parameters

$field

string

Field name

$tableName

string

Table name, if empty loops through tables until first match

Returns

mixed

Gets the named piece of extra data.

getExtraData(string $name) : mixed

Parameters

$name

string

Returns

mixed

getFieldNames()

getFieldNames($tableName) 

Parameters

$tableName

Merges the new and existing data to show a "final" view of the data.

getMergedData(string $tableName) : array

This will generally reflect what is in the database.

If no table is specified, all data will be flattened into one array. New data takes priority over existing data, and earlier tables in the list take priority over later tables.

Parameters

$tableName

string

Returns

array

Gets the existing data only into a flat view of the data.

getMergedExistingData(string $tableName) : array

Parameters

$tableName

string

Returns

array

Gets all new data that has been set to date, merged through all tables.

getMergedNewData(string $tableName) 

Parameters

$tableName

string

Gets the specified model object from the cache.

getModelFromCache(string $class) : \XenForo_Model

If it does not exist, it will be instantiated.

Parameters

$class

string

Name of the class to load

Returns

Explictly gets data from the new data array.

getNew(string $field, string $tableName) : mixed

Returns null if not set.

Parameters

$field

string

Field name

$tableName

string

Table name, if empty loops through tables until first match

Returns

mixed

Gets all new data that has been set to date

getNewData() : array

Returns

array

Gets an option.

getOption(string $name) : mixed

The meaning of this option is completely domain specific. If an unknown option specified, an exception will be triggered.

Parameters

$name

string

Name of the option to get

Returns

mixedValue of the option

Splits a (complete) data record array into its constituent tables using the _fields array for use in _getExistingData

getTablesDataFromArray(array $dataArray) : array

In order for this to work, the following must be true: 1) The input array must provide all data that this datawriter requires 2) There can be no overlapping field names in the tables that define this data, unless those fields all store the same value 3) IMPORTANT: If the input array does not include all the required data fields, it is your responsibility to provide it after this function returns.

Parameters

$dataArray

array

Complete data record

Returns

array

External handler to get the SQL update/delete condition for this data.

getUpdateCondition(string $tableName) : string

If there is no existing data, this always returns an empty string, otherwise it proxies to _getUpdateCondition(), which is an abstract function.

Parameters

$tableName

string

Name of the table to fetch the condition for

Returns

string

Returns true if changes have been made to this data.

hasChanges() : boolean

Returns

boolean

Determines if this DW has errors.

hasErrors() : boolean

Returns

boolean

Determines whether the named field has been changed/set.

isChanged(string $field, string $tableName) : boolean

Parameters

$field

string

Field name

$tableName

string

Table name, if empty loops through tables until first match

Returns

boolean

Determines whether or not the specified extra data field has been set at all

isExtraDataSet(string $name) : boolean

Parameters

$name

string

Returns

boolean

Returns true if this DW is inserting a record, rather than updating one.

isInsert() : boolean

Returns

boolean

Returns true if this DW is updating a record, rather than inserting one.

isUpdate() : boolean

Returns

boolean

Merges a set of errors into this DW.

mergeErrors(array $errors) 

Parameters

$errors

array

Public facing handler for final verification before a delete.

preDelete() 

Any verification or complex defaults may be set by this.

It is generally not advisable to override this function. If you just want to add pre-delete behaviors, override _preDelete().

Public facing handler for final verification before a save.

preSave() 

Any verification or complex defaults may be set by this.

It is generally not advisable to override this function. If you just want to add pre-save behaviors, override _preSave().

Saves the changes to the data.

save() : boolean

This either updates an existing record or inserts a new one, depending whether setExistingData was called.

After a successful insert with an auto_increment field, the value will be stored into the new data array with a field marked as autoIncrement. Use get() to get access to it.

Returns

booleanTrue on success

Sets a field.

set(string $field, string $value, string $tableName, array $options) : boolean

This value will be updated when save is called.

Parameters

$field

string

Name of field to update

$value

string

Value to update with

$tableName

string

Table name, if empty then all tables with that column

$options

array

Options. See {@link $_setOptions).

Returns

boolean

Sets the default options for {@link set()}.

setDefaultSetOptions(array $setOptions) 

See $_setOptions for the available options.

Parameters

$setOptions

array

Sets the error handler type.

setErrorHandler(integer $errorHandler) 

Parameters

$errorHandler

integer

Sets the existing data.

setExistingData(mixed $data, boolean $trustInputAsPrimary) : boolean

This causes the system to do an update instead of an insert. This function triggers an error if no data can be fetched from the provided data.

Parameters

$data

mixed

Data that can uniquely ID this item

$trustInputAsPrimary

boolean

If true, trust the passed data to be based on data in DB; if false, the data is used as is (if it's an array)

Returns

boolean

Sets extra data that the DW can use to help it.

setExtraData(string $name, mixed $value) 

The DW should be able to function without this data.

Parameters

$name

string

Name of the data

$value

mixed

Value of the data

Sets the import mode.

setImportMode(\boolean$mode $mode) 

When enabled, preSave, postSave, and verification functions are disabled.

Parameters

$mode

\boolean$mode

Sets an option.

setOption(string $name, mixed $value) 

The meaning of this option is completely domain specific. If an unknown option specified, an exception will be triggered.

Parameters

$name

string

Name of the option to set

$value

mixed

Value of the option

Updates the version ID field for the specified record.

updateVersionId(string $versionIdField, string $versionStringField, string $addOnIdField) : integer

Th add-on ID is determined from a previously set value, so it should not be updated after this is called.

Parameters

$versionIdField

string

Name of the field the version ID will be written to

$versionStringField

string

Name of the field where the version string will be written to

$addOnIdField

string

Name of the field the add-on ID is kept in

Returns

integerVersion ID to use

Applies value limits to a field based on type and other constraints.

_applyFieldValueLimits(string $fieldType, mixed $value, array $extraLimits) : boolean | string

Returns true if the field meets the constraints. The passed in value will be modified by reference.

Parameters

$fieldType

string

Type of the field. See the TYPE_* constants.

$value

mixed

Value for the field.

$extraLimits

array

Extra constraints

Returns

booleanstringEither TRUE or an error message

Starts a new database transaction.

_beginDbTransaction() 

Casts the field value based on the specified type (TYPE_* constants).

_castValueToType(string $fieldType, mixed $value, string $fieldName, array $fieldData) : mixed

Parameters

$fieldType

string

Type to cast to

$value

mixed

Value to cast

$fieldName

string

Name of the field being cast

$fieldData

array

Array of all field data information, for extra options

Returns

mixed

Checks that required field values are still maintained on updates.

_checkRequiredFieldsForUpdate() 

Commits a new database transaction.

_commitDbTransaction() 

Internal handler for a delete action.

_delete() 

Actually does the delete.

Deletes the named master phrase if it exists.

_deleteMasterPhrase(string $title) 

Parameters

$title

string

Returns the admin search model

_getAdminSearchModel() : \XenForo_Model_AdminSearch

Returns the alert model

_getAlertModel() : \XenForo_Model_Alert

Finds the auto-increment field in the list of fields.

_getAutoIncrementField(string $tableName) : string | false

This field is simply the first field tagged with the autoIncrement flag.

Parameters

$tableName

string

Name of the table to obtain the field for

Returns

stringfalseName of the field if found or false

Helper method to get the cache object.

_getCache() : \Zend_Cache_Core | \Zend_Cache_Frontend | false

Returns

\Zend_Cache_Core\Zend_Cache_Frontendfalse

Gets the default set of options for this data writer.

_getDefaultOptions() : array

This is automatically called in the constructor. If you wish to set options in your data writer, override this function. As this is handled at run time rather than compile time, you may use dynamic behaviors to set the option defaults.

Returns

array

Gets the actual existing data out of data that was passed in.

_getExistingData(mixed $data) : array | false

This data may be a scalar or an array. If it's a scalar, assume that it is the primary key (if there is one); if it is an array, attempt to extract the primary key (or some other unique identifier). Then fetch the correct data from a model.

Parameters

$data

mixed

Data that can uniquely ID this item

Returns

arrayfalse

Get the primary key from either an array of data or just the scalar value

_getExistingPrimaryKey(mixed $data, string $primaryKeyField, string $tableName) : string | false

Parameters

$data

mixed

Array of data containing the primary field or a scalar ID

$primaryKeyField

string

Primary key field, if data is an array

$tableName

string

Table name, if empty the first table defined in fields is used

Returns

stringfalse

Gets the fields that are defined for the table.

_getFields() : array

This should return an array with each key being a table name and a further array with each key being a field in database. The value of each entry should be an array, which may have the following keys: * type - one of the TYPE_* constants, this controls the type of data in the field * autoIncrement - set to true when the field is an auto_increment field. Used to populate this field after an insert * required - if set, inserts will be prevented if this field is not set or an empty string (0 is accepted) * requiredError - the phrase title that should be used if the field is not set (only if required) * default - the default value of the field; used if the field isn't set or if the set value is outside the constraints (if a $_setOption is set) * maxLength - for string/binary types only, the maximum length of the data. For strings, in characters; for binary, in bytes. * min - for numeric types only, the minimum value allowed (inclusive) * max - for numeric types only, the maximum value allowed (inclusive) * allowedValues - an array of allowed values for this field (commonly for enums) * verification - a callback to do more advanced verification. Callback function will take params for $value and $this.

Returns

array

Returns the news feed model

_getNewsFeedModel() : \XenForo_Model_NewsFeed

Returns the phrase model

_getPhraseModel() : \XenForo_Model_Phrase

Finds the first table in the _fields array

_getPrimaryTable() : string | false

Returns

stringfalseName of the table or false

Gets the error text (or phrase) for a specific required field.

_getSpecificRequiredFieldErrorText(string $tableName, string $field) : false | string | \XenForo_Phrase

Concrete DWs may override this to get nicer error messages for specific fields.

Parameters

$tableName

string

$field

string

Returns

falsestring\XenForo_Phrase

Gets an array with a list of all table names or, if provided, only the specified table.

_getTableList(string $tableName) : array

Parameters

$tableName

string

Optional table to limit results to.

Returns

array

Gets SQL condition to update the existing record.

_getUpdateCondition(string $tableName) : string

Should read from _existingData.

Parameters

$tableName

string

Table name

Returns

string

_getUserIgnoreModel()

_getUserIgnoreModel() : \XenForo_Model_UserIgnore

Returns the user model

_getUserModel() : \XenForo_Model_User

Determines if we have errors that would prevent a save.

_haveErrorsPreventSave() : boolean

If the silent error handler is used, errors simply trigger a return of true (yes, we have errors); otherwise, errors trigger an exception. Generally, if errors are to be handled, save shouldn't be called.

Returns

booleanTrue if there are errors

Internal save handler.

_insert() 

Inserts or updates a master (language 0) phrase.

_insertOrUpdateMasterPhrase(string $title, string $text, string $addOnId, array $extra) 

Errors will be silently ignored.

Parameters

$title

string

$text

string

$addOnId

string

$extra

array

Determines if the provided value for a field is valid.

_isFieldValueValid(string $fieldName, array $fieldData, mixed $value, array $options) : boolean

The value may be modified based on type, contraints, or other verification methods.

Parameters

$fieldName

string

Name of the field.

$fieldData

array

Data about the field (includes type, contraints, callback, etc)

$value

mixed

Value for the field

$options

array

Options. Uses {@link $_setOptions}.

Returns

boolean

Performs a language rebuild if needed.

_performLanguageRebuild() 

Method designed to be overridden by child classes to add pre-delete behaviors.

_postDelete() 

Method designed to be overridden by child classes to add post-save behaviors.

_postSave() 

This is not called in import mode.

Method designed to be overridden by child classes to add post-save behaviors that should be run after the transaction is committed.

_postSaveAfterTransaction() 

This is not called in import mode.

Method designed to be overridden by child classes to add pre-delete behaviors.

_preDelete() 

Method designed to be overridden by child classes to add pre-save behaviors.

_preSave() 

This is not callbed in import mode.

Method designed to be overridden by child classes to add pre-save behaviors that set dynamic defaults.

_preSaveDefaults() 

This is still called in import mode.

Renames a master phrase.

_renameMasterPhrase(string $oldName, string $newName) 

If you get a conflict, it will be silently ignored.

Parameters

$oldName

string

$newName

string

This resolves unset fields to their defaults (if available) and the checks for required fields that are unset or empty.

_resolveDefaultsAndRequiredFieldsForInsert(boolean $checkRequired) 

If a required field is not set properly, an error is thrown.

Parameters

$checkRequired

boolean

If true, checks required fields

Rolls a database transaction back.

_rollbackDbTransaction() 

Runs the verification callback.

_runVerificationCallback(callback $callback, mixed $value, array $fieldData, $fieldName) : boolean

This callback may modify the value if it chooses to. Callback receives 2 params: the value and this object. The callback must return true if the value was valid.

Returns true if the verification was successful.

Parameters

$callback

callback

Callback to run. Use an array with a string '$this' to callback to this object.

$value

mixed

Value to verify

$fieldData

array

Information about the field, including all constraints to be applied

$fieldName

Returns

boolean

Internal save handler.

_save() 

Deals with both updates and inserts.

Sets the auto-increment value to the auto increment field, if there is one.

_setAutoIncrementValue(integer $insertId, string $tableName, bool $updateAll) : boolean

If the ID passed in is 0, nothing will be updated.

Parameters

$insertId

integer

Auto-increment value from 0.

$tableName

string

Name of the table set the auto increment field in

$updateAll

bool

Update all tables with cross referenced auto increment fields

Returns

booleanTrue on update

Internal function to set a field without any validation or type casting.

_setInternal(string $table, string $field, mixed $newValue, boolean $forceSet) 

Use only when you're sure validation, etc isn't needed. The field will only be set if the value has changed.

Parameters

$table

string

Table the field belongs to

$field

string

Name of the field

$newValue

mixed

Value for the field

$forceSet

boolean

If true, the set always goes through

Internal helper for calling set after save and not triggering an error.

_setPostSave(string $field, string $newValue, string $tableName, array $options) : boolean

Parameters

$field

string

Name of field to update

$newValue

string

Value to update with

$tableName

string

Table name, if empty then all tables with that column

$options

array

Options. See {@link $_setOptions).

Returns

boolean

Triggers the error for when invalid existing data was requested.

_triggerInvalidExistingDataError() 

This can (and generally should) be extended by concrete DWs to give an error that is more specific to their content type.

Triggers the error for a required field not being specified.

_triggerRequiredFieldError(string $tableName, string $field) 

Parameters

$tableName

string

$field

string

Internal update handler.

_update() 

 Properties

 

$_cache : \Zend_Cache_Core | \Zend_Cache_Frontend
 

$_db : \Zend_Db_Adapter_Abstract
 

$_errorHandler : integer

See ERROR_EXCEPTION and related.

 

$_errors : array

This is always populated when an error occurs, though an exception may be thrown as well.

 

$_existingData : array

This is only populated when updating a record.

 

$_existingDataErrorPhrase : string
 

$_extraData : array

The DW should usually function without any data in this array. Any data that DW supports should be documented in this array, preferably by the use of constants.

Required data (for example, a related phrase) can be included here if necessary.

 

$_fields : array

See _getFields() for more info.

 

$_importMode : boolean

To be used when using the DW for importing data in bulk. Note that you are responsible for manually replicating the post save effects.

 

$_modelCache : array

This is now a static cache to allow data to be reused between data writers, as they are often used in bulk.

 

$_newData : array
 

$_options : array

All options that a data writer supports must be documented in this array, preferably by the use of constants.

 

$_preDeleteCalled : boolean

It can only be called once.

 

$_preSaveCalled : boolean

It can only be called once.

 

$_setOptions : array

Available options are: (default value is listed in parentheses) * ignoreInvalidFields (false) - when true, an invalid field is simply ignored; otherwise an error is triggered * replaceInvalidWithDefault (false) - when true, invalid values are replaced with the default value (if there is one) * runVerificationCallback (true) - when true, verification callbacks are run when setting * setAfterPreSave (false) - when true, you may set data after preSave is called. This has very specific uses.

 

$_triggerLanguageRebuild : boolean

 Constants

 

Constant for error handling.

ERROR_ARRAY : integer

Use this to push errors onto an array. If you try to save while there are errors, an exception will be thrown.

 

Constant for error handling.

ERROR_EXCEPTION : integer

Use this to trigger an exception when an error occurs.

 

Constant for error handling.

ERROR_SILENT : integer

Use this to push errors onto an array. If you try to save while there are errors, the save will silently fail. Use this in places where you aren't interested in handling errors.

 

Constant for data fields.

TYPE_BINARY : string

Use this for binary or ASCII-only fields. Limits will refer to bytes.

 

Constant for data fields.

TYPE_BOOLEAN : string

Use this for 0/1 boolean integer fields.

 

Constant for data fields.

TYPE_FLOAT : string

Use this for float fields. Limits can be applied on the range of valid values.

 

Constant for data fields.

TYPE_INT : string

Use this for integer fields. Limits can be applied on the range of valid values.

 

Data is serialized to JSON.

TYPE_JSON : string
 

Data is serialized.

TYPE_SERIALIZED : string

Ensures that if the data is not a string, it is serialized to ne.

 

Constant for data fields.

TYPE_STRING : string

Use this for string fields. String fields are assumed to be UTF-8 and limits will refer to characters.

 

Constant for data fields.

TYPE_UINT : string

Use this for unsigned integer fields. Negative values will always fail to be valid. Limits can be applied on the range of valid values.

 

Constant for data fields.

TYPE_UINT_FORCED : string

Use this for unsigned integer fields. This differs from TYPE_UINT in that negative values will be silently cast to 0. Limits can be applied on the range of valid values.

 

Constant for data fields.

TYPE_UNKNOWN : string

Use this for fields that have a type that cannot be known statically. Use this sparingly, as you must write code to ensure that the value is a scalar before it is inserted into the DB. The behavior if you don't do this is not defined!