Rewrite preference DbStore

refs #5682
This commit is contained in:
Johannes Meyer 2014-04-08 13:28:45 +02:00
parent a1649a1f22
commit 3195e6a897
3 changed files with 165 additions and 187 deletions

View File

@ -7,7 +7,10 @@ namespace Icinga\User\Preferences;
use \Zend_Config; use \Zend_Config;
use Icinga\User; use Icinga\User;
use Icinga\User\Preferences; use Icinga\User\Preferences;
use Icinga\Data\ResourceFactory;
use Icinga\Exception\ConfigurationError; use Icinga\Exception\ConfigurationError;
use Icinga\Data\Db\Connection as DbConnection;
use Icinga\Application\Config as IcingaConfig;
/** /**
* Preferences store factory * Preferences store factory
@ -120,13 +123,20 @@ abstract class PreferencesStore
); );
} }
$storeClass = 'Icinga\\User\\Preferences\\Store\\' . ucfirst(strtolower($type)) . 'Store'; $type = ucfirst(strtolower($type));
$storeClass = 'Icinga\\User\\Preferences\\Store\\' . $type . 'Store';
if (!class_exists($storeClass)) { if (!class_exists($storeClass)) {
throw new ConfigurationError( throw new ConfigurationError(
'Preferences configuration defines an invalid storage type. Storage type ' . $type . ' not found' 'Preferences configuration defines an invalid storage type. Storage type ' . $type . ' not found'
); );
} }
if ($type === 'Ini') {
$config->location = IcingaConfig::resolvePath($config->configPath);
} elseif ($type === 'Db') {
$config->connection = new DbConnection(ResourceFactory::getResourceConfig($config->resource));
}
return new $storeClass($config, $user); return new $storeClass($config, $user);
} }
} }

View File

@ -1,44 +1,20 @@
<?php <?php
// {{{ICINGA_LICENSE_HEADER}}} // {{{ICINGA_LICENSE_HEADER}}}
/**
* This file is part of Icinga Web 2.
*
* Icinga Web 2 - Head for multiple monitoring backends.
* Copyright (C) 2013 Icinga Development Team
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* @copyright 2013 Icinga Development Team <info@icinga.org>
* @license http://www.gnu.org/licenses/gpl-2.0.txt GPL, version 2
* @author Icinga Development Team <info@icinga.org>
*
*/
// {{{ICINGA_LICENSE_HEADER}}} // {{{ICINGA_LICENSE_HEADER}}}
namespace Icinga\User\Preferences; namespace Icinga\User\Preferences\Store;
use Icinga\User; use \Exception;
use SplSubject; use \Zend_Db_Select;
use Icinga\Exception\ProgrammingError; use Icinga\Exception\NotReadableError;
use Icinga\Exception\NotWritableError;
use Icinga\User\Preferences; use Icinga\User\Preferences;
use Icinga\Data\ResourceFactory; use Icinga\User\Preferences\PreferencesStore;
/** /**
* Store user preferences in database * Load and save user preferences by using a database
*/ */
class DbStore implements LoadInterface, FlushObserverInterface class DbStore extends PreferencesStore
{ {
/** /**
* Column name for username * Column name for username
@ -55,55 +31,24 @@ class DbStore implements LoadInterface, FlushObserverInterface
*/ */
const COLUMN_VALUE = 'value'; const COLUMN_VALUE = 'value';
/**
* User object
*
* @var User
*/
private $user;
/**
* Zend database adapter
*
* @var Zend_Db_Adapter_Abstract
*/
private $db;
/** /**
* Table name * Table name
* *
* @var string * @var string
*/ */
private $table = 'preference'; protected $table = 'preference';
/** /**
* Setter for user * Stored preferences
* *
* @param User $user * @var array
*/ */
public function setUser(User $user) protected $preferences = array();
{
$this->user = $user;
ResourceFactory::createResource(
ResourceFactory::getResourceConfig($config->resource)
);
}
/** /**
* Setter for db adapter * Set the table to use
* *
* @param Zend_Db_Adapter_Abstract $db * @param string $table The table name
*/
public function setDbAdapter( $db)
{
$this->db = $db;
}
/**
* Setter for table
*
* @param string $table
*/ */
public function setTable($table) public function setTable($table)
{ {
@ -111,133 +56,157 @@ class DbStore implements LoadInterface, FlushObserverInterface
} }
/** /**
* Load preferences from source * Initialize the store
*/
protected function init()
{
}
/**
* Load preferences from the database
* *
* @return array * @return array
*
* @throws NotReadableError In case the database operation failed
*/ */
public function load() public function load()
{ {
$res = $this->db->select()->from($this->table) try {
->where('username=?', $this->user->getUsername()); $select = new Zend_Db_Select($this->getStoreConfig()->connection->getConnection());
$result = $select->from($this->table, array(self::COLUMN_PREFERENCE, self::COLUMN_VALUE))
$out = array(); ->where(self::COLUMN_USERNAME . ' = ?', $this->getUser()->getUsername())
->query()->fetchAll();
foreach ($res->fetchAll() as $row) { } catch (Exception $e) {
$out[$row->{self::COLUMN_PREFERENCE}] = $row->{self::COLUMN_VALUE}; throw new NotReadableError(
'Cannot fetch preferences for user ' . $this->getUser()->getUsername() . ' from database', 0, $e
);
} }
return $out; if ($result !== false) {
} $values = array();
foreach ($result as $row) {
/** $values[$row->{self::COLUMN_PREFERENCE}] = $row->{self::COLUMN_VALUE};
* Helper to create zend db suitable where condition
*
* @param string $preference
* @return array
*/
private function createWhereCondition($preference)
{
return array(
$this->db->quoteIdentifier(self::COLUMN_USERNAME) . '=?' => $this->user->getUsername(),
$this->db->quoteIdentifier(self::COLUMN_PREFERENCE) . '=?' => $preference
);
}
/**
* Create operation
*
* @param string $preference
* @param mixed $value
* @return int
*/
private function doCreate($preference, $value)
{
return $this->db->insert(
$this->table,
array(
$this->db->quoteIdentifier(self::COLUMN_USERNAME) => $this->user->getUsername(),
$this->db->quoteIdentifier(self::COLUMN_PREFERENCE) => $preference,
$this->db->quoteIdentifier(self::COLUMN_VALUE) => $value
)
);
}
/**
* Update operation
*
* @param string $preference
* @param mixed $value
* @return int
*/
private function doUpdate($preference, $value)
{
return $this->db->update(
$this->table,
array(
self::COLUMN_VALUE => $value
),
$this->createWhereCondition($preference)
);
}
/**
* Delete preference operation
*
* @param string $preference
* @return int
*/
private function doDelete($preference)
{
return $this->db->delete(
$this->table,
$this->createWhereCondition($preference)
);
}
/**
* Receive update from subject
*
* @link http://php.net/manual/en/splobserver.update.php
* @param SplSubject $subject
* @throws ProgrammingError
*/
public function update(SplSubject $subject)
{
if (!$subject instanceof Preferences) {
throw new ProgrammingError('Not compatible with '. get_class($subject));
}
$changeSet = $subject->getChangeSet();
foreach ($changeSet->getCreate() as $key => $value) {
$retVal = $this->doCreate($key, $value);
if (!$retVal) {
throw new ProgrammingError('Could not create preference value in db: '. $key. '='. $value);
} }
$this->preferences = $values;
} }
foreach ($changeSet->getUpdate() as $key => $value) { return $this->preferences;
$retVal = $this->doUpdate($key, $value); }
/* /**
* Fallback if we switch storage type while user logged in * Save the given preferences in the database
*/ *
if (!$retVal) { * @param Preferences $preferences The preferences to save
$retVal = $this->doCreate($key, $value); */
public function save(Preferences $preferences)
{
$preferences = $preferences->toArray();
if (!$retVal) { $toBeInserted = array_diff_key($preferences, $this->preferences);
throw new ProgrammingError('Could not create preference value in db: '. $key. '='. $value); if (!empty($toBeInserted)) {
} $this->insert($toBeInserted);
}
} }
foreach ($changeSet->getDelete() as $key) { $current = $this->preferences;
$retVal = $this->doDelete($key); $toBeUpdated = array();
foreach (array_filter(
array_keys(array_intersect_key($preferences, $this->preferences)),
function ($k) use ($current, $preferences) { return $current[$k] == $preferences[$k] ? false : true; }
) as $key) {
$toBeUpdated[$key] = $preferences[$key];
}
if (!empty($toBeUpdated)) {
$this->update($toBeUpdated);
}
if (!$retVal) { $toBeDeleted = array_keys(array_diff_key($this->preferences, $preferences));
throw new ProgrammingError('Could not delete preference value in db: '. $key); if (!empty($toBeDeleted)) {
$this->delete($toBeDeleted);
}
}
/**
* Insert the given preferences into the database
*
* @param array $preferences The preferences to insert
*
* @throws NotWritableError In case the database operation failed
*/
protected function insert(array $preferences)
{
$db = $this->getStoreConfig()->connection->getConnection();
try {
foreach ($preferences as $key => $value) {
$db->insert(
$this->table,
array(
self::COLUMN_USERNAME => $this->getUser()->getUsername(),
$db->quoteIdentifier(self::COLUMN_PREFERENCE) => $key,
self::COLUMN_VALUE => $value
)
);
} }
} catch (Exception $e) {
throw new NotWritableError(
'Cannot insert preferences for user ' . $this->getUser()->getUsername() . ' into database', 0, $e
);
}
}
/**
* Update the given preferences in the database
*
* @param array $preferences The preferences to update
*
* @throws NotWritableError In case the database operation failed
*/
protected function update(array $preferences)
{
$db = $this->getStoreConfig()->connection->getConnection();
try {
foreach ($preferences as $key => $value) {
$db->update(
$this->table,
array(self::COLUMN_VALUE => $value),
array(
self::COLUMN_USERNAME . '=?' => $this->getUser()->getUsername(),
$db->quoteIdentifier(self::COLUMN_PREFERENCE) . '=?' => $key
)
);
}
} catch (Exception $e) {
throw new NotWritableError(
'Cannot update preferences for user ' . $this->getUser()->getUsername() . ' in database', 0, $e
);
}
}
/**
* Delete the given preference names from the database
*
* @param array $preferenceKeys The preference names to delete
*
* @throws NotWritableError In case the database operation failed
*/
protected function delete(array $preferenceKeys)
{
$db = $this->getStoreConfig()->connection->getConnection();
try {
$db->delete(
$this->table,
array(
self::COLUMN_USERNAME . '=?' => $this->getUser()->getUsername(),
$db->quoteIdentifier(self::COLUMN_PREFERENCE) . ' IN (?)' => $preferenceKeys
)
);
} catch (Exception $e) {
throw new NotWritableError(
'Cannot delete preferences for user ' . $this->getUser()->getUsername() . ' from database', 0, $e
);
} }
} }
} }

View File

@ -11,7 +11,6 @@ use Icinga\Exception\NotReadableError;
use Icinga\Exception\NotWritableError; use Icinga\Exception\NotWritableError;
use Icinga\User\Preferences; use Icinga\User\Preferences;
use Icinga\User\Preferences\PreferencesStore; use Icinga\User\Preferences\PreferencesStore;
use Icinga\Application\Config as IcingaConfig;
/** /**
* Load and save user preferences from and to INI files * Load and save user preferences from and to INI files
@ -46,7 +45,7 @@ class IniStore extends PreferencesStore
{ {
$this->preferencesFile = sprintf( $this->preferencesFile = sprintf(
'%s/%s.ini', '%s/%s.ini',
IcingaConfig::resolvePath($this->getStoreConfig()->configPath), $this->getStoreConfig()->location,
$this->getUser()->getUsername() $this->getUser()->getUsername()
); );
} }
@ -85,7 +84,7 @@ class IniStore extends PreferencesStore
$this->update( $this->update(
array_merge( array_merge(
array_diff_key($preferences, $this->preferences), array_diff_key($preferences, $this->preferences),
array_diff_assoc($preferences, $this->preferences) array_intersect_key($preferences, $this->preferences)
) )
); );
$this->delete(array_keys(array_diff_key($this->preferences, $preferences))); $this->delete(array_keys(array_diff_key($this->preferences, $preferences)));
@ -101,11 +100,11 @@ class IniStore extends PreferencesStore
{ {
if ($this->writer === null) { if ($this->writer === null) {
if (!file_exists($this->preferencesFile)) { if (!file_exists($this->preferencesFile)) {
if (!is_writable($this->getStoreConfig()->configPath)) { if (!is_writable($this->getStoreConfig()->location)) {
throw new NotWritableError( throw new NotWritableError(
sprintf( sprintf(
'Path to the preferences INI files %s is not writable', 'Path to the preferences INI files %s is not writable',
$this->getStoreConfig()->configPath $this->getStoreConfig()->location
) )
); );
} }