Refactor PreferencesStore and IniStore

refs #5682
This commit is contained in:
Johannes Meyer 2014-04-07 15:13:28 +02:00
parent 6692f253fd
commit a1649a1f22
3 changed files with 128 additions and 159 deletions

View File

@ -1,38 +1,13 @@
<?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;
use Zend_Config; use \Zend_Config;
use Icinga\User; use Icinga\User;
use Icinga\Exception\ConfigurationError;
use Icinga\User\Preferences; use Icinga\User\Preferences;
use Icinga\Exception\ConfigurationError;
/** /**
* Preferences store factory * Preferences store factory
@ -46,7 +21,7 @@ use Icinga\User\Preferences;
* use Icinga\User\Preferences\PreferencesStore; * use Icinga\User\Preferences\PreferencesStore;
* *
* // Create a INI store * // Create a INI store
* $store = new PreferencesStore( * $store = PreferencesStore::create(
* new Zend_Config( * new Zend_Config(
* 'type' => 'ini', * 'type' => 'ini',
* 'configPath' => '/path/to/preferences' * 'configPath' => '/path/to/preferences'
@ -57,6 +32,7 @@ use Icinga\User\Preferences;
* $preferences = new Preferences($store->load()); * $preferences = new Preferences($store->load());
* $preferences->aPreference = 'value'; * $preferences->aPreference = 'value';
* $store->save($preferences); * $store->save($preferences);
* </code>
*/ */
abstract class PreferencesStore abstract class PreferencesStore
{ {
@ -65,20 +41,20 @@ abstract class PreferencesStore
* *
* @var Zend_Config * @var Zend_Config
*/ */
private $config; protected $config;
/** /**
* Given user * Given user
* *
* @var User * @var User
*/ */
private $user; protected $user;
/** /**
* Create a new store * Create a new store
* *
* @param Zend_Config $config * @param Zend_Config $config The config for this adapter
* @param User $user * @param User $user The user to which these preferences belong
*/ */
public function __construct(Zend_Config $config, User $user) public function __construct(Zend_Config $config, User $user)
{ {
@ -87,20 +63,12 @@ abstract class PreferencesStore
$this->init(); $this->init();
} }
/**
* Initialize the sore
*/
public function init()
{
}
/** /**
* Getter for the store config * Getter for the store config
* *
* @return Zend_Config * @return Zend_Config
*/ */
final public function getStoreConfig() public function getStoreConfig()
{ {
return $this->config; return $this->config;
} }
@ -108,54 +76,41 @@ abstract class PreferencesStore
/** /**
* Getter for the user * Getter for the user
* *
* @return User * @return User
*/ */
final public function getUser() public function getUser()
{ {
return $this->user; return $this->user;
} }
/**
* Initialize the store
*/
abstract protected function init();
/** /**
* Load preferences from source * Load preferences from source
* *
* @return array * @return array
*/ */
abstract public function load(); abstract public function load();
/** /**
* Save the given preferences * Save the given preferences
* *
* @param Preferences $preferences * @param Preferences $preferences The preferences to save
*/ */
public function save(Preferences $preferences) abstract public function save(Preferences $preferences);
{
$storedPreferences = $this->load();
$preferences = $preferences->toArray();
$newPreferences = array_diff_key($preferences, $storedPreferences);
$updatedPreferences = array_diff_assoc($preferences, $storedPreferences);
$deletedPreferences = array_keys(array_diff_key($storedPreferences, $preferences));
if (count($newPreferences) || count($updatedPreferences) || count($deletedPreferences)) {
$this->cud($newPreferences, $updatedPreferences, $deletedPreferences);
}
}
/**
* Create, update and delete the given preferences
*
* @param array $newPreferences Key-value array of preferences to create
* @param array $updatedPreferences Key-value array of preferences to update
* @param array $deletedPreferences An array of preference names to delete
*/
abstract public function cud($newPreferences, $updatedPreferences, $deletedPreferences);
/** /**
* Create preferences storage adapter from config * Create preferences storage adapter from config
* *
* @param Zend_Config $config * @param Zend_Config $config The config for the adapter
* @param User $user * @param User $user The user to which these preferences belong
* *
* @return self * @return self
* @throws ConfigurationError When the configuration defines an invalid storage type *
* @throws ConfigurationError When the configuration defines an invalid storage type
*/ */
public static function create(Zend_Config $config, User $user) public static function create(Zend_Config $config, User $user)
{ {
@ -164,13 +119,14 @@ abstract class PreferencesStore
'Preferences configuration is missing the type directive' 'Preferences configuration is missing the type directive'
); );
} }
$type = ucfirst(strtolower($type));
$storeClass = 'Icinga\\User\\Preferences\\Store\\' . $type . 'Store'; $storeClass = 'Icinga\\User\\Preferences\\Store\\' . ucfirst(strtolower($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'
); );
} }
return new $storeClass($config, $user); return new $storeClass($config, $user);
} }
} }

View File

@ -4,48 +4,17 @@
namespace Icinga\User\Preferences\Store; namespace Icinga\User\Preferences\Store;
use Zend_Config; use \Zend_Config;
use Icinga\Application\Config as IcingaConfig; use Icinga\Util\File;
use Icinga\Config\PreservingIniWriter; use Icinga\Config\PreservingIniWriter;
use Icinga\Exception\NotReadableError; use Icinga\Exception\NotReadableError;
use Icinga\Exception\NotWritableError; use Icinga\Exception\NotWritableError;
use Icinga\User; use Icinga\User\Preferences;
use Icinga\User\Preferences\PreferencesStore; use Icinga\User\Preferences\PreferencesStore;
use Icinga\Util\File; 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
*
* Usage example:
* <code>
* <?php
*
* use Zend_Config;
* use Icinga\User\Preferences;
* use Icinga\User\Preferences\PreferencesStore;
* use Icinga\User\Preferences\Store\IniStore;
*
* // Create the store from the factory (preferred approach)
* $store = new PreferencesStore(
* new Zend_Config(
* 'type' => 'ini',
* 'configPath' => '/path/to/preferences'
* ),
* $user // Instance of \Icinga\User
* );
*
* // Create the store directly
* $store = new IniStore(
* new Zend_Config(
* 'configPath' => '/path/to/preferences'
* ),
* $user // Instance of \Icinga\User
* );
*
* $preferences = new Preferences($store->load());
* $preferences->aPreference = 'value';
* $store->save($preferences);
* </code>
*/ */
class IniStore extends PreferencesStore class IniStore extends PreferencesStore
{ {
@ -54,93 +23,135 @@ class IniStore extends PreferencesStore
* *
* @var string * @var string
*/ */
private $preferencesFile; protected $preferencesFile;
/** /**
* Stored preferences * Stored preferences
* *
* @var array * @var array
*/ */
private $preferences; protected $preferences = array();
/** /**
* Writer which stores the preferences * Writer which stores the preferences
* *
* @var PreservingIniWriter * @var PreservingIniWriter
*/ */
private $writer; protected $writer;
/** /**
* Initialize the store * Initialize the store
*
* @throws NotReadableError When the preferences INI file of the given user is not readable
*/ */
public function init() protected function init()
{ {
$this->preferencesFile = sprintf( $this->preferencesFile = sprintf(
'%s/%s.ini', '%s/%s.ini',
IcingaConfig::resolvePath($this->getStoreConfig()->configPath), IcingaConfig::resolvePath($this->getStoreConfig()->configPath),
$this->getUser()->getUsername() $this->getUser()->getUsername()
); );
if (file_exists($this->preferencesFile)) {
if (!is_readable($this->preferencesFile)) {
throw new NotReadableError('Preferences INI file ' . $this->preferencesFile . ' for user '
. $this->getUser()->getUsername() . ' is not readable');
} else {
$this->preferences = parse_ini_file($this->preferencesFile);
}
}
} }
/** /**
* Load preferences from source * Load preferences from source
* *
* @return array * @return array
*
* @throws NotReadableError When the INI file of the user exists and is not readable
*/ */
public function load() public function load()
{ {
return $this->preferences !== null ? $this->preferences : array(); if (file_exists($this->preferencesFile)) {
if (!is_readable($this->preferencesFile)) {
throw new NotReadableError(
'Preferences INI file ' . $this->preferencesFile . ' for user '
. $this->getUser()->getUsername() . ' is not readable'
);
} else {
$this->preferences = parse_ini_file($this->preferencesFile);
}
}
return $this->preferences;
} }
/** /**
* Create, update and delete the given preferences * Save the given preferences
* *
* @param array $newPreferences Key-value array of preferences to create * @param Preferences $preferences The preferences to save
* @param array $updatedPreferences Key-value array of preferences to update
* @param array $deletedPreferences An array of preference names to delete
*
* @throws NotWritableError When either the path to the preferences INI files is not writable or the
* preferences INI file for the given user is not writable
*/ */
public function cud($newPreferences, $updatedPreferences, $deletedPreferences) public function save(Preferences $preferences)
{
$preferences = $preferences->toArray();
$this->update(
array_merge(
array_diff_key($preferences, $this->preferences),
array_diff_assoc($preferences, $this->preferences)
)
);
$this->delete(array_keys(array_diff_key($this->preferences, $preferences)));
$this->write();
}
/**
* Write the preferences
*
* @throws NotWritableError In case the INI file cannot be written
*/
public function write()
{ {
if ($this->preferences === null) {
// Preferences INI file does not yet exist
if (!is_writable($this->getStoreConfig()->configPath)) {
throw new NotWritableError('Path to the preferences INI files ' . $this->getStoreConfig()->configPath
. ' is not writable');
}
File::create($this->preferencesFile);
$this->preferences = array();
}
if (!is_writable($this->preferencesFile)) {
throw new NotWritableError('Preferences INI file ' . $this->preferencesFile . ' for user '
. $this->getUser()->getUsername() . ' is not writable');
}
foreach ($newPreferences as $name => $value) {
$this->preferences[$name] = $value;
}
foreach ($updatedPreferences as $name => $value) {
$this->preferences[$name] = $value;
}
foreach ($deletedPreferences as $name) {
unset($this->preferences[$name]);
}
if ($this->writer === null) { if ($this->writer === null) {
if (!file_exists($this->preferencesFile)) {
if (!is_writable($this->getStoreConfig()->configPath)) {
throw new NotWritableError(
sprintf(
'Path to the preferences INI files %s is not writable',
$this->getStoreConfig()->configPath
)
);
}
File::create($this->preferencesFile);
}
if (!is_writable($this->preferencesFile)) {
throw new NotWritableError(
'Preferences INI file ' . $this->preferencesFile . ' for user '
. $this->getUser()->getUsername() . ' is not writable'
);
}
$this->writer = new PreservingIniWriter( $this->writer = new PreservingIniWriter(
array('config' => new Zend_Config($this->preferences), 'filename' => $this->preferencesFile) array(
'config' => new Zend_Config($this->preferences),
'filename' => $this->preferencesFile
)
); );
} }
$this->writer->write(); $this->writer->write();
} }
/**
* Add or update the given preferences
*
* @param array $preferences The preferences to set
*/
protected function update(array $preferences)
{
foreach ($preferences as $key => $value) {
$this->preferences[$key] = $value;
}
}
/**
* Delete the given preferences by name
*
* @param array $preferenceKeys The preference names to delete
*/
protected function delete(array $preferenceKeys)
{
foreach ($preferenceKeys as $key) {
unset($this->preferences[$key]);
}
}
} }

View File

@ -32,7 +32,6 @@ namespace Icinga\Web\Controller;
use Icinga\Application\Config as IcingaConfig; use Icinga\Application\Config as IcingaConfig;
use Icinga\Exception\ConfigurationError; use Icinga\Exception\ConfigurationError;
use Icinga\Web\Session; use Icinga\Web\Session;
use Icinga\User\Preferences;
use Icinga\User\Preferences\PreferencesStore; use Icinga\User\Preferences\PreferencesStore;
/** /**
@ -71,21 +70,24 @@ class BasePreferenceController extends ActionController
protected function savePreferences(array $preferences) protected function savePreferences(array $preferences)
{ {
$currentPreferences = $this->_request->getUser()->getPreferences(); $session = Session::getSession();
$currentPreferences = $session->user->getPreferences();
foreach ($preferences as $key => $value) { foreach ($preferences as $key => $value) {
if ($value === null) { if ($value === null) {
unset($currentPreferences->{$key}); $currentPreferences->remove($key);
} else { } else {
$currentPreferences->{$key} = $value; $currentPreferences->{$key} = $value;
} }
} }
Session::getSession()->write(); $session->write();
if (($preferencesConfig = IcingaConfig::app()->preferences) === null) { if (($preferencesConfig = IcingaConfig::app()->preferences) === null) {
throw new ConfigurationError( throw new ConfigurationError(
'Cannot save preferences changes since you\'ve not configured a preferences backend' 'Cannot save preferences changes since you\'ve not configured a preferences backend'
); );
} }
$store = PreferencesStore::create($preferencesConfig, $this->_request->getUser()); $store = PreferencesStore::create($preferencesConfig, $session->user);
$store->load(); // Necessary for patching existing preferences
$store->save($currentPreferences); $store->save($currentPreferences);
} }
} }