/**
* Creates the menu item in the database. If the item already exists it tries to remove it and create it afresh.
*
* @param array &$data The menu item data to create
* @param integer $parentId The parent menu item ID
*
* @return boolean|integer Menu item ID on success, false on failure
*
* @throws \Exception
*
* @since 3.1
*/
protected function _createAdminMenuItem(array &$data, $parentId)
{
$db = $this->parent->getDbo();
/** @var \Joomla\CMS\Table\Menu $table */
$table = Table::getInstance('menu');
try {
$table->setLocation($parentId, 'last-child');
} catch (\InvalidArgumentException $e) {
Log::add($e->getMessage(), Log::WARNING, 'jerror');
return false;
}
if (!$table->bind($data) || !$table->check() || !$table->store()) {
$menutype = $data['menutype'];
$link = $data['link'];
$type = $data['type'];
$menuParentId = $data['parent_id'];
$home = $data['home'];
// The menu item already exists. Delete it and retry instead of throwing an error.
$query = $db->getQuery(true)->select($db->quoteName('id'))->from($db->quoteName('#__menu'))->where([$db->quoteName('menutype') . ' = :menutype', $db->quoteName('client_id') . ' = 1', $db->quoteName('link') . ' = :link', $db->quoteName('type') . ' = :type', $db->quoteName('parent_id') . ' = :parent_id', $db->quoteName('home') . ' = :home'])->bind(':menutype', $menutype)->bind(':link', $link)->bind(':type', $type)->bind(':parent_id', $menuParentId, ParameterType::INTEGER)->bind(':home', $home, ParameterType::BOOLEAN);
$db->setQuery($query);
$menu_id = $db->loadResult();
if (!$menu_id) {
// Oops! Could not get the menu ID. Go back and rollback changes.
Factory::getApplication()->enqueueMessage($table->getError(), 'error');
return false;
} else {
/** @var \Joomla\CMS\Table\Menu $temporaryTable */
$temporaryTable = Table::getInstance('menu');
$temporaryTable->delete($menu_id, true);
$temporaryTable->load($parentId);
$temporaryTable->rebuild($parentId, $temporaryTable->lft, $temporaryTable->level, $temporaryTable->path);
// Retry creating the menu item
$table->setLocation($parentId, 'last-child');
if (!$table->bind($data) || !$table->check() || !$table->store()) {
// Install failed, warn user and rollback changes
Factory::getApplication()->enqueueMessage($table->getError(), 'error');
return false;
}
}
}
return $table->id;
}