/**
* Method to check a row out if the necessary properties/fields exist.
*
* To prevent race conditions while editing rows in a database, a row can be checked out if the fields 'checked_out' and 'checked_out_time'
* are available. While a row is checked out, any attempt to store the row by a user other than the one who checked the row out should be
* held until the row is checked in again.
*
* @param integer $userId The Id of the user checking out the row.
* @param mixed $pk An optional primary key value to check out. If not set the instance property value is used.
*
* @return boolean True on success.
*
* @since 1.7.0
* @throws \UnexpectedValueException
*/
public function checkOut($userId, $pk = null)
{
// Pre-processing by observers
$event = AbstractEvent::create('onTableBeforeCheckout', ['subject' => $this, 'userId' => $userId, 'pk' => $pk]);
$this->getDispatcher()->dispatch('onTableBeforeCheckout', $event);
// If there is no checked_out or checked_out_time field, just return true.
if (!$this->hasField('checked_out') || !$this->hasField('checked_out_time')) {
return true;
}
if (\is_null($pk)) {
$pk = array();
foreach ($this->_tbl_keys as $key) {
$pk[$key] = $this->{$key};
}
} elseif (!\is_array($pk)) {
$pk = array($this->_tbl_key => $pk);
}
foreach ($this->_tbl_keys as $key) {
$pk[$key] = \is_null($pk[$key]) ? $this->{$key} : $pk[$key];
if ($pk[$key] === null) {
throw new \UnexpectedValueException('Null primary key not allowed.');
}
}
// Get column names.
$checkedOutField = $this->getColumnAlias('checked_out');
$checkedOutTimeField = $this->getColumnAlias('checked_out_time');
// Get the current time in the database format.
$time = Factory::getDate()->toSql();
// Check the row out by primary key.
$query = $this->_db->getQuery(true)->update($this->_tbl)->set($this->_db->quoteName($checkedOutField) . ' = ' . (int) $userId)->set($this->_db->quoteName($checkedOutTimeField) . ' = ' . $this->_db->quote($time));
$this->appendPrimaryKeys($query, $pk);
$this->_db->setQuery($query);
$this->_db->execute();
// Set table values in the object.
$this->{$checkedOutField} = (int) $userId;
$this->{$checkedOutTimeField} = $time;
// Post-processing by observers
$event = AbstractEvent::create('onTableAfterCheckout', ['subject' => $this, 'userId' => $userId, 'pk' => $pk]);
$this->getDispatcher()->dispatch('onTableAfterCheckout', $event);
return true;
}