public function onAfterSave(DataModel &$model)
{
if (!$model->hasField('asset_id') || !$model->isAssetsTracked()) {
return true;
}
$assetFieldAlias = $model->getFieldAlias('asset_id');
$currentAssetId = $model->getFieldValue('asset_id');
unset($model->{$assetFieldAlias});
// Create the object used for inserting/udpating data to the database
$fields = $model->getTableFields();
// Let's remove the asset_id field, since we unset the property above and we would get a PHP notice
if (isset($fields[$assetFieldAlias])) {
unset($fields[$assetFieldAlias]);
}
// Asset Tracking
$parentId = $model->getAssetParentId();
$name = $model->getAssetName();
$title = $model->getAssetTitle();
$asset = \JTable::getInstance('Asset');
$asset->loadByName($name);
// Re-inject the asset id.
$this->{$assetFieldAlias} = $asset->id;
// Check for an error.
$error = $asset->getError();
// Since we are using JTable, there is no way to mock it and test for failures :(
// @codeCoverageIgnoreStart
if ($error) {
throw new \Exception($error);
}
// @codeCoverageIgnoreEnd
// Specify how a new or moved node asset is inserted into the tree.
// Since we're unsetting the table field before, this statement is always true...
if (empty($model->{$assetFieldAlias}) || $asset->parent_id != $parentId) {
$asset->setLocation($parentId, 'last-child');
}
// Prepare the asset to be stored.
$asset->parent_id = $parentId;
$asset->name = $name;
$asset->title = $title;
if ($model->getRules() instanceof \JAccessRules) {
$asset->rules = (string) $model->getRules();
}
// Since we are using JTable, there is no way to mock it and test for failures :(
// @codeCoverageIgnoreStart
if (!$asset->check() || !$asset->store()) {
throw new \Exception($asset->getError());
}
// @codeCoverageIgnoreEnd
// Create an asset_id or heal one that is corrupted.
if (empty($model->{$assetFieldAlias}) || $currentAssetId != $model->{$assetFieldAlias} && !empty($model->{$assetFieldAlias})) {
// Update the asset_id field in this table.
$model->{$assetFieldAlias} = (int) $asset->id;
$k = $model->getKeyName();
$db = $model->getDbo();
$query = $db->getQuery(true)->update($db->qn($model->getTableName()))->set($db->qn($assetFieldAlias) . ' = ' . (int) $model->{$assetFieldAlias})->where($db->qn($k) . ' = ' . (int) $model->{$k});
$db->setQuery($query)->execute();
}
return true;
}