Refactoring Core class structures ...

This commit is contained in:
Philipp 2021-10-26 21:44:29 +02:00
parent 57b4c008cb
commit b216317477
No known key found for this signature in database
GPG key ID: 24A7501396EB5432
130 changed files with 1625 additions and 1397 deletions

View file

@ -188,7 +188,7 @@ namespace Friendica\Addon\samplestorage;
use Friendica\Model\Storage\IWritableStorage; use Friendica\Model\Storage\IWritableStorage;
use Friendica\Core\Config\IConfig; use Friendica\Core\Config\Capability\IManageConfigValues;
use Friendica\Core\L10n; use Friendica\Core\L10n;
class SampleStorageBackend implements IWritableStorage class SampleStorageBackend implements IWritableStorage
@ -249,12 +249,12 @@ namespace Friendica\Addon\samplestorage;
use Friendica\Model\Storage\IStorageConfiguration; use Friendica\Model\Storage\IStorageConfiguration;
use Friendica\Core\Config\IConfig; use Friendica\Core\Config\Capability\IManageConfigValues;
use Friendica\Core\L10n; use Friendica\Core\L10n;
class SampleStorageBackendConfig implements IStorageConfiguration class SampleStorageBackendConfig implements IStorageConfiguration
{ {
/** @var IConfig */ /** @var \Friendica\Core\Config\Capability\IManageConfigValues */
private $config; private $config;
/** @var L10n */ /** @var L10n */
private $l10n; private $l10n;
@ -265,7 +265,7 @@ class SampleStorageBackendConfig implements IStorageConfiguration
* You can add here every dynamic class as dependency you like and add them to a private field * You can add here every dynamic class as dependency you like and add them to a private field
* Friendica automatically creates these classes and passes them as argument to the constructor * Friendica automatically creates these classes and passes them as argument to the constructor
*/ */
public function __construct(IConfig $config, L10n $l10n) public function __construct(IManageConfigValues $config, L10n $l10n)
{ {
$this->config = $config; $this->config = $config;
$this->l10n = $l10n; $this->l10n = $l10n;

View file

@ -43,7 +43,7 @@ $a = \Friendica\DI::app();
$a->runFrontend( $a->runFrontend(
$dice->create(\Friendica\App\Module::class), $dice->create(\Friendica\App\Module::class),
$dice->create(\Friendica\App\Router::class), $dice->create(\Friendica\App\Router::class),
$dice->create(\Friendica\Core\PConfig\IPConfig::class), $dice->create(\Friendica\Core\PConfig\Capability\IManagePersonalConfigValues::class),
$dice->create(\Friendica\Security\Authentication::class), $dice->create(\Friendica\Security\Authentication::class),
$dice->create(\Friendica\App\Page::class), $dice->create(\Friendica\App\Page::class),
$start_time $start_time

View file

@ -25,12 +25,12 @@ use Exception;
use Friendica\App\Arguments; use Friendica\App\Arguments;
use Friendica\App\BaseURL; use Friendica\App\BaseURL;
use Friendica\App\Module; use Friendica\App\Module;
use Friendica\Core\Config\Factory\ConfigFactory; use Friendica\Core\Config\Factory\Config;
use Friendica\Module\Maintenance; use Friendica\Module\Maintenance;
use Friendica\Security\Authentication; use Friendica\Security\Authentication;
use Friendica\Core\Config\Cache\Cache; use Friendica\Core\Config\ValueObject\Cache;
use Friendica\Core\Config\IConfig; use Friendica\Core\Config\Capability\IManageConfigValues;
use Friendica\Core\PConfig\IPConfig; use Friendica\Core\PConfig\Capability\IManagePersonalConfigValues;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Core\Theme; use Friendica\Core\Theme;
@ -88,7 +88,7 @@ class App
private $currentMobileTheme; private $currentMobileTheme;
/** /**
* @var IConfig The config * @var IManageConfigValues The config
*/ */
private $config; private $config;
@ -123,7 +123,7 @@ class App
private $process; private $process;
/** /**
* @var IPConfig * @var IManagePersonalConfigValues
*/ */
private $pConfig; private $pConfig;
@ -306,7 +306,7 @@ class App
/** /**
* @param Database $database The Friendica Database * @param Database $database The Friendica Database
* @param IConfig $config The Configuration * @param IManageConfigValues $config The Configuration
* @param App\Mode $mode The mode of this Friendica app * @param App\Mode $mode The mode of this Friendica app
* @param BaseURL $baseURL The full base URL of this Friendica app * @param BaseURL $baseURL The full base URL of this Friendica app
* @param LoggerInterface $logger The current app logger * @param LoggerInterface $logger The current app logger
@ -314,9 +314,9 @@ class App
* @param L10n $l10n The translator instance * @param L10n $l10n The translator instance
* @param App\Arguments $args The Friendica Arguments of the call * @param App\Arguments $args The Friendica Arguments of the call
* @param Core\Process $process The process methods * @param Core\Process $process The process methods
* @param IPConfig $pConfig Personal configuration * @param \Friendica\Core\PConfig\Capability\IManagePersonalConfigValues $pConfig Personal configuration
*/ */
public function __construct(Database $database, IConfig $config, App\Mode $mode, BaseURL $baseURL, LoggerInterface $logger, Profiler $profiler, L10n $l10n, Arguments $args, Core\Process $process, IPConfig $pConfig) public function __construct(Database $database, IManageConfigValues $config, App\Mode $mode, BaseURL $baseURL, LoggerInterface $logger, Profiler $profiler, L10n $l10n, Arguments $args, Core\Process $process, IManagePersonalConfigValues $pConfig)
{ {
$this->database = $database; $this->database = $database;
$this->config = $config; $this->config = $config;
@ -357,7 +357,7 @@ class App
$this->profiler->update($this->config); $this->profiler->update($this->config);
Core\Hook::loadHooks(); Core\Hook::loadHooks();
$loader = (new ConfigFactory())->createConfigFileLoader($this->getBasePath(), $_SERVER); $loader = (new Config())->createConfigFileLoader($this->getBasePath(), $_SERVER);
Core\Hook::callAll('load_config', $loader); Core\Hook::callAll('load_config', $loader);
} }
@ -554,14 +554,14 @@ class App
* *
* @param App\Module $module The determined module * @param App\Module $module The determined module
* @param App\Router $router * @param App\Router $router
* @param IPConfig $pconfig * @param IManagePersonalConfigValues $pconfig
* @param Authentication $auth The Authentication backend of the node * @param Authentication $auth The Authentication backend of the node
* @param App\Page $page The Friendica page printing container * @param App\Page $page The Friendica page printing container
* *
* @throws HTTPException\InternalServerErrorException * @throws HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
public function runFrontend(App\Module $module, App\Router $router, IPConfig $pconfig, Authentication $auth, App\Page $page, float $start_time) public function runFrontend(App\Module $module, App\Router $router, IManagePersonalConfigValues $pconfig, Authentication $auth, App\Page $page, float $start_time)
{ {
$this->profiler->set($start_time, 'start'); $this->profiler->set($start_time, 'start');
$this->profiler->set(microtime(true), 'classinit'); $this->profiler->set(microtime(true), 'classinit');

View file

@ -21,7 +21,7 @@
namespace Friendica\App; namespace Friendica\App;
use Friendica\Core\Config\IConfig; use Friendica\Core\Config\Capability\IManageConfigValues;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Util\Network; use Friendica\Util\Network;
use Friendica\Util\Strings; use Friendica\Util\Strings;
@ -56,7 +56,7 @@ class BaseURL
/** /**
* The Friendica Config * The Friendica Config
* *
* @var IConfig * @var IManageConfigValues
*/ */
private $config; private $config;
@ -272,10 +272,10 @@ class BaseURL
} }
/** /**
* @param IConfig $config The Friendica IConfiguration * @param \Friendica\Core\Config\Capability\IManageConfigValues $config The Friendica IConfiguration
* @param array $server The $_SERVER array * @param array $server The $_SERVER array
*/ */
public function __construct(IConfig $config, array $server) public function __construct(IManageConfigValues $config, array $server)
{ {
$this->config = $config; $this->config = $config;
$this->server = $server; $this->server = $server;

View file

@ -22,7 +22,7 @@
namespace Friendica\App; namespace Friendica\App;
use Detection\MobileDetect; use Detection\MobileDetect;
use Friendica\Core\Config\Cache\Cache; use Friendica\Core\Config\ValueObject\Cache;
use Friendica\Database\Database; use Friendica\Database\Database;
use Friendica\Util\BasePath; use Friendica\Util\BasePath;

View file

@ -170,13 +170,13 @@ class Module
* *
* @param Arguments $args The Friendica execution arguments * @param Arguments $args The Friendica execution arguments
* @param Router $router The Friendica routing instance * @param Router $router The Friendica routing instance
* @param Core\Config\IConfig $config The Friendica Configuration * @param \Friendica\Core\Config\Capability\IManageConfigValues $config The Friendica Configuration
* *
* @return Module The determined module of this call * @return Module The determined module of this call
* *
* @throws \Exception * @throws \Exception
*/ */
public function determineClass(Arguments $args, Router $router, Core\Config\IConfig $config) public function determineClass(Arguments $args, Router $router, Core\Config\Capability\IManageConfigValues $config)
{ {
$printNotAllowedAddon = false; $printNotAllowedAddon = false;

View file

@ -26,8 +26,8 @@ use DOMDocument;
use DOMXPath; use DOMXPath;
use Friendica\App; use Friendica\App;
use Friendica\Content\Nav; use Friendica\Content\Nav;
use Friendica\Core\Config\IConfig; use Friendica\Core\Config\Capability\IManageConfigValues;
use Friendica\Core\PConfig\IPConfig; use Friendica\Core\PConfig\Capability\IManagePersonalConfigValues;
use Friendica\Core\Hook; use Friendica\Core\Hook;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Renderer; use Friendica\Core\Renderer;
@ -193,12 +193,12 @@ class Page implements ArrayAccess
* @param App $app The Friendica App instance * @param App $app The Friendica App instance
* @param Module $module The loaded Friendica module * @param Module $module The loaded Friendica module
* @param L10n $l10n The l10n language instance * @param L10n $l10n The l10n language instance
* @param IConfig $config The Friendica configuration * @param \Friendica\Core\Config\Capability\IManageConfigValues $config The Friendica configuration
* @param IPConfig $pConfig The Friendica personal configuration (for user) * @param \Friendica\Core\PConfig\Capability\IManagePersonalConfigValues $pConfig The Friendica personal configuration (for user)
* *
* @throws HTTPException\InternalServerErrorException * @throws HTTPException\InternalServerErrorException
*/ */
private function initHead(App $app, Module $module, L10n $l10n, IConfig $config, IPConfig $pConfig) private function initHead(App $app, Module $module, L10n $l10n, IManageConfigValues $config, IManagePersonalConfigValues $pConfig)
{ {
$interval = ((local_user()) ? $pConfig->get(local_user(), 'system', 'update_interval') : 40000); $interval = ((local_user()) ? $pConfig->get(local_user(), 'system', 'update_interval') : 40000);
@ -372,12 +372,12 @@ class Page implements ArrayAccess
* @param Mode $mode The current node mode * @param Mode $mode The current node mode
* @param Module $module The loaded Friendica module * @param Module $module The loaded Friendica module
* @param L10n $l10n The l10n language class * @param L10n $l10n The l10n language class
* @param IConfig $config The Configuration of this node * @param IManageConfigValues $config The Configuration of this node
* @param IPConfig $pconfig The personal/user configuration * @param IManagePersonalConfigValues $pconfig The personal/user configuration
* *
* @throws HTTPException\InternalServerErrorException * @throws HTTPException\InternalServerErrorException
*/ */
public function run(App $app, BaseURL $baseURL, Mode $mode, Module $module, L10n $l10n, Profiler $profiler, IConfig $config, IPConfig $pconfig) public function run(App $app, BaseURL $baseURL, Mode $mode, Module $module, L10n $l10n, Profiler $profiler, IManageConfigValues $config, IManagePersonalConfigValues $pconfig)
{ {
$moduleName = $module->getName(); $moduleName = $module->getName();

View file

@ -27,10 +27,10 @@ use FastRoute\Dispatcher;
use FastRoute\RouteCollector; use FastRoute\RouteCollector;
use FastRoute\RouteParser\Std; use FastRoute\RouteParser\Std;
use Friendica\Core\Cache\Enum\Duration; use Friendica\Core\Cache\Enum\Duration;
use Friendica\Core\Cache\ICache; use Friendica\Core\Cache\Capability\ICanCache;
use Friendica\Core\Hook; use Friendica\Core\Hook;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Lock\ILock; use Friendica\Core\Lock\Capability\ICanLock;
use Friendica\Network\HTTPException; use Friendica\Network\HTTPException;
/** /**
@ -77,10 +77,10 @@ class Router
/** @var L10n */ /** @var L10n */
private $l10n; private $l10n;
/** @var ICache */ /** @var ICanCache */
private $cache; private $cache;
/** @var ILock */ /** @var ICanLock */
private $lock; private $lock;
/** @var string */ /** @var string */
@ -90,10 +90,10 @@ class Router
* @param array $server The $_SERVER variable * @param array $server The $_SERVER variable
* @param string $baseRoutesFilepath The path to a base routes file to leverage cache, can be empty * @param string $baseRoutesFilepath The path to a base routes file to leverage cache, can be empty
* @param L10n $l10n * @param L10n $l10n
* @param ICache $cache * @param ICanCache $cache
* @param RouteCollector|null $routeCollector * @param RouteCollector|null $routeCollector
*/ */
public function __construct(array $server, string $baseRoutesFilepath, L10n $l10n, ICache $cache, ILock $lock, RouteCollector $routeCollector = null) public function __construct(array $server, string $baseRoutesFilepath, L10n $l10n, ICanCache $cache, ICanLock $lock, RouteCollector $routeCollector = null)
{ {
$this->baseRoutesFilepath = $baseRoutesFilepath; $this->baseRoutesFilepath = $baseRoutesFilepath;
$this->l10n = $l10n; $this->l10n = $l10n;

View file

@ -24,8 +24,8 @@ namespace Friendica\Console;
use Asika\SimpleConsole\Console; use Asika\SimpleConsole\Console;
use Friendica\App; use Friendica\App;
use Friendica\App\BaseURL; use Friendica\App\BaseURL;
use Friendica\Core\Config\IConfig; use Friendica\Core\Config\Capability\IManageConfigValues;
use Friendica\Core\Config\Cache\Cache; use Friendica\Core\Config\ValueObject\Cache;
use Friendica\Core\Installer; use Friendica\Core\Installer;
use Friendica\Core\Theme; use Friendica\Core\Theme;
use Friendica\Database\Database; use Friendica\Database\Database;
@ -36,9 +36,9 @@ class AutomaticInstallation extends Console
{ {
/** @var App\Mode */ /** @var App\Mode */
private $appMode; private $appMode;
/** @var \Friendica\Core\Config\Cache\Cache */ /** @var \Friendica\Core\Config\ValueObject\Cache */
private $configCache; private $configCache;
/** @var IConfig */ /** @var IManageConfigValues */
private $config; private $config;
/** @var Database */ /** @var Database */
private $dba; private $dba;
@ -98,7 +98,7 @@ Examples
HELP; HELP;
} }
public function __construct(App\Mode $appMode, Cache $configCache, IConfig $config, Database $dba, array $argv = null) public function __construct(App\Mode $appMode, Cache $configCache, IManageConfigValues $config, Database $dba, array $argv = null)
{ {
parent::__construct($argv); parent::__construct($argv);
@ -253,7 +253,7 @@ HELP;
/** /**
* @param Installer $installer The Installer instance * @param Installer $installer The Installer instance
* @param Cache $configCache The config cache * @param \Friendica\Core\Config\ValueObject\Cache $configCache The config cache
* *
* @return bool true if checks were successfully, otherwise false * @return bool true if checks were successfully, otherwise false
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException

View file

@ -24,7 +24,7 @@ namespace Friendica\Console;
use Asika\SimpleConsole\CommandArgsException; use Asika\SimpleConsole\CommandArgsException;
use Friendica\App; use Friendica\App;
use Friendica\Core\Cache\Enum\Duration; use Friendica\Core\Cache\Enum\Duration;
use Friendica\Core\Cache\ICache; use Friendica\Core\Cache\Capability\ICanCache;
use RuntimeException; use RuntimeException;
/** /**
@ -44,7 +44,7 @@ class Cache extends \Asika\SimpleConsole\Console
private $appMode; private $appMode;
/** /**
* @var ICache * @var ICanCache
*/ */
private $cache; private $cache;
@ -82,7 +82,7 @@ HELP;
return $help; return $help;
} }
public function __construct(App\Mode $appMode, ICache $cache, array $argv = null) public function __construct(App\Mode $appMode, ICanCache $cache, array $argv = null)
{ {
parent::__construct($argv); parent::__construct($argv);

View file

@ -23,7 +23,7 @@ namespace Friendica\Console;
use Asika\SimpleConsole\CommandArgsException; use Asika\SimpleConsole\CommandArgsException;
use Friendica\App; use Friendica\App;
use Friendica\Core\Config\IConfig; use Friendica\Core\Config\Capability\IManageConfigValues;
use RuntimeException; use RuntimeException;
/** /**
@ -56,7 +56,7 @@ class Config extends \Asika\SimpleConsole\Console
*/ */
private $appMode; private $appMode;
/** /**
* @var IConfig * @var IManageConfigValues
*/ */
private $config; private $config;
@ -94,7 +94,7 @@ HELP;
return $help; return $help;
} }
public function __construct(App\Mode $appMode, IConfig $config, array $argv = null) public function __construct(App\Mode $appMode, IManageConfigValues $config, array $argv = null)
{ {
parent::__construct($argv); parent::__construct($argv);

View file

@ -21,7 +21,7 @@
namespace Friendica\Console; namespace Friendica\Console;
use Friendica\Core\Config\Cache\Cache; use Friendica\Core\Config\ValueObject\Cache;
use Friendica\Core\Update; use Friendica\Core\Update;
use Friendica\Database\Database; use Friendica\Database\Database;
use Friendica\Database\DBStructure; use Friendica\Database\DBStructure;

View file

@ -23,7 +23,7 @@ namespace Friendica\Console;
use Asika\SimpleConsole\CommandArgsException; use Asika\SimpleConsole\CommandArgsException;
use Friendica\App; use Friendica\App;
use Friendica\Core\Lock\ILock; use Friendica\Core\Lock\Capability\ICanLock;
use RuntimeException; use RuntimeException;
/** /**
@ -42,7 +42,7 @@ class Lock extends \Asika\SimpleConsole\Console
private $appMode; private $appMode;
/** /**
* @var ILock * @var \Friendica\Core\Lock\Capability\ICanLock
*/ */
private $lock; private $lock;
@ -76,7 +76,7 @@ HELP;
return $help; return $help;
} }
public function __construct(App\Mode $appMode, ILock $lock, array $argv = null) public function __construct(App\Mode $appMode, ICanLock $lock, array $argv = null)
{ {
parent::__construct($argv); parent::__construct($argv);

View file

@ -22,7 +22,7 @@
namespace Friendica\Console; namespace Friendica\Console;
use Friendica\App; use Friendica\App;
use Friendica\Core\Config\IConfig; use Friendica\Core\Config\Capability\IManageConfigValues;
/** /**
* Sets maintenance mode for this node * Sets maintenance mode for this node
@ -36,7 +36,7 @@ class Maintenance extends \Asika\SimpleConsole\Console
*/ */
private $appMode; private $appMode;
/** /**
* @var IConfig * @var IManageConfigValues
*/ */
private $config; private $config;
@ -69,7 +69,7 @@ HELP;
return $help; return $help;
} }
public function __construct(App\Mode $appMode, IConfig $config, $argv = null) public function __construct(App\Mode $appMode, IManageConfigValues $config, $argv = null)
{ {
parent::__construct($argv); parent::__construct($argv);

View file

@ -22,7 +22,7 @@
namespace Friendica\Console; namespace Friendica\Console;
use Friendica\App; use Friendica\App;
use Friendica\Core\Config\IConfig; use Friendica\Core\Config\Capability\IManageConfigValues;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Update; use Friendica\Core\Update;
@ -38,7 +38,7 @@ class PostUpdate extends \Asika\SimpleConsole\Console
*/ */
private $appMode; private $appMode;
/** /**
* @var IConfig * @var \Friendica\Core\Config\Capability\IManageConfigValues
*/ */
private $config; private $config;
/** /**
@ -60,7 +60,7 @@ HELP;
return $help; return $help;
} }
public function __construct(App\Mode $appMode, IConfig $config, L10n $l10n, array $argv = null) public function __construct(App\Mode $appMode, IManageConfigValues $config, L10n $l10n, array $argv = null)
{ {
parent::__construct($argv); parent::__construct($argv);

View file

@ -24,7 +24,7 @@ namespace Friendica\Console;
use Asika\SimpleConsole\CommandArgsException; use Asika\SimpleConsole\CommandArgsException;
use Asika\SimpleConsole\Console; use Asika\SimpleConsole\Console;
use Console_Table; use Console_Table;
use Friendica\Core\Config\IConfig; use Friendica\Core\Config\Capability\IManageConfigValues;
/** /**
* Manage blocked servers * Manage blocked servers
@ -39,7 +39,7 @@ class ServerBlock extends Console
protected $helpOptions = ['h', 'help', '?']; protected $helpOptions = ['h', 'help', '?'];
/** /**
* @var IConfig * @var IManageConfigValues
*/ */
private $config; private $config;
@ -72,7 +72,7 @@ HELP;
return $help; return $help;
} }
public function __construct(IConfig $config, $argv = null) public function __construct(IManageConfigValues $config, $argv = null)
{ {
parent::__construct($argv); parent::__construct($argv);
@ -105,9 +105,9 @@ HELP;
* Exports the list of blocked domains including the reason for the * Exports the list of blocked domains including the reason for the
* block to a CSV file. * block to a CSV file.
* *
* @param IConfig $config * @param IManageConfigValues $config
*/ */
private function exportBlockedServers(IConfig $config) private function exportBlockedServers(IManageConfigValues $config)
{ {
$filename = $this->getArgument(1); $filename = $this->getArgument(1);
$blocklist = $config->get('system', 'blocklist', []); $blocklist = $config->get('system', 'blocklist', []);
@ -123,9 +123,9 @@ HELP;
* Imports a list of domains and a reason for the block from a CSV * Imports a list of domains and a reason for the block from a CSV
* file, e.g. created with the export function. * file, e.g. created with the export function.
* *
* @param IConfig $config * @param IManageConfigValues $config
*/ */
private function importBlockedServers(IConfig $config) private function importBlockedServers(IManageConfigValues $config)
{ {
$filename = $this->getArgument(1); $filename = $this->getArgument(1);
$currBlockList = $config->get('system', 'blocklist', []); $currBlockList = $config->get('system', 'blocklist', []);
@ -167,9 +167,9 @@ HELP;
/** /**
* Prints the whole list of blocked domains including the reason * Prints the whole list of blocked domains including the reason
* *
* @param IConfig $config * @param IManageConfigValues $config
*/ */
private function printBlockedServers(IConfig $config) private function printBlockedServers(IManageConfigValues $config)
{ {
$table = new Console_Table(); $table = new Console_Table();
$table->setHeaders(['Domain', 'Reason']); $table->setHeaders(['Domain', 'Reason']);
@ -183,11 +183,11 @@ HELP;
/** /**
* Adds a server to the blocked list * Adds a server to the blocked list
* *
* @param IConfig $config * @param IManageConfigValues $config
* *
* @return int The return code (0 = success, 1 = failed) * @return int The return code (0 = success, 1 = failed)
*/ */
private function addBlockedServer(IConfig $config) private function addBlockedServer(IManageConfigValues $config)
{ {
if (count($this->args) < 2 || count($this->args) > 3) { if (count($this->args) < 2 || count($this->args) > 3) {
throw new CommandArgsException('Add needs a domain and optional a reason.'); throw new CommandArgsException('Add needs a domain and optional a reason.');
@ -235,11 +235,11 @@ HELP;
/** /**
* Removes a server from the blocked list * Removes a server from the blocked list
* *
* @param IConfig $config * @param IManageConfigValues $config
* *
* @return int The return code (0 = success, 1 = failed) * @return int The return code (0 = success, 1 = failed)
*/ */
private function removeBlockedServer(IConfig $config) private function removeBlockedServer(IManageConfigValues $config)
{ {
if (count($this->args) !== 2) { if (count($this->args) !== 2) {
throw new CommandArgsException('Remove needs a second parameter.'); throw new CommandArgsException('Remove needs a second parameter.');

View file

@ -21,7 +21,7 @@
namespace Friendica\Console; namespace Friendica\Console;
use Friendica\Core\Config\IConfig; use Friendica\Core\Config\Capability\IManageConfigValues;
/** /**
* Tired of chasing typos and finding them after a commit. * Tired of chasing typos and finding them after a commit.
@ -32,7 +32,7 @@ class Typo extends \Asika\SimpleConsole\Console
protected $helpOptions = ['h', 'help', '?']; protected $helpOptions = ['h', 'help', '?'];
/** /**
* @var IConfig * @var IManageConfigValues
*/ */
private $config; private $config;
@ -53,7 +53,7 @@ HELP;
return $help; return $help;
} }
public function __construct(IConfig $config, array $argv = null) public function __construct(IManageConfigValues $config, array $argv = null)
{ {
parent::__construct($argv); parent::__construct($argv);

View file

@ -25,7 +25,7 @@ use Console_Table;
use Friendica\App; use Friendica\App;
use Friendica\Content\Pager; use Friendica\Content\Pager;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\PConfig\IPConfig; use Friendica\Core\PConfig\Capability\IManagePersonalConfigValues;
use Friendica\Model\Register; use Friendica\Model\Register;
use Friendica\Model\User as UserModel; use Friendica\Model\User as UserModel;
use Friendica\Util\Temporal; use Friendica\Util\Temporal;
@ -48,7 +48,7 @@ class User extends \Asika\SimpleConsole\Console
*/ */
private $l10n; private $l10n;
/** /**
* @var IPConfig * @var IManagePersonalConfigValues
*/ */
private $pConfig; private $pConfig;
@ -88,7 +88,7 @@ HELP;
return $help; return $help;
} }
public function __construct(App\Mode $appMode, L10n $l10n, IPConfig $pConfig, array $argv = null) public function __construct(App\Mode $appMode, L10n $l10n, IManagePersonalConfigValues $pConfig, array $argv = null)
{ {
parent::__construct($argv); parent::__construct($argv);

View file

@ -26,10 +26,10 @@ use Friendica\App\Arguments;
use Friendica\App\BaseURL; use Friendica\App\BaseURL;
use Friendica\BaseModule; use Friendica\BaseModule;
use Friendica\Core\ACL; use Friendica\Core\ACL;
use Friendica\Core\Config\IConfig; use Friendica\Core\Config\Capability\IManageConfigValues;
use Friendica\Core\Hook; use Friendica\Core\Hook;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\PConfig\IPConfig; use Friendica\Core\PConfig\Capability\IManagePersonalConfigValues;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Core\Renderer; use Friendica\Core\Renderer;
use Friendica\Core\Session; use Friendica\Core\Session;
@ -66,11 +66,11 @@ class Conversation
private $item; private $item;
/** @var App\Arguments */ /** @var App\Arguments */
private $args; private $args;
/** @var IPConfig */ /** @var IManagePersonalConfigValues */
private $pConfig; private $pConfig;
/** @var BaseURL */ /** @var BaseURL */
private $baseURL; private $baseURL;
/** @var IConfig */ /** @var IManageConfigValues */
private $config; private $config;
/** @var App */ /** @var App */
private $app; private $app;
@ -79,7 +79,7 @@ class Conversation
/** @var App\Mode */ /** @var App\Mode */
private $mode; private $mode;
public function __construct(LoggerInterface $logger, Profiler $profiler, Activity $activity, L10n $l10n, Item $item, Arguments $args, BaseURL $baseURL, IConfig $config, IPConfig $pConfig, App\Page $page, App\Mode $mode, App $app) public function __construct(LoggerInterface $logger, Profiler $profiler, Activity $activity, L10n $l10n, Item $item, Arguments $args, BaseURL $baseURL, IManageConfigValues $config, IManagePersonalConfigValues $pConfig, App\Page $page, App\Mode $mode, App $app)
{ {
$this->activity = $activity; $this->activity = $activity;
$this->item = $item; $this->item = $item;
@ -629,7 +629,7 @@ class Conversation
$body_html = ItemModel::prepareBody($item, true, $preview); $body_html = ItemModel::prepareBody($item, true, $preview);
list($categories, $folders) = $this->item->determineCategoriesTerms($item, local_user()); [$categories, $folders] = $this->item->determineCategoriesTerms($item, local_user());
if (!empty($item['content-warning']) && $this->pConfig->get(local_user(), 'system', 'disable_cw', false)) { if (!empty($item['content-warning']) && $this->pConfig->get(local_user(), 'system', 'disable_cw', false)) {
$title = ucfirst($item['content-warning']); $title = ucfirst($item['content-warning']);

View file

@ -19,23 +19,24 @@
* *
*/ */
namespace Friendica\Core\Cache; namespace Friendica\Core\Cache\Capability;
use Friendica\Core\Cache\Enum\Duration; use Friendica\Core\Cache\Enum\Duration;
use Friendica\Core\Cache\Exception\CachePersistenceException;
/** /**
* Cache Interface * Interface for caches
*/ */
interface ICache interface ICanCache
{ {
/** /**
* Lists all cache keys * Lists all cache keys
* *
* @param string prefix optional a prefix to search * @param string|null prefix optional a prefix to search
* *
* @return array Empty if it isn't supported by the cache driver * @return array Empty if it isn't supported by the cache driver
*/ */
public function getAllKeys($prefix = null); public function getAllKeys(?string $prefix = null): array;
/** /**
* Fetches cached data according to the key * Fetches cached data according to the key
@ -43,8 +44,10 @@ interface ICache
* @param string $key The key to the cached data * @param string $key The key to the cached data
* *
* @return mixed Cached $value or "null" if not found * @return mixed Cached $value or "null" if not found
*
* @throws CachePersistenceException In case the underlying cache driver has errors during persistence
*/ */
public function get($key); public function get(string $key);
/** /**
* Stores data in the cache identified by the key. The input $value can have multiple formats. * Stores data in the cache identified by the key. The input $value can have multiple formats.
@ -54,8 +57,10 @@ interface ICache
* @param integer $ttl The cache lifespan, must be one of the Cache constants * @param integer $ttl The cache lifespan, must be one of the Cache constants
* *
* @return bool * @return bool
*
* @throws CachePersistenceException In case the underlying cache driver has errors during persistence
*/ */
public function set($key, $value, $ttl = Duration::FIVE_MINUTES); public function set(string $key, $value, int $ttl = Duration::FIVE_MINUTES): bool;
/** /**
* Delete a key from the cache * Delete a key from the cache
@ -63,21 +68,26 @@ interface ICache
* @param string $key The cache key * @param string $key The cache key
* *
* @return bool * @return bool
*
* @throws CachePersistenceException In case the underlying cache driver has errors during persistence
*/ */
public function delete($key); public function delete(string $key): bool;
/** /**
* Remove outdated data from the cache * Remove outdated data from the cache
*
* @param boolean $outdated just remove outdated values * @param boolean $outdated just remove outdated values
* *
* @return bool * @return bool
*
* @throws CachePersistenceException In case the underlying cache driver has errors during persistence
*/ */
public function clear($outdated = true); public function clear(bool $outdated = true): bool;
/** /**
* Returns the name of the current cache * Returns the name of the current cache
* *
* @return string * @return string
*/ */
public function getName(); public function getName(): string;
} }

View file

@ -19,14 +19,15 @@
* *
*/ */
namespace Friendica\Core\Cache; namespace Friendica\Core\Cache\Capability;
use Friendica\Core\Cache\Enum\Duration; use Friendica\Core\Cache\Enum\Duration;
use Friendica\Core\Cache\Exception\CachePersistenceException;
/** /**
* This interface defines methods for Memory-Caches only * This interface defines methods for Memory-Caches only
*/ */
interface IMemoryCache extends ICache interface ICanCacheInMemory extends ICanCache
{ {
/** /**
* Sets a value if it's not already stored * Sets a value if it's not already stored
@ -34,9 +35,12 @@ interface IMemoryCache extends ICache
* @param string $key The cache key * @param string $key The cache key
* @param mixed $value The old value we know from the cache * @param mixed $value The old value we know from the cache
* @param int $ttl The cache lifespan, must be one of the Cache constants * @param int $ttl The cache lifespan, must be one of the Cache constants
*
* @return bool * @return bool
*
* @throws CachePersistenceException In case the underlying cache driver has errors during persistence
*/ */
public function add($key, $value, $ttl = Duration::FIVE_MINUTES); public function add(string $key, $value, int $ttl = Duration::FIVE_MINUTES): bool;
/** /**
* Compares if the old value is set and sets the new value * Compares if the old value is set and sets the new value
@ -47,15 +51,20 @@ interface IMemoryCache extends ICache
* @param int $ttl The cache lifespan, must be one of the Cache constants * @param int $ttl The cache lifespan, must be one of the Cache constants
* *
* @return bool * @return bool
*
* @throws CachePersistenceException In case the underlying cache driver has errors during persistence
*/ */
public function compareSet($key, $oldValue, $newValue, $ttl = Duration::FIVE_MINUTES); public function compareSet(string $key, $oldValue, $newValue, int $ttl = Duration::FIVE_MINUTES): bool;
/** /**
* Compares if the old value is set and removes it * Compares if the old value is set and removes it
* *
* @param string $key The cache key * @param string $key The cache key
* @param mixed $value The old value we know and want to delete * @param mixed $value The old value we know and want to delete
*
* @return bool * @return bool
*
* @throws CachePersistenceException In case the underlying cache driver has errors during persistence
*/ */
public function compareDelete($key, $value); public function compareDelete(string $key, $value): bool;
} }

View file

@ -0,0 +1,13 @@
<?php
namespace Friendica\Core\Cache\Exception;
use Throwable;
class CachePersistenceException extends \RuntimeException
{
public function __construct($message = "", Throwable $previous = null)
{
parent::__construct($message, 500, $previous);
}
}

View file

@ -0,0 +1,13 @@
<?php
namespace Friendica\Core\Cache\Exception;
use Throwable;
class InvalidCacheDriverException extends \RuntimeException
{
public function __construct($message = "", Throwable $previous = null)
{
parent::__construct($message, 500, $previous);
}
}

View file

@ -22,9 +22,12 @@
namespace Friendica\Core\Cache\Factory; namespace Friendica\Core\Cache\Factory;
use Friendica\App\BaseURL; use Friendica\App\BaseURL;
use Friendica\Core\Cache; use Friendica\Core\Cache\Enum;
use Friendica\Core\Cache\ICache; use Friendica\Core\Cache\Capability\ICanCache;
use Friendica\Core\Config\IConfig; use Friendica\Core\Cache\Exception\CachePersistenceException;
use Friendica\Core\Cache\Exception\InvalidCacheDriverException;
use Friendica\Core\Cache\Type;
use Friendica\Core\Config\Capability\IManageConfigValues;
use Friendica\Database\Database; use Friendica\Database\Database;
use Friendica\Util\Profiler; use Friendica\Util\Profiler;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
@ -36,15 +39,15 @@ use Psr\Log\LoggerInterface;
* *
* A basic class to generate a CacheDriver * A basic class to generate a CacheDriver
*/ */
class CacheFactory class Cache
{ {
/** /**
* @var string The default cache if nothing set * @var string The default cache if nothing set
*/ */
const DEFAULT_TYPE = Cache\Enum\Type::DATABASE; const DEFAULT_TYPE = Enum\Type::DATABASE;
/** /**
* @var IConfig The IConfiguration to read parameters out of the config * @var IManageConfigValues The IConfiguration to read parameters out of the config
*/ */
private $config; private $config;
@ -68,7 +71,7 @@ class CacheFactory
*/ */
private $logger; private $logger;
public function __construct(BaseURL $baseURL, IConfig $config, Database $dba, Profiler $profiler, LoggerInterface $logger) public function __construct(BaseURL $baseURL, IManageConfigValues $config, Database $dba, Profiler $profiler, LoggerInterface $logger)
{ {
$this->hostname = $baseURL->getHostname(); $this->hostname = $baseURL->getHostname();
$this->config = $config; $this->config = $config;
@ -80,39 +83,41 @@ class CacheFactory
/** /**
* This method creates a CacheDriver for the given cache driver name * This method creates a CacheDriver for the given cache driver name
* *
* @param string $type The cache type to create (default is per config) * @param string|null $type The cache type to create (default is per config)
* *
* @return ICache The instance of the CacheDriver * @return ICanCache The instance of the CacheDriver
* @throws \Exception The exception if something went wrong during the CacheDriver creation *
* @throws InvalidCacheDriverException In case the underlying cache driver isn't valid or not configured properly
* @throws CachePersistenceException In case the underlying cache has errors during persistence
*/ */
public function create(string $type = null) public function create(string $type = null): ICanCache
{ {
if (empty($type)) { if (empty($type)) {
$type = $this->config->get('system', 'cache_driver', self::DEFAULT_TYPE); $type = $this->config->get('system', 'cache_driver', self::DEFAULT_TYPE);
} }
switch ($type) { switch ($type) {
case Cache\Enum\Type::MEMCACHE: case Enum\Type::MEMCACHE:
$cache = new Cache\Type\MemcacheCache($this->hostname, $this->config); $cache = new Type\MemcacheCache($this->hostname, $this->config);
break; break;
case Cache\Enum\Type::MEMCACHED: case Enum\Type::MEMCACHED:
$cache = new Cache\Type\MemcachedCache($this->hostname, $this->config, $this->logger); $cache = new Type\MemcachedCache($this->hostname, $this->config, $this->logger);
break; break;
case Cache\Enum\Type::REDIS: case Enum\Type::REDIS:
$cache = new Cache\Type\RedisCache($this->hostname, $this->config); $cache = new Type\RedisCache($this->hostname, $this->config);
break; break;
case Cache\Enum\Type::APCU: case Enum\Type::APCU:
$cache = new Cache\Type\APCuCache($this->hostname); $cache = new Type\APCuCache($this->hostname);
break; break;
default: default:
$cache = new Cache\Type\DatabaseCache($this->hostname, $this->dba); $cache = new Type\DatabaseCache($this->hostname, $this->dba);
} }
$profiling = $this->config->get('system', 'profiling', false); $profiling = $this->config->get('system', 'profiling', false);
// In case profiling is enabled, wrap the ProfilerCache around the current cache // In case profiling is enabled, wrap the ProfilerCache around the current cache
if (isset($profiling) && $profiling !== false) { if (isset($profiling) && $profiling !== false) {
return new Cache\Type\ProfilerCache($cache, $this->profiler); return new Type\ProfilerCacheDecorator($cache, $this->profiler);
} else { } else {
return $cache; return $cache;
} }

View file

@ -21,28 +21,28 @@
namespace Friendica\Core\Cache\Type; namespace Friendica\Core\Cache\Type;
use Exception;
use Friendica\Core\Cache\Enum\Duration; use Friendica\Core\Cache\Enum\Duration;
use Friendica\Core\Cache\IMemoryCache; use Friendica\Core\Cache\Capability\ICanCacheInMemory;
use Friendica\Core\Cache\Type\TraitCompareDelete;
use Friendica\Core\Cache\Type\TraitCompareSet;
use Friendica\Core\Cache\Enum\Type; use Friendica\Core\Cache\Enum\Type;
use Friendica\Core\Cache\Exception\InvalidCacheDriverException;
/** /**
* APCu Cache. * APCu Cache.
*/ */
class APCuCache extends BaseCache implements IMemoryCache class APCuCache extends AbstractCache implements ICanCacheInMemory
{ {
use TraitCompareSet; use CompareSetTrait;
use TraitCompareDelete; use CompareDeleteTrait;
/** /**
* @throws Exception * @param string $hostname
*
* @throws InvalidCacheDriverException
*/ */
public function __construct(string $hostname) public function __construct(string $hostname)
{ {
if (!self::isAvailable()) { if (!self::isAvailable()) {
throw new Exception('APCu is not available.'); throw new InvalidCacheDriverException('APCu is not available.');
} }
parent::__construct($hostname); parent::__construct($hostname);
@ -51,9 +51,9 @@ class APCuCache extends BaseCache implements IMemoryCache
/** /**
* (@inheritdoc) * (@inheritdoc)
*/ */
public function getAllKeys($prefix = null) public function getAllKeys(?string $prefix = null): array
{ {
$ns = $this->getCacheKey($prefix); $ns = $this->getCacheKey($prefix ?? '');
$ns = preg_quote($ns, '/'); $ns = preg_quote($ns, '/');
if (class_exists('\APCIterator')) { if (class_exists('\APCIterator')) {
@ -73,12 +73,11 @@ class APCuCache extends BaseCache implements IMemoryCache
/** /**
* (@inheritdoc) * (@inheritdoc)
*/ */
public function get($key) public function get(string $key)
{ {
$return = null; $cacheKey = $this->getCacheKey($key);
$cachekey = $this->getCacheKey($key);
$cached = apcu_fetch($cachekey, $success); $cached = apcu_fetch($cacheKey, $success);
if (!$success) { if (!$success) {
return null; return null;
} }
@ -89,30 +88,30 @@ class APCuCache extends BaseCache implements IMemoryCache
// We also check if the db entry is a serialized // We also check if the db entry is a serialized
// boolean 'false' value (which we want to return). // boolean 'false' value (which we want to return).
if ($cached === serialize(false) || $value !== false) { if ($cached === serialize(false) || $value !== false) {
$return = $value; return $value;
} }
return $return; return null;
} }
/** /**
* (@inheritdoc) * (@inheritdoc)
*/ */
public function set($key, $value, $ttl = Duration::FIVE_MINUTES) public function set(string $key, $value, int $ttl = Duration::FIVE_MINUTES): bool
{ {
$cachekey = $this->getCacheKey($key); $cacheKey = $this->getCacheKey($key);
$cached = serialize($value); $cached = serialize($value);
if ($ttl > 0) { if ($ttl > 0) {
return apcu_store( return apcu_store(
$cachekey, $cacheKey,
$cached, $cached,
$ttl $ttl
); );
} else { } else {
return apcu_store( return apcu_store(
$cachekey, $cacheKey,
$cached $cached
); );
} }
@ -121,16 +120,16 @@ class APCuCache extends BaseCache implements IMemoryCache
/** /**
* (@inheritdoc) * (@inheritdoc)
*/ */
public function delete($key) public function delete(string $key): bool
{ {
$cachekey = $this->getCacheKey($key); $cacheKey = $this->getCacheKey($key);
return apcu_delete($cachekey); return apcu_delete($cacheKey);
} }
/** /**
* (@inheritdoc) * (@inheritdoc)
*/ */
public function clear($outdated = true) public function clear(bool $outdated = true): bool
{ {
if ($outdated) { if ($outdated) {
return true; return true;
@ -151,15 +150,15 @@ class APCuCache extends BaseCache implements IMemoryCache
/** /**
* (@inheritdoc) * (@inheritdoc)
*/ */
public function add($key, $value, $ttl = Duration::FIVE_MINUTES) public function add(string $key, $value, int $ttl = Duration::FIVE_MINUTES): bool
{ {
$cachekey = $this->getCacheKey($key); $cacheKey = $this->getCacheKey($key);
$cached = serialize($value); $cached = serialize($value);
return apcu_add($cachekey, $cached); return apcu_add($cacheKey, $cached);
} }
public static function isAvailable() public static function isAvailable(): bool
{ {
if (!extension_loaded('apcu')) { if (!extension_loaded('apcu')) {
return false; return false;
@ -178,7 +177,7 @@ class APCuCache extends BaseCache implements IMemoryCache
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public function getName() public function getName(): string
{ {
return Type::APCU; return Type::APCU;
} }

View file

@ -21,12 +21,12 @@
namespace Friendica\Core\Cache\Type; namespace Friendica\Core\Cache\Type;
use Friendica\Core\Cache\ICache; use Friendica\Core\Cache\Capability\ICanCache;
/** /**
* Abstract class for common used functions * Abstract class for common used functions
*/ */
abstract class BaseCache implements ICache abstract class AbstractCache implements ICanCache
{ {
/** /**
* @var string The hostname * @var string The hostname
@ -42,9 +42,8 @@ abstract class BaseCache implements ICache
* Returns the prefix (to avoid namespace conflicts) * Returns the prefix (to avoid namespace conflicts)
* *
* @return string * @return string
* @throws \Exception
*/ */
protected function getPrefix() protected function getPrefix(): string
{ {
// We fetch with the hostname as key to avoid problems with other applications // We fetch with the hostname as key to avoid problems with other applications
return $this->hostName; return $this->hostName;
@ -52,19 +51,20 @@ abstract class BaseCache implements ICache
/** /**
* @param string $key The original key * @param string $key The original key
*
* @return string The cache key used for the cache * @return string The cache key used for the cache
* @throws \Exception
*/ */
protected function getCacheKey($key) protected function getCacheKey(string $key): string
{ {
return $this->getPrefix() . ":" . $key; return $this->getPrefix() . ":" . $key;
} }
/** /**
* @param array $keys A list of cached keys * @param string[] $keys A list of cached keys
* @return array A list of original keys *
* @return string[] A list of original keys
*/ */
protected function getOriginalKeys($keys) protected function getOriginalKeys(array $keys): array
{ {
if (empty($keys)) { if (empty($keys)) {
return []; return [];
@ -84,12 +84,12 @@ abstract class BaseCache implements ICache
* Filters the keys of an array with a given prefix * Filters the keys of an array with a given prefix
* Returns the filtered keys as an new array * Returns the filtered keys as an new array
* *
* @param array $keys The keys, which should get filtered * @param string[] $keys The keys, which should get filtered
* @param string|null $prefix The prefix (if null, all keys will get returned) * @param string|null $prefix The prefix (if null, all keys will get returned)
* *
* @return array The filtered array with just the keys * @return string[] The filtered array with just the keys
*/ */
protected function filterArrayKeysByPrefix(array $keys, string $prefix = null) protected function filterArrayKeysByPrefix(array $keys, string $prefix = null): array
{ {
if (empty($prefix)) { if (empty($prefix)) {
return $keys; return $keys;

View file

@ -21,25 +21,23 @@
namespace Friendica\Core\Cache\Type; namespace Friendica\Core\Cache\Type;
use Friendica\Core\Cache\Enum\Duration; use Friendica\Core\Cache\Capability\ICanCacheInMemory;
use Friendica\Core\Cache\IMemoryCache; use Friendica\Core\Cache\Enum;
use Friendica\Core\Cache\Type\TraitCompareDelete;
use Friendica\Core\Cache\Enum\Type;
/** /**
* Implementation of the IMemoryCache mainly for testing purpose * Implementation of the IMemoryCache mainly for testing purpose
*/ */
class ArrayCache extends BaseCache implements IMemoryCache class ArrayCache extends AbstractCache implements ICanCacheInMemory
{ {
use TraitCompareDelete; use CompareDeleteTrait;
/** @var array Array with the cached data */ /** @var array Array with the cached data */
protected $cachedData = array(); protected $cachedData = [];
/** /**
* (@inheritdoc) * (@inheritdoc)
*/ */
public function getAllKeys($prefix = null) public function getAllKeys(?string $prefix = null): array
{ {
return $this->filterArrayKeysByPrefix(array_keys($this->cachedData), $prefix); return $this->filterArrayKeysByPrefix(array_keys($this->cachedData), $prefix);
} }
@ -47,7 +45,7 @@ class ArrayCache extends BaseCache implements IMemoryCache
/** /**
* (@inheritdoc) * (@inheritdoc)
*/ */
public function get($key) public function get(string $key)
{ {
if (isset($this->cachedData[$key])) { if (isset($this->cachedData[$key])) {
return $this->cachedData[$key]; return $this->cachedData[$key];
@ -58,7 +56,7 @@ class ArrayCache extends BaseCache implements IMemoryCache
/** /**
* (@inheritdoc) * (@inheritdoc)
*/ */
public function set($key, $value, $ttl = Duration::FIVE_MINUTES) public function set(string $key, $value, int $ttl = Enum\Duration::FIVE_MINUTES): bool
{ {
$this->cachedData[$key] = $value; $this->cachedData[$key] = $value;
return true; return true;
@ -67,7 +65,7 @@ class ArrayCache extends BaseCache implements IMemoryCache
/** /**
* (@inheritdoc) * (@inheritdoc)
*/ */
public function delete($key) public function delete(string $key): bool
{ {
unset($this->cachedData[$key]); unset($this->cachedData[$key]);
return true; return true;
@ -76,7 +74,7 @@ class ArrayCache extends BaseCache implements IMemoryCache
/** /**
* (@inheritdoc) * (@inheritdoc)
*/ */
public function clear($outdated = true) public function clear(bool $outdated = true): bool
{ {
// Array doesn't support TTL so just don't delete something // Array doesn't support TTL so just don't delete something
if ($outdated) { if ($outdated) {
@ -90,7 +88,7 @@ class ArrayCache extends BaseCache implements IMemoryCache
/** /**
* (@inheritdoc) * (@inheritdoc)
*/ */
public function add($key, $value, $ttl = Duration::FIVE_MINUTES) public function add(string $key, $value, int $ttl = Enum\Duration::FIVE_MINUTES): bool
{ {
if (isset($this->cachedData[$key])) { if (isset($this->cachedData[$key])) {
return false; return false;
@ -102,7 +100,7 @@ class ArrayCache extends BaseCache implements IMemoryCache
/** /**
* (@inheritdoc) * (@inheritdoc)
*/ */
public function compareSet($key, $oldValue, $newValue, $ttl = Duration::FIVE_MINUTES) public function compareSet(string $key, $oldValue, $newValue, int $ttl = Enum\Duration::FIVE_MINUTES): bool
{ {
if ($this->get($key) === $oldValue) { if ($this->get($key) === $oldValue) {
return $this->set($key, $newValue); return $this->set($key, $newValue);
@ -114,8 +112,8 @@ class ArrayCache extends BaseCache implements IMemoryCache
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public function getName() public function getName(): string
{ {
return Type::ARRAY; return Enum\Type::ARRAY;
} }
} }

View file

@ -24,28 +24,28 @@ namespace Friendica\Core\Cache\Type;
use Friendica\Core\Cache\Enum\Duration; use Friendica\Core\Cache\Enum\Duration;
/** /**
* Trait TraitCompareSetDelete
*
* This Trait is to compensate nonnative "exclusive" sets/deletes in caches * This Trait is to compensate nonnative "exclusive" sets/deletes in caches
*/ */
trait TraitCompareDelete trait CompareDeleteTrait
{ {
abstract public function get($key); abstract public function get(string $key);
abstract public function set($key, $value, $ttl = Duration::FIVE_MINUTES); abstract public function set(string $key, $value, int $ttl = Duration::FIVE_MINUTES);
abstract public function delete($key); abstract public function delete(string $key);
abstract public function add($key, $value, $ttl = Duration::FIVE_MINUTES); abstract public function add(string $key, $value, int $ttl = Duration::FIVE_MINUTES);
/** /**
* NonNative - Compares if the old value is set and removes it * NonNative - Compares if the old value is set and removes it
* *
* @param string $key The cache key * @param string $key The cache key
* @param mixed $value The old value we know and want to delete * @param mixed $value The old value we know and want to delete
*
* @return bool * @return bool
*/ */
public function compareDelete($key, $value) { public function compareDelete(string $key, $value): bool
{
if ($this->add($key . "_lock", true)) { if ($this->add($key . "_lock", true)) {
if ($this->get($key) === $value) { if ($this->get($key) === $value) {
$this->delete($key); $this->delete($key);

View file

@ -24,19 +24,17 @@ namespace Friendica\Core\Cache\Type;
use Friendica\Core\Cache\Enum\Duration; use Friendica\Core\Cache\Enum\Duration;
/** /**
* Trait TraitCompareSetDelete
*
* This Trait is to compensate nonnative "exclusive" sets/deletes in caches * This Trait is to compensate nonnative "exclusive" sets/deletes in caches
*/ */
trait TraitCompareSet trait CompareSetTrait
{ {
abstract public function get($key); abstract public function get(string $key);
abstract public function set($key, $value, $ttl = Duration::FIVE_MINUTES); abstract public function set(string $key, $value, int $ttl = Duration::FIVE_MINUTES);
abstract public function delete($key); abstract public function delete(string $key);
abstract public function add($key, $value, $ttl = Duration::FIVE_MINUTES); abstract public function add(string $key, $value, int $ttl = Duration::FIVE_MINUTES);
/** /**
* NonNative - Compares if the old value is set and sets the new value * NonNative - Compares if the old value is set and sets the new value
@ -48,7 +46,8 @@ trait TraitCompareSet
* *
* @return bool * @return bool
*/ */
public function compareSet($key, $oldValue, $newValue, $ttl = Duration::FIVE_MINUTES) { public function compareSet(string $key, $oldValue, $newValue, int $ttl = Duration::FIVE_MINUTES): bool
{
if ($this->add($key . "_lock", true)) { if ($this->add($key . "_lock", true)) {
if ($this->get($key) === $oldValue) { if ($this->get($key) === $oldValue) {
$this->set($key, $newValue, $ttl); $this->set($key, $newValue, $ttl);

View file

@ -21,16 +21,16 @@
namespace Friendica\Core\Cache\Type; namespace Friendica\Core\Cache\Type;
use Friendica\Core\Cache\Enum\Duration; use Friendica\Core\Cache\Capability\ICanCache;
use Friendica\Core\Cache\ICache; use Friendica\Core\Cache\Enum;
use Friendica\Core\Cache\Enum\Type; use Friendica\Core\Cache\Exception\CachePersistenceException;
use Friendica\Database\Database; use Friendica\Database\Database;
use Friendica\Util\DateTimeFormat; use Friendica\Util\DateTimeFormat;
/** /**
* Database Cache * Database Cache
*/ */
class DatabaseCache extends BaseCache implements ICache class DatabaseCache extends AbstractCache implements ICanCache
{ {
/** /**
* @var Database * @var Database
@ -46,9 +46,12 @@ class DatabaseCache extends BaseCache implements ICache
/** /**
* (@inheritdoc) * (@inheritdoc)
*
* @throws CachePersistenceException
*/ */
public function getAllKeys($prefix = null) public function getAllKeys(?string $prefix = null): array
{ {
try {
if (empty($prefix)) { if (empty($prefix)) {
$where = ['`expires` >= ?', DateTimeFormat::utcNow()]; $where = ['`expires` >= ?', DateTimeFormat::utcNow()];
} else { } else {
@ -61,7 +64,11 @@ class DatabaseCache extends BaseCache implements ICache
while ($key = $this->dba->fetch($stmt)) { while ($key = $this->dba->fetch($stmt)) {
array_push($keys, $key['k']); array_push($keys, $key['k']);
} }
} catch (\Exception $exception) {
throw new CachePersistenceException(sprintf('Cannot fetch all keys with prefix %s', $prefix), $exception);
} finally {
$this->dba->close($stmt); $this->dba->close($stmt);
}
return $keys; return $keys;
} }
@ -69,9 +76,12 @@ class DatabaseCache extends BaseCache implements ICache
/** /**
* (@inheritdoc) * (@inheritdoc)
*/ */
public function get($key) public function get(string $key)
{ {
$cache = $this->dba->selectFirst('cache', ['v'], ['`k` = ? AND (`expires` >= ? OR `expires` = -1)', $key, DateTimeFormat::utcNow()]); try {
$cache = $this->dba->selectFirst('cache', ['v'], [
'`k` = ? AND (`expires` >= ? OR `expires` = -1)', $key, DateTimeFormat::utcNow()
]);
if ($this->dba->isResult($cache)) { if ($this->dba->isResult($cache)) {
$cached = $cache['v']; $cached = $cache['v'];
@ -84,6 +94,9 @@ class DatabaseCache extends BaseCache implements ICache
return $value; return $value;
} }
} }
} catch (\Exception $exception) {
throw new CachePersistenceException(sprintf('Cannot get cache entry with key %s', $key), $exception);
}
return null; return null;
} }
@ -91,8 +104,9 @@ class DatabaseCache extends BaseCache implements ICache
/** /**
* (@inheritdoc) * (@inheritdoc)
*/ */
public function set($key, $value, $ttl = Duration::FIVE_MINUTES) public function set(string $key, $value, int $ttl = Enum\Duration::FIVE_MINUTES): bool
{ {
try {
if ($ttl > 0) { if ($ttl > 0) {
$fields = [ $fields = [
'v' => serialize($value), 'v' => serialize($value),
@ -108,33 +122,44 @@ class DatabaseCache extends BaseCache implements ICache
} }
return $this->dba->update('cache', $fields, ['k' => $key], true); return $this->dba->update('cache', $fields, ['k' => $key], true);
} catch (\Exception $exception) {
throw new CachePersistenceException(sprintf('Cannot set cache entry with key %s', $key), $exception);
}
} }
/** /**
* (@inheritdoc) * (@inheritdoc)
*/ */
public function delete($key) public function delete(string $key): bool
{ {
try {
return $this->dba->delete('cache', ['k' => $key]); return $this->dba->delete('cache', ['k' => $key]);
} catch (\Exception $exception) {
throw new CachePersistenceException(sprintf('Cannot delete cache entry with key %s', $key), $exception);
}
} }
/** /**
* (@inheritdoc) * (@inheritdoc)
*/ */
public function clear($outdated = true) public function clear(bool $outdated = true): bool
{ {
try {
if ($outdated) { if ($outdated) {
return $this->dba->delete('cache', ['`expires` < NOW()']); return $this->dba->delete('cache', ['`expires` < NOW()']);
} else { } else {
return $this->dba->delete('cache', ['`k` IS NOT NULL ']); return $this->dba->delete('cache', ['`k` IS NOT NULL ']);
} }
} catch (\Exception $exception) {
throw new CachePersistenceException('Cannot clear cache', $exception);
}
} }
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public function getName() public function getName(): string
{ {
return Type::DATABASE; return Enum\Type::DATABASE;
} }
} }

View file

@ -21,24 +21,22 @@
namespace Friendica\Core\Cache\Type; namespace Friendica\Core\Cache\Type;
use Exception;
use Friendica\Core\Cache\Enum\Duration; use Friendica\Core\Cache\Enum\Duration;
use Friendica\Core\Cache\IMemoryCache; use Friendica\Core\Cache\Capability\ICanCacheInMemory;
use Friendica\Core\Cache\Type\TraitCompareDelete;
use Friendica\Core\Cache\Type\TraitCompareSet;
use Friendica\Core\Cache\Type\TraitMemcacheCommand;
use Friendica\Core\Cache\Enum\Type; use Friendica\Core\Cache\Enum\Type;
use Friendica\Core\Config\IConfig; use Friendica\Core\Cache\Exception\CachePersistenceException;
use Friendica\Core\Cache\Exception\InvalidCacheDriverException;
use Friendica\Core\Config\Capability\IManageConfigValues;
use Memcache; use Memcache;
/** /**
* Memcache Cache * Memcache Cache
*/ */
class MemcacheCache extends BaseCache implements IMemoryCache class MemcacheCache extends AbstractCache implements ICanCacheInMemory
{ {
use TraitCompareSet; use CompareSetTrait;
use TraitCompareDelete; use CompareDeleteTrait;
use TraitMemcacheCommand; use MemcacheCommandTrait;
/** /**
* @var Memcache * @var Memcache
@ -46,30 +44,34 @@ class MemcacheCache extends BaseCache implements IMemoryCache
private $memcache; private $memcache;
/** /**
* @throws Exception * @param string $hostname
* @param IManageConfigValues $config
*
* @throws InvalidCacheDriverException
* @throws CachePersistenceException
*/ */
public function __construct(string $hostname, IConfig $config) public function __construct(string $hostname, IManageConfigValues $config)
{ {
if (!class_exists('Memcache', false)) { if (!class_exists('Memcache', false)) {
throw new Exception('Memcache class isn\'t available'); throw new InvalidCacheDriverException('Memcache class isn\'t available');
} }
parent::__construct($hostname); parent::__construct($hostname);
$this->memcache = new Memcache(); $this->memcache = new Memcache();
$this->server = $config->get('system', 'memcache_host');; $this->server = $config->get('system', 'memcache_host');
$this->port = $config->get('system', 'memcache_port'); $this->port = $config->get('system', 'memcache_port');
if (!@$this->memcache->connect($this->server, $this->port)) { if (!@$this->memcache->connect($this->server, $this->port)) {
throw new Exception('Expected Memcache server at ' . $this->server . ':' . $this->port . ' isn\'t available'); throw new CachePersistenceException('Expected Memcache server at ' . $this->server . ':' . $this->port . ' isn\'t available');
} }
} }
/** /**
* (@inheritdoc) * (@inheritdoc)
*/ */
public function getAllKeys($prefix = null) public function getAllKeys(?string $prefix = null): array
{ {
$keys = $this->getOriginalKeys($this->getMemcacheKeys()); $keys = $this->getOriginalKeys($this->getMemcacheKeys());
@ -79,17 +81,16 @@ class MemcacheCache extends BaseCache implements IMemoryCache
/** /**
* (@inheritdoc) * (@inheritdoc)
*/ */
public function get($key) public function get(string $key)
{ {
$return = null; $cacheKey = $this->getCacheKey($key);
$cachekey = $this->getCacheKey($key);
// We fetch with the hostname as key to avoid problems with other applications // We fetch with the hostname as key to avoid problems with other applications
$cached = $this->memcache->get($cachekey); $cached = $this->memcache->get($cacheKey);
// @see http://php.net/manual/en/memcache.get.php#84275 // @see http://php.net/manual/en/memcache.get.php#84275
if (is_bool($cached) || is_double($cached) || is_long($cached)) { if (is_bool($cached) || is_double($cached) || is_long($cached)) {
return $return; return null;
} }
$value = @unserialize($cached); $value = @unserialize($cached);
@ -98,30 +99,30 @@ class MemcacheCache extends BaseCache implements IMemoryCache
// We also check if the db entry is a serialized // We also check if the db entry is a serialized
// boolean 'false' value (which we want to return). // boolean 'false' value (which we want to return).
if ($cached === serialize(false) || $value !== false) { if ($cached === serialize(false) || $value !== false) {
$return = $value; return $value;
} }
return $return; return null;
} }
/** /**
* (@inheritdoc) * (@inheritdoc)
*/ */
public function set($key, $value, $ttl = Duration::FIVE_MINUTES) public function set(string $key, $value, int $ttl = Duration::FIVE_MINUTES): bool
{ {
$cachekey = $this->getCacheKey($key); $cacheKey = $this->getCacheKey($key);
// We store with the hostname as key to avoid problems with other applications // We store with the hostname as key to avoid problems with other applications
if ($ttl > 0) { if ($ttl > 0) {
return $this->memcache->set( return $this->memcache->set(
$cachekey, $cacheKey,
serialize($value), serialize($value),
MEMCACHE_COMPRESSED, MEMCACHE_COMPRESSED,
time() + $ttl time() + $ttl
); );
} else { } else {
return $this->memcache->set( return $this->memcache->set(
$cachekey, $cacheKey,
serialize($value), serialize($value),
MEMCACHE_COMPRESSED MEMCACHE_COMPRESSED
); );
@ -131,16 +132,16 @@ class MemcacheCache extends BaseCache implements IMemoryCache
/** /**
* (@inheritdoc) * (@inheritdoc)
*/ */
public function delete($key) public function delete(string $key): bool
{ {
$cachekey = $this->getCacheKey($key); $cacheKey = $this->getCacheKey($key);
return $this->memcache->delete($cachekey); return $this->memcache->delete($cacheKey);
} }
/** /**
* (@inheritdoc) * (@inheritdoc)
*/ */
public function clear($outdated = true) public function clear(bool $outdated = true): bool
{ {
if ($outdated) { if ($outdated) {
return true; return true;
@ -152,16 +153,16 @@ class MemcacheCache extends BaseCache implements IMemoryCache
/** /**
* (@inheritdoc) * (@inheritdoc)
*/ */
public function add($key, $value, $ttl = Duration::FIVE_MINUTES) public function add(string $key, $value, int $ttl = Duration::FIVE_MINUTES): bool
{ {
$cachekey = $this->getCacheKey($key); $cacheKey = $this->getCacheKey($key);
return $this->memcache->add($cachekey, serialize($value), MEMCACHE_COMPRESSED, $ttl); return $this->memcache->add($cacheKey, serialize($value), MEMCACHE_COMPRESSED, $ttl);
} }
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public function getName() public function getName(): string
{ {
return Type::MEMCACHE; return Type::MEMCACHE;
} }

View file

@ -21,7 +21,7 @@
namespace Friendica\Core\Cache\Type; namespace Friendica\Core\Cache\Type;
use Friendica\Network\HTTPException\InternalServerErrorException; use Friendica\Core\Cache\Exception\CachePersistenceException;
/** /**
* Trait for Memcache to add a custom version of the * Trait for Memcache to add a custom version of the
@ -29,7 +29,7 @@ use Friendica\Network\HTTPException\InternalServerErrorException;
* *
* Adds the possibility to directly communicate with the memcache too * Adds the possibility to directly communicate with the memcache too
*/ */
trait TraitMemcacheCommand trait MemcacheCommandTrait
{ {
/** /**
* @var string server address * @var string server address
@ -52,22 +52,18 @@ trait TraitMemcacheCommand
* *
* @return array All keys of the memcache instance * @return array All keys of the memcache instance
* *
* @throws InternalServerErrorException * @throws CachePersistenceException
*/ */
protected function getMemcacheKeys() protected function getMemcacheKeys(): array
{ {
$string = $this->sendMemcacheCommand("stats items"); $string = $this->sendMemcacheCommand("stats items");
$lines = explode("\r\n", $string); $lines = explode("\r\n", $string);
$slabs = [];
$keys = []; $keys = [];
foreach ($lines as $line) { foreach ($lines as $line) {
if (preg_match("/STAT items:([\d]+):number ([\d]+)/", $line, $matches) && if (preg_match("/STAT items:([\d]+):number ([\d]+)/", $line, $matches) &&
isset($matches[1]) && isset($matches[1]) &&
!in_array($matches[1], $keys)) { !in_array($matches[1], $keys)) {
$slabs[] = $matches[1];
$string = $this->sendMemcacheCommand("stats cachedump " . $matches[1] . " " . $matches[2]); $string = $this->sendMemcacheCommand("stats cachedump " . $matches[1] . " " . $matches[2]);
preg_match_all("/ITEM (.*?) /", $string, $matches); preg_match_all("/ITEM (.*?) /", $string, $matches);
$keys = array_merge($keys, $matches[1]); $keys = array_merge($keys, $matches[1]);
@ -88,20 +84,19 @@ trait TraitMemcacheCommand
* *
* @return string The returned buffer result * @return string The returned buffer result
* *
* @throws InternalServerErrorException In case the memcache server isn't available (anymore) * @throws CachePersistenceException In case the memcache server isn't available (anymore)
*/ */
protected function sendMemcacheCommand(string $command) protected function sendMemcacheCommand(string $command): string
{ {
$s = @fsockopen($this->server, $this->port); $s = @fsockopen($this->server, $this->port);
if (!$s) { if (!$s) {
throw new InternalServerErrorException("Cant connect to:" . $this->server . ':' . $this->port); throw new CachePersistenceException("Cant connect to:" . $this->server . ':' . $this->port);
} }
fwrite($s, $command . "\r\n"); fwrite($s, $command . "\r\n");
$buf = ''; $buf = '';
while (!feof($s)) { while (!feof($s)) {
$buf .= fgets($s, 256); $buf .= fgets($s, 256);
if (strpos($buf, "END\r\n") !== false) { // stat says end if (strpos($buf, "END\r\n") !== false) { // stat says end

View file

@ -21,25 +21,23 @@
namespace Friendica\Core\Cache\Type; namespace Friendica\Core\Cache\Type;
use Exception;
use Friendica\Core\Cache\Enum\Duration; use Friendica\Core\Cache\Enum\Duration;
use Friendica\Core\Cache\IMemoryCache; use Friendica\Core\Cache\Capability\ICanCacheInMemory;
use Friendica\Core\Cache\Type\TraitCompareDelete;
use Friendica\Core\Cache\Type\TraitCompareSet;
use Friendica\Core\Cache\Type\TraitMemcacheCommand;
use Friendica\Core\Cache\Enum\Type; use Friendica\Core\Cache\Enum\Type;
use Friendica\Core\Config\IConfig; use Friendica\Core\Cache\Exception\CachePersistenceException;
use Friendica\Core\Cache\Exception\InvalidCacheDriverException;
use Friendica\Core\Config\Capability\IManageConfigValues;
use Memcached; use Memcached;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
/** /**
* Memcached Cache * Memcached Cache
*/ */
class MemcachedCache extends BaseCache implements IMemoryCache class MemcachedCache extends AbstractCache implements ICanCacheInMemory
{ {
use TraitCompareSet; use CompareSetTrait;
use TraitCompareDelete; use CompareDeleteTrait;
use TraitMemcacheCommand; use MemcacheCommandTrait;
/** /**
* @var \Memcached * @var \Memcached
@ -58,14 +56,17 @@ class MemcachedCache extends BaseCache implements IMemoryCache
* 1 => ... * 1 => ...
* } * }
* *
* @param array $memcached_hosts * @param string $hostname
* @param IManageConfigValues $config
* @param LoggerInterface $logger
* *
* @throws \Exception * @throws InvalidCacheDriverException
* @throws CachePersistenceException
*/ */
public function __construct(string $hostname, IConfig $config, LoggerInterface $logger) public function __construct(string $hostname, IManageConfigValues $config, LoggerInterface $logger)
{ {
if (!class_exists('Memcached', false)) { if (!class_exists('Memcached', false)) {
throw new Exception('Memcached class isn\'t available'); throw new InvalidCacheDriverException('Memcached class isn\'t available');
} }
parent::__construct($hostname); parent::__construct($hostname);
@ -88,14 +89,14 @@ class MemcachedCache extends BaseCache implements IMemoryCache
$this->memcached->addServers($memcached_hosts); $this->memcached->addServers($memcached_hosts);
if (count($this->memcached->getServerList()) == 0) { if (count($this->memcached->getServerList()) == 0) {
throw new Exception('Expected Memcached servers aren\'t available, config:' . var_export($memcached_hosts, true)); throw new CachePersistenceException('Expected Memcached servers aren\'t available, config:' . var_export($memcached_hosts, true));
} }
} }
/** /**
* (@inheritdoc) * (@inheritdoc)
*/ */
public function getAllKeys($prefix = null) public function getAllKeys(?string $prefix = null): array
{ {
$keys = $this->getOriginalKeys($this->getMemcacheKeys()); $keys = $this->getOriginalKeys($this->getMemcacheKeys());
@ -105,40 +106,40 @@ class MemcachedCache extends BaseCache implements IMemoryCache
/** /**
* (@inheritdoc) * (@inheritdoc)
*/ */
public function get($key) public function get(string $key)
{ {
$return = null; $cacheKey = $this->getCacheKey($key);
$cachekey = $this->getCacheKey($key);
// We fetch with the hostname as key to avoid problems with other applications // We fetch with the hostname as key to avoid problems with other applications
$value = $this->memcached->get($cachekey); $value = $this->memcached->get($cacheKey);
if ($this->memcached->getResultCode() === Memcached::RES_SUCCESS) { if ($this->memcached->getResultCode() === Memcached::RES_SUCCESS) {
$return = $value; return $value;
} elseif ($this->memcached->getResultCode() === Memcached::RES_NOTFOUND) {
$this->logger->notice('Try to use unknown key.', ['key' => $key]);
return null;
} else { } else {
$this->logger->debug('Memcached \'get\' failed', ['result' => $this->memcached->getResultMessage()]); throw new CachePersistenceException(sprintf('Cannot get cache entry with key %s', $key), new \MemcachedException($this->memcached->getResultMessage(), $this->memcached->getResultCode()));
} }
return $return;
} }
/** /**
* (@inheritdoc) * (@inheritdoc)
*/ */
public function set($key, $value, $ttl = Duration::FIVE_MINUTES) public function set(string $key, $value, int $ttl = Duration::FIVE_MINUTES): bool
{ {
$cachekey = $this->getCacheKey($key); $cacheKey = $this->getCacheKey($key);
// We store with the hostname as key to avoid problems with other applications // We store with the hostname as key to avoid problems with other applications
if ($ttl > 0) { if ($ttl > 0) {
return $this->memcached->set( return $this->memcached->set(
$cachekey, $cacheKey,
$value, $value,
$ttl $ttl
); );
} else { } else {
return $this->memcached->set( return $this->memcached->set(
$cachekey, $cacheKey,
$value $value
); );
} }
@ -147,16 +148,16 @@ class MemcachedCache extends BaseCache implements IMemoryCache
/** /**
* (@inheritdoc) * (@inheritdoc)
*/ */
public function delete($key) public function delete(string $key): bool
{ {
$cachekey = $this->getCacheKey($key); $cacheKey = $this->getCacheKey($key);
return $this->memcached->delete($cachekey); return $this->memcached->delete($cacheKey);
} }
/** /**
* (@inheritdoc) * (@inheritdoc)
*/ */
public function clear($outdated = true) public function clear(bool $outdated = true): bool
{ {
if ($outdated) { if ($outdated) {
return true; return true;
@ -168,16 +169,16 @@ class MemcachedCache extends BaseCache implements IMemoryCache
/** /**
* (@inheritdoc) * (@inheritdoc)
*/ */
public function add($key, $value, $ttl = Duration::FIVE_MINUTES) public function add(string $key, $value, int $ttl = Duration::FIVE_MINUTES): bool
{ {
$cachekey = $this->getCacheKey($key); $cacheKey = $this->getCacheKey($key);
return $this->memcached->add($cachekey, $value, $ttl); return $this->memcached->add($cacheKey, $value, $ttl);
} }
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public function getName() public function getName(): string
{ {
return Type::MEMCACHED; return Type::MEMCACHED;
} }

View file

@ -22,19 +22,19 @@
namespace Friendica\Core\Cache\Type; namespace Friendica\Core\Cache\Type;
use Friendica\Core\Cache\Enum\Duration; use Friendica\Core\Cache\Enum\Duration;
use Friendica\Core\Cache\ICache; use Friendica\Core\Cache\Capability\ICanCache;
use Friendica\Core\Cache\IMemoryCache; use Friendica\Core\Cache\Capability\ICanCacheInMemory;
use Friendica\Util\Profiler; use Friendica\Util\Profiler;
/** /**
* This class wraps cache driver so they can get profiled - in case the profiler is enabled * This class wraps cache driver, so they can get profiled - in case the profiler is enabled
* *
* It is using the decorator pattern (@see * It is using the decorator pattern (@see https://en.wikipedia.org/wiki/Decorator_pattern )
*/ */
class ProfilerCache implements ICache, IMemoryCache class ProfilerCacheDecorator implements ICanCache, ICanCacheInMemory
{ {
/** /**
* @var ICache The original cache driver * @var ICanCache The original cache driver
*/ */
private $cache; private $cache;
@ -43,7 +43,7 @@ class ProfilerCache implements ICache, IMemoryCache
*/ */
private $profiler; private $profiler;
public function __construct(ICache $cache, Profiler $profiler) public function __construct(ICanCache $cache, Profiler $profiler)
{ {
$this->cache = $cache; $this->cache = $cache;
$this->profiler = $profiler; $this->profiler = $profiler;
@ -52,7 +52,7 @@ class ProfilerCache implements ICache, IMemoryCache
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public function getAllKeys($prefix = null) public function getAllKeys(?string $prefix = null): array
{ {
$this->profiler->startRecording('cache'); $this->profiler->startRecording('cache');
@ -66,7 +66,7 @@ class ProfilerCache implements ICache, IMemoryCache
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public function get($key) public function get(string $key)
{ {
$this->profiler->startRecording('cache'); $this->profiler->startRecording('cache');
@ -80,7 +80,7 @@ class ProfilerCache implements ICache, IMemoryCache
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public function set($key, $value, $ttl = Duration::FIVE_MINUTES) public function set(string $key, $value, int $ttl = Duration::FIVE_MINUTES): bool
{ {
$this->profiler->startRecording('cache'); $this->profiler->startRecording('cache');
@ -94,7 +94,7 @@ class ProfilerCache implements ICache, IMemoryCache
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public function delete($key) public function delete(string $key): bool
{ {
$this->profiler->startRecording('cache'); $this->profiler->startRecording('cache');
@ -108,7 +108,7 @@ class ProfilerCache implements ICache, IMemoryCache
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public function clear($outdated = true) public function clear(bool $outdated = true): bool
{ {
$this->profiler->startRecording('cache'); $this->profiler->startRecording('cache');
@ -122,9 +122,9 @@ class ProfilerCache implements ICache, IMemoryCache
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public function add($key, $value, $ttl = Duration::FIVE_MINUTES) public function add(string $key, $value, int $ttl = Duration::FIVE_MINUTES): bool
{ {
if ($this->cache instanceof IMemoryCache) { if ($this->cache instanceof ICanCacheInMemory) {
$this->profiler->startRecording('cache'); $this->profiler->startRecording('cache');
$return = $this->cache->add($key, $value, $ttl); $return = $this->cache->add($key, $value, $ttl);
@ -140,9 +140,9 @@ class ProfilerCache implements ICache, IMemoryCache
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public function compareSet($key, $oldValue, $newValue, $ttl = Duration::FIVE_MINUTES) public function compareSet(string $key, $oldValue, $newValue, int $ttl = Duration::FIVE_MINUTES): bool
{ {
if ($this->cache instanceof IMemoryCache) { if ($this->cache instanceof ICanCacheInMemory) {
$this->profiler->startRecording('cache'); $this->profiler->startRecording('cache');
$return = $this->cache->compareSet($key, $oldValue, $newValue, $ttl); $return = $this->cache->compareSet($key, $oldValue, $newValue, $ttl);
@ -158,9 +158,9 @@ class ProfilerCache implements ICache, IMemoryCache
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public function compareDelete($key, $value) public function compareDelete(string $key, $value): bool
{ {
if ($this->cache instanceof IMemoryCache) { if ($this->cache instanceof ICanCacheInMemory) {
$this->profiler->startRecording('cache'); $this->profiler->startRecording('cache');
$return = $this->cache->compareDelete($key, $value); $return = $this->cache->compareDelete($key, $value);
@ -176,7 +176,7 @@ class ProfilerCache implements ICache, IMemoryCache
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public function GetName() public function GetName(): string
{ {
return $this->cache->getName() . ' (with profiler)'; return $this->cache->getName() . ' (with profiler)';
} }

View file

@ -23,15 +23,17 @@ namespace Friendica\Core\Cache\Type;
use Exception; use Exception;
use Friendica\Core\Cache\Enum\Duration; use Friendica\Core\Cache\Enum\Duration;
use Friendica\Core\Cache\IMemoryCache; use Friendica\Core\Cache\Capability\ICanCacheInMemory;
use Friendica\Core\Cache\Enum\Type; use Friendica\Core\Cache\Enum\Type;
use Friendica\Core\Config\IConfig; use Friendica\Core\Cache\Exception\CachePersistenceException;
use Friendica\Core\Cache\Exception\InvalidCacheDriverException;
use Friendica\Core\Config\Capability\IManageConfigValues;
use Redis; use Redis;
/** /**
* Redis Cache. This driver is based on Memcache driver * Redis Cache. This driver is based on Memcache driver
*/ */
class RedisCache extends BaseCache implements IMemoryCache class RedisCache extends AbstractCache implements ICanCacheInMemory
{ {
/** /**
* @var Redis * @var Redis
@ -39,12 +41,13 @@ class RedisCache extends BaseCache implements IMemoryCache
private $redis; private $redis;
/** /**
* @throws Exception * @throws InvalidCacheDriverException
* @throws CachePersistenceException
*/ */
public function __construct(string $hostname, IConfig $config) public function __construct(string $hostname, IManageConfigValues $config)
{ {
if (!class_exists('Redis', false)) { if (!class_exists('Redis', false)) {
throw new Exception('Redis class isn\'t available'); throw new InvalidCacheDriverException('Redis class isn\'t available');
} }
parent::__construct($hostname); parent::__construct($hostname);
@ -57,24 +60,24 @@ class RedisCache extends BaseCache implements IMemoryCache
$redis_db = $config->get('system', 'redis_db', 0); $redis_db = $config->get('system', 'redis_db', 0);
if (isset($redis_port) && !@$this->redis->connect($redis_host, $redis_port)) { if (isset($redis_port) && !@$this->redis->connect($redis_host, $redis_port)) {
throw new Exception('Expected Redis server at ' . $redis_host . ':' . $redis_port . ' isn\'t available'); throw new CachePersistenceException('Expected Redis server at ' . $redis_host . ':' . $redis_port . ' isn\'t available');
} elseif (!@$this->redis->connect($redis_host)) { } elseif (!@$this->redis->connect($redis_host)) {
throw new Exception('Expected Redis server at ' . $redis_host . ' isn\'t available'); throw new CachePersistenceException('Expected Redis server at ' . $redis_host . ' isn\'t available');
} }
if (isset($redis_pw) && !$this->redis->auth($redis_pw)) { if (isset($redis_pw) && !$this->redis->auth($redis_pw)) {
throw new Exception('Cannot authenticate redis server at ' . $redis_host . ':' . $redis_port); throw new CachePersistenceException('Cannot authenticate redis server at ' . $redis_host . ':' . $redis_port);
} }
if ($redis_db !== 0 && !$this->redis->select($redis_db)) { if ($redis_db !== 0 && !$this->redis->select($redis_db)) {
throw new Exception('Cannot switch to redis db ' . $redis_db . ' at ' . $redis_host . ':' . $redis_port); throw new CachePersistenceException('Cannot switch to redis db ' . $redis_db . ' at ' . $redis_host . ':' . $redis_port);
} }
} }
/** /**
* (@inheritdoc) * (@inheritdoc)
*/ */
public function getAllKeys($prefix = null) public function getAllKeys(?string $prefix = null): array
{ {
if (empty($prefix)) { if (empty($prefix)) {
$search = '*'; $search = '*';
@ -90,13 +93,13 @@ class RedisCache extends BaseCache implements IMemoryCache
/** /**
* (@inheritdoc) * (@inheritdoc)
*/ */
public function get($key) public function get(string $key)
{ {
$return = null; $return = null;
$cachekey = $this->getCacheKey($key); $cacheKey = $this->getCacheKey($key);
$cached = $this->redis->get($cachekey); $cached = $this->redis->get($cacheKey);
if ($cached === false && !$this->redis->exists($cachekey)) { if ($cached === false && !$this->redis->exists($cacheKey)) {
return null; return null;
} }
@ -115,21 +118,21 @@ class RedisCache extends BaseCache implements IMemoryCache
/** /**
* (@inheritdoc) * (@inheritdoc)
*/ */
public function set($key, $value, $ttl = Duration::FIVE_MINUTES) public function set(string $key, $value, int $ttl = Duration::FIVE_MINUTES): bool
{ {
$cachekey = $this->getCacheKey($key); $cacheKey = $this->getCacheKey($key);
$cached = serialize($value); $cached = serialize($value);
if ($ttl > 0) { if ($ttl > 0) {
return $this->redis->setex( return $this->redis->setex(
$cachekey, $cacheKey,
$ttl, $ttl,
$cached $cached
); );
} else { } else {
return $this->redis->set( return $this->redis->set(
$cachekey, $cacheKey,
$cached $cached
); );
} }
@ -138,10 +141,10 @@ class RedisCache extends BaseCache implements IMemoryCache
/** /**
* (@inheritdoc) * (@inheritdoc)
*/ */
public function delete($key) public function delete(string $key): bool
{ {
$cachekey = $this->getCacheKey($key); $cacheKey = $this->getCacheKey($key);
$this->redis->del($cachekey); $this->redis->del($cacheKey);
// Redis doesn't have an error state for del() // Redis doesn't have an error state for del()
return true; return true;
} }
@ -149,7 +152,7 @@ class RedisCache extends BaseCache implements IMemoryCache
/** /**
* (@inheritdoc) * (@inheritdoc)
*/ */
public function clear($outdated = true) public function clear(bool $outdated = true): bool
{ {
if ($outdated) { if ($outdated) {
return true; return true;
@ -161,34 +164,30 @@ class RedisCache extends BaseCache implements IMemoryCache
/** /**
* (@inheritdoc) * (@inheritdoc)
*/ */
public function add($key, $value, $ttl = Duration::FIVE_MINUTES) public function add(string $key, $value, int $ttl = Duration::FIVE_MINUTES): bool
{ {
$cachekey = $this->getCacheKey($key); $cacheKey = $this->getCacheKey($key);
$cached = serialize($value); $cached = serialize($value);
return $this->redis->setnx($cachekey, $cached); return $this->redis->setnx($cacheKey, $cached);
} }
/** /**
* (@inheritdoc) * (@inheritdoc)
*/ */
public function compareSet($key, $oldValue, $newValue, $ttl = Duration::FIVE_MINUTES) public function compareSet(string $key, $oldValue, $newValue, int $ttl = Duration::FIVE_MINUTES): bool
{ {
$cachekey = $this->getCacheKey($key); $cacheKey = $this->getCacheKey($key);
$newCached = serialize($newValue); $newCached = serialize($newValue);
$this->redis->watch($cachekey); $this->redis->watch($cacheKey);
// If the old value isn't what we expected, somebody else changed the key meanwhile // If the old value isn't what we expected, somebody else changed the key meanwhile
if ($this->get($key) === $oldValue) { if ($this->get($key) === $oldValue) {
if ($ttl > 0) { if ($ttl > 0) {
$result = $this->redis->multi() $result = $this->redis->multi()->setex($cacheKey, $ttl, $newCached)->exec();
->setex($cachekey, $ttl, $newCached)
->exec();
} else { } else {
$result = $this->redis->multi() $result = $this->redis->multi()->set($cacheKey, $newCached)->exec();
->set($cachekey, $newCached)
->exec();
} }
return $result !== false; return $result !== false;
} }
@ -199,17 +198,15 @@ class RedisCache extends BaseCache implements IMemoryCache
/** /**
* (@inheritdoc) * (@inheritdoc)
*/ */
public function compareDelete($key, $value) public function compareDelete(string $key, $value): bool
{ {
$cachekey = $this->getCacheKey($key); $cacheKey = $this->getCacheKey($key);
$this->redis->watch($cachekey); $this->redis->watch($cacheKey);
// If the old value isn't what we expected, somebody else changed the key meanwhile // If the old value isn't what we expected, somebody else changed the key meanwhile
if ($this->get($key) === $value) { if ($this->get($key) === $value) {
$result = $this->redis->multi() $this->redis->multi()->del($cacheKey)->exec();
->del($cachekey) return true;
->exec();
return $result !== false;
} }
$this->redis->unwatch(); $this->redis->unwatch();
return false; return false;
@ -218,7 +215,7 @@ class RedisCache extends BaseCache implements IMemoryCache
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public function getName() public function getName(): string
{ {
return Type::REDIS; return Type::REDIS;
} }

View file

@ -19,32 +19,35 @@
* *
*/ */
namespace Friendica\Core\Config; namespace Friendica\Core\Config\Capability;
use Friendica\Core\Config\Cache\Cache; use Friendica\Core\Config\Exception\ConfigPersistenceException;
use Friendica\Core\Config\ValueObject\Cache;
/** /**
* Interface for accessing system wide configurations * Interface for accessing system-wide configurations
*/ */
interface IConfig interface IManageConfigValues
{ {
/** /**
* Loads all configuration values of family into a cached storage. * Loads all configuration values of family into a cached storage.
* *
* All configuration values of the system are stored in the cache ( @param string $cat The category of the configuration value * All configuration values of the system are stored in the cache.
*
* @param string $cat The category of the configuration value
* *
* @return void * @return void
*
* @throws ConfigPersistenceException In case the persistence layer throws errors
*/ */
function load(string $cat = 'config'); public function load(string $cat = 'config');
/** /**
* Get a particular user's config variable given the category name * Get a particular user's config variable given the category name
* ($cat) and a $key. * ($cat) and a $key.
* *
* Get a particular config value from the given category ($cat) * Get a particular config value from the given category ($cat)
* and the $key from a cached storage either from the $this->configAdapter * and the $key from a cached storage either from the database or from the cache.
* (@see IConfigAdapter) or from the $this->configCache (@see ConfigCache).
* *
* @param string $cat The category of the configuration value * @param string $cat The category of the configuration value
* @param string $key The configuration key to query * @param string $key The configuration key to query
@ -52,8 +55,11 @@ interface IConfig
* @param boolean $refresh optional, If true the config is loaded from the db and not from the cache (default: false) * @param boolean $refresh optional, If true the config is loaded from the db and not from the cache (default: false)
* *
* @return mixed Stored value or null if it does not exist * @return mixed Stored value or null if it does not exist
*
* @throws ConfigPersistenceException In case the persistence layer throws errors
*
*/ */
function get(string $cat, string $key, $default_value = null, bool $refresh = false); public function get(string $cat, string $key, $default_value = null, bool $refresh = false);
/** /**
* Sets a configuration value for system config * Sets a configuration value for system config
@ -67,26 +73,30 @@ interface IConfig
* @param mixed $value The value to store * @param mixed $value The value to store
* *
* @return bool Operation success * @return bool Operation success
*
* @throws ConfigPersistenceException In case the persistence layer throws errors
*/ */
function set(string $cat, string $key, $value); public function set(string $cat, string $key, $value): bool;
/** /**
* Deletes the given key from the system configuration. * Deletes the given key from the system configuration.
* *
* Removes the configured value from the stored cache in $this->configCache * Removes the configured value from the stored cache in the cache and removes it from the database.
* (@see ConfigCache) and removes it from the database (@see IConfigAdapter).
* *
* @param string $cat The category of the configuration value * @param string $cat The category of the configuration value
* @param string $key The configuration key to delete * @param string $key The configuration key to delete
* *
* @return bool * @return bool
*
* @throws ConfigPersistenceException In case the persistence layer throws errors
*
*/ */
function delete(string $cat, string $key); public function delete(string $cat, string $key): bool;
/** /**
* Returns the Config Cache * Returns the Config Cache
* *
* @return Cache * @return Cache
*/ */
function getCache(); public function getCache(): Cache;
} }

View file

@ -0,0 +1,13 @@
<?php
namespace Friendica\Core\Config\Exception;
use Throwable;
class ConfigFileException extends \RuntimeException
{
public function __construct($message = "", $code = 0, Throwable $previous = null)
{
parent::__construct($message, 500, $previous);
}
}

View file

@ -0,0 +1,13 @@
<?php
namespace Friendica\Core\Config\Exception;
use Throwable;
class ConfigPersistenceException extends \RuntimeException
{
public function __construct($message = "", Throwable $previous = null)
{
parent::__construct($message, 500, $previous);
}
}

View file

@ -21,13 +21,13 @@
namespace Friendica\Core\Config\Factory; namespace Friendica\Core\Config\Factory;
use Exception; use Friendica\Core\Config\Capability;
use Friendica\Core\Config; use Friendica\Core\Config\Repository;
use Friendica\Core\Config\Cache\Cache; use Friendica\Core\Config\Type;
use Friendica\Core\Config\Model\Config as ConfigModel; use Friendica\Core\Config\Util;
use Friendica\Core\Config\Cache\ConfigFileLoader; use Friendica\Core\Config\ValueObject\Cache;
class ConfigFactory class Config
{ {
/** /**
* The key of the $_SERVER variable to override the config directory * The key of the $_SERVER variable to override the config directory
@ -52,11 +52,11 @@ class ConfigFactory
/** /**
* @param string $basePath The basepath of FRIENDICA * @param string $basePath The basepath of FRIENDICA
* @param array $serer the $_SERVER array * @param array $server The $_SERVER array
* *
* @return \Friendica\Core\Config\Cache\ConfigFileLoader * @return Util\ConfigFileLoader
*/ */
public function createConfigFileLoader(string $basePath, array $server = []) public function createConfigFileLoader(string $basePath, array $server = []): Util\ConfigFileLoader
{ {
if (!empty($server[self::CONFIG_DIR_ENV]) && is_dir($server[self::CONFIG_DIR_ENV])) { if (!empty($server[self::CONFIG_DIR_ENV]) && is_dir($server[self::CONFIG_DIR_ENV])) {
$configDir = $server[self::CONFIG_DIR_ENV]; $configDir = $server[self::CONFIG_DIR_ENV];
@ -65,17 +65,16 @@ class ConfigFactory
} }
$staticDir = $basePath . DIRECTORY_SEPARATOR . self::STATIC_DIR; $staticDir = $basePath . DIRECTORY_SEPARATOR . self::STATIC_DIR;
return new ConfigFileLoader($basePath, $configDir, $staticDir); return new Util\ConfigFileLoader($basePath, $configDir, $staticDir);
} }
/** /**
* @param \Friendica\Core\Config\Cache\ConfigFileLoader $loader The Config Cache loader (INI/config/.htconfig) * @param Util\ConfigFileLoader $loader The Config Cache loader (INI/config/.htconfig)
* @param array $server
* *
* @return Cache * @return Cache
*
* @throws Exception
*/ */
public function createCache(ConfigFileLoader $loader, array $server = []) public function createCache(Util\ConfigFileLoader $loader, array $server = []): Cache
{ {
$configCache = new Cache(); $configCache = new Cache();
$loader->setupCache($configCache, $server); $loader->setupCache($configCache, $server);
@ -84,20 +83,19 @@ class ConfigFactory
} }
/** /**
* @param \Friendica\Core\Config\Cache\Cache $configCache The config cache of this adapter * @param Cache $configCache The config cache of this adapter
* @param ConfigModel $configModel The configuration model * @param Repository\Config $configRepo The configuration repository
* *
* @return Config\IConfig * @return Capability\IManageConfigValues
*/ */
public function create(Cache $configCache, ConfigModel $configModel) public function create(Cache $configCache, Repository\Config $configRepo)
{ {
if ($configCache->get('system', 'config_adapter') === 'preload') { if ($configCache->get('system', 'config_adapter') === 'preload') {
$configuration = new Config\Type\PreloadConfig($configCache, $configModel); $configuration = new Type\PreloadConfig($configCache, $configRepo);
} else { } else {
$configuration = new Config\Type\JitConfig($configCache, $configModel); $configuration = new Type\JitConfig($configCache, $configRepo);
} }
return $configuration; return $configuration;
} }
} }

View file

@ -19,34 +19,35 @@
* *
*/ */
namespace Friendica\Core\Config\Model; namespace Friendica\Core\Config\Repository;
use Friendica\Core\Config\Exception\ConfigPersistenceException;
use Friendica\Core\Config\Util\ValueConversion;
use Friendica\Database\Database; use Friendica\Database\Database;
/** /**
* The Config model backend, which is using the general DB-model backend for configs * The Config Repository, which is using the general DB-model backend for configs
*/ */
class Config class Config
{ {
/** @var Database */ /** @var Database */
protected $dba; protected $db;
/** public function __construct(Database $db)
* @param Database $dba The database connection of this model
*/
public function __construct(Database $dba)
{ {
$this->dba = $dba; $this->db = $db;
} }
protected static $table_name = 'config';
/** /**
* Checks if the model is currently connected * Checks if the model is currently connected
* *
* @return bool * @return bool
*/ */
public function isConnected() public function isConnected(): bool
{ {
return $this->dba->isConnected(); return $this->db->isConnected();
} }
/** /**
@ -56,29 +57,33 @@ class Config
* *
* @return array The config array * @return array The config array
* *
* @throws \Exception In case DB calls are invalid * @throws ConfigPersistenceException In case the persistence layer throws errors
*/ */
public function load(string $cat = null) public function load(?string $cat = null): array
{ {
$return = []; $return = [];
try {
if (empty($cat)) { if (empty($cat)) {
$configs = $this->dba->select('config', ['cat', 'v', 'k']); $configs = $this->db->select(static::$table_name, ['cat', 'v', 'k']);
} else { } else {
$configs = $this->dba->select('config', ['cat', 'v', 'k'], ['cat' => $cat]); $configs = $this->db->select(static::$table_name, ['cat', 'v', 'k'], ['cat' => $cat]);
} }
while ($config = $this->dba->fetch($configs)) { while ($config = $this->db->fetch($configs)) {
$key = $config['k']; $key = $config['k'];
$value = DbaUtils::toConfigValue($config['v']); $value = ValueConversion::toConfigValue($config['v']);
// just save it in case it is set // just save it in case it is set
if (isset($value)) { if (isset($value)) {
$return[$config['cat']][$key] = $value; $return[$config['cat']][$key] = $value;
} }
} }
$this->dba->close($configs); } catch (\Exception $exception) {
throw new ConfigPersistenceException(sprintf('Cannot load config category %s', $cat), $exception);
} finally {
$this->db->close($configs);
}
return $return; return $return;
} }
@ -94,7 +99,7 @@ class Config
* *
* @return array|string|null Stored value or null if it does not exist * @return array|string|null Stored value or null if it does not exist
* *
* @throws \Exception In case DB calls are invalid * @throws ConfigPersistenceException In case the persistence layer throws errors
*/ */
public function get(string $cat, string $key) public function get(string $cat, string $key)
{ {
@ -102,15 +107,19 @@ class Config
return null; return null;
} }
$config = $this->dba->selectFirst('config', ['v'], ['cat' => $cat, 'k' => $key]); try {
if ($this->dba->isResult($config)) { $config = $this->db->selectFirst(static::$table_name, ['v'], ['cat' => $cat, 'k' => $key]);
$value = DbaUtils::toConfigValue($config['v']); if ($this->db->isResult($config)) {
$value = ValueConversion::toConfigValue($config['v']);
// just return it in case it is set // just return it in case it is set
if (isset($value)) { if (isset($value)) {
return $value; return $value;
} }
} }
} catch (\Exception $exception) {
throw new ConfigPersistenceException(sprintf('Cannot get config with category %s and key %s', $cat, $key), $exception);
}
return null; return null;
} }
@ -126,9 +135,9 @@ class Config
* *
* @return bool Operation success * @return bool Operation success
* *
* @throws \Exception In case DB calls are invalid * @throws ConfigPersistenceException In case the persistence layer throws errors
*/ */
public function set(string $cat, string $key, $value) public function set(string $cat, string $key, $value): bool
{ {
if (!$this->isConnected()) { if (!$this->isConnected()) {
return false; return false;
@ -144,11 +153,13 @@ class Config
return true; return true;
} }
$dbvalue = DbaUtils::toDbValue($value); $dbValue = ValueConversion::toDbValue($value);
$result = $this->dba->update('config', ['v' => $dbvalue], ['cat' => $cat, 'k' => $key], true); try {
return $this->db->update(static::$table_name, ['v' => $dbValue], ['cat' => $cat, 'k' => $key], true);
return $result; } catch (\Exception $exception) {
throw new ConfigPersistenceException(sprintf('Cannot set config with category %s and key %s', $cat, $key), $exception);
}
} }
/** /**
@ -159,14 +170,18 @@ class Config
* *
* @return bool Operation success * @return bool Operation success
* *
* @throws \Exception In case DB calls are invalid * @throws ConfigPersistenceException In case the persistence layer throws errors
*/ */
public function delete(string $cat, string $key) public function delete(string $cat, string $key): bool
{ {
if (!$this->isConnected()) { if (!$this->isConnected()) {
return false; return false;
} }
return $this->dba->delete('config', ['cat' => $cat, 'k' => $key]); try {
return $this->db->delete(static::$table_name, ['cat' => $cat, 'k' => $key]);
} catch (\Exception $exception) {
throw new ConfigPersistenceException(sprintf('Cannot delete config with category %s and key %s', $cat, $key), $exception);
}
} }
} }

View file

@ -21,17 +21,17 @@
namespace Friendica\Core\Config\Type; namespace Friendica\Core\Config\Type;
use Friendica\Core\Config\Cache\Cache; use Friendica\Core\Config\Repository\Config;
use Friendica\Core\Config\IConfig; use Friendica\Core\Config\ValueObject\Cache;
use Friendica\Model; use Friendica\Core\Config\Capability\IManageConfigValues;
/** /**
* This class is responsible for all system-wide configuration values in Friendica * This class is responsible for all system-wide configuration values in Friendica
* There are two types of storage * There are two types of storage
* - The Config-Files (loaded into the FileCache @see ConfigCache) * - The Config-Files (loaded into the FileCache @see Cache)
* - The Config-DB-Table (per Config-DB-model @see Model\Config\Config) * - The Config-Repository (per Config-Repository @see Config )
*/ */
abstract class BaseConfig implements IConfig abstract class AbstractConfig implements IManageConfigValues
{ {
/** /**
* @var Cache * @var Cache
@ -39,24 +39,24 @@ abstract class BaseConfig implements IConfig
protected $configCache; protected $configCache;
/** /**
* @var \Friendica\Core\Config\Model\Config * @var Config
*/ */
protected $configModel; protected $configRepo;
/** /**
* @param Cache $configCache The configuration cache (based on the config-files) * @param Cache $configCache The configuration cache (based on the config-files)
* @param \Friendica\Core\Config\Model\Config $configModel The configuration model * @param Config $configRepo The configuration repository
*/ */
public function __construct(Cache $configCache, \Friendica\Core\Config\Model\Config $configModel) public function __construct(Cache $configCache, Config $configRepo)
{ {
$this->configCache = $configCache; $this->configCache = $configCache;
$this->configModel = $configModel; $this->configRepo = $configRepo;
} }
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public function getCache() public function getCache(): Cache
{ {
return $this->configCache; return $this->configCache;
} }

View file

@ -21,8 +21,8 @@
namespace Friendica\Core\Config\Type; namespace Friendica\Core\Config\Type;
use Friendica\Core\Config\Cache\Cache; use Friendica\Core\Config\ValueObject\Cache;
use Friendica\Core\Config\Model\Config; use Friendica\Core\Config\Repository\Config;
/** /**
* This class implements the Just-In-Time configuration, which will cache * This class implements the Just-In-Time configuration, which will cache
@ -31,7 +31,7 @@ use Friendica\Core\Config\Model\Config;
* Default Configuration type. * Default Configuration type.
* Provides the best performance for pages loading few configuration variables. * Provides the best performance for pages loading few configuration variables.
*/ */
class JitConfig extends BaseConfig class JitConfig extends AbstractConfig
{ {
/** /**
* @var array Array of already loaded db values (even if there was no value) * @var array Array of already loaded db values (even if there was no value)
@ -40,11 +40,11 @@ class JitConfig extends BaseConfig
/** /**
* @param Cache $configCache The configuration cache (based on the config-files) * @param Cache $configCache The configuration cache (based on the config-files)
* @param Config $configModel The configuration model * @param Config $configRepo The configuration model
*/ */
public function __construct(Cache $configCache, Config $configModel) public function __construct(Cache $configCache, Config $configRepo)
{ {
parent::__construct($configCache, $configModel); parent::__construct($configCache, $configRepo);
$this->db_loaded = []; $this->db_loaded = [];
$this->load(); $this->load();
@ -52,16 +52,15 @@ class JitConfig extends BaseConfig
/** /**
* {@inheritDoc} * {@inheritDoc}
*
*/ */
public function load(string $cat = 'config') public function load(string $cat = 'config')
{ {
// If not connected, do nothing // If not connected, do nothing
if (!$this->configModel->isConnected()) { if (!$this->configRepo->isConnected()) {
return; return;
} }
$config = $this->configModel->load($cat); $config = $this->configRepo->load($cat);
if (!empty($config[$cat])) { if (!empty($config[$cat])) {
foreach ($config[$cat] as $key => $value) { foreach ($config[$cat] as $key => $value) {
@ -79,15 +78,14 @@ class JitConfig extends BaseConfig
public function get(string $cat, string $key, $default_value = null, bool $refresh = false) public function get(string $cat, string $key, $default_value = null, bool $refresh = false)
{ {
// if the value isn't loaded or refresh is needed, load it to the cache // if the value isn't loaded or refresh is needed, load it to the cache
if ($this->configModel->isConnected() && if ($this->configRepo->isConnected() &&
(empty($this->db_loaded[$cat][$key]) || (empty($this->db_loaded[$cat][$key]) ||
$refresh)) { $refresh)) {
$dbValue = $this->configRepo->get($cat, $key);
$dbvalue = $this->configModel->get($cat, $key); if (isset($dbValue)) {
$this->configCache->set($cat, $key, $dbValue, Cache::SOURCE_DB);
if (isset($dbvalue)) { unset($dbValue);
$this->configCache->set($cat, $key, $dbvalue, Cache::SOURCE_DB);
unset($dbvalue);
} }
$this->db_loaded[$cat][$key] = true; $this->db_loaded[$cat][$key] = true;
@ -102,17 +100,17 @@ class JitConfig extends BaseConfig
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public function set(string $cat, string $key, $value) public function set(string $cat, string $key, $value): bool
{ {
// set the cache first // set the cache first
$cached = $this->configCache->set($cat, $key, $value, Cache::SOURCE_DB); $cached = $this->configCache->set($cat, $key, $value, Cache::SOURCE_DB);
// If there is no connected adapter, we're finished // If there is no connected adapter, we're finished
if (!$this->configModel->isConnected()) { if (!$this->configRepo->isConnected()) {
return $cached; return $cached;
} }
$stored = $this->configModel->set($cat, $key, $value); $stored = $this->configRepo->set($cat, $key, $value);
$this->db_loaded[$cat][$key] = $stored; $this->db_loaded[$cat][$key] = $stored;
@ -122,7 +120,7 @@ class JitConfig extends BaseConfig
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public function delete(string $cat, string $key) public function delete(string $cat, string $key): bool
{ {
$cacheRemoved = $this->configCache->delete($cat, $key); $cacheRemoved = $this->configCache->delete($cat, $key);
@ -130,11 +128,11 @@ class JitConfig extends BaseConfig
unset($this->db_loaded[$cat][$key]); unset($this->db_loaded[$cat][$key]);
} }
if (!$this->configModel->isConnected()) { if (!$this->configRepo->isConnected()) {
return $cacheRemoved; return $cacheRemoved;
} }
$storeRemoved = $this->configModel->delete($cat, $key); $storeRemoved = $this->configRepo->delete($cat, $key);
return $cacheRemoved || $storeRemoved; return $cacheRemoved || $storeRemoved;
} }

View file

@ -21,8 +21,8 @@
namespace Friendica\Core\Config\Type; namespace Friendica\Core\Config\Type;
use Friendica\Core\Config\Cache\Cache; use Friendica\Core\Config\ValueObject\Cache;
use Friendica\Core\Config\Model\Config; use Friendica\Core\Config\Repository\Config;
/** /**
* This class implements the preload configuration, which will cache * This class implements the preload configuration, which will cache
@ -30,18 +30,18 @@ use Friendica\Core\Config\Model\Config;
* *
* Minimizes the number of database queries to retrieve configuration values at the cost of memory. * Minimizes the number of database queries to retrieve configuration values at the cost of memory.
*/ */
class PreloadConfig extends BaseConfig class PreloadConfig extends AbstractConfig
{ {
/** @var bool */ /** @var bool */
private $config_loaded; private $config_loaded;
/** /**
* @param Cache $configCache The configuration cache (based on the config-files) * @param Cache $configCache The configuration cache (based on the config-files)
* @param Config $configModel The configuration model * @param Config $configRepo The configuration model
*/ */
public function __construct(Cache $configCache, Config $configModel) public function __construct(Cache $configCache, Config $configRepo)
{ {
parent::__construct($configCache, $configModel); parent::__construct($configCache, $configRepo);
$this->config_loaded = false; $this->config_loaded = false;
$this->load(); $this->load();
@ -51,7 +51,6 @@ class PreloadConfig extends BaseConfig
* {@inheritDoc} * {@inheritDoc}
* *
* This loads all config values everytime load is called * This loads all config values everytime load is called
*
*/ */
public function load(string $cat = 'config') public function load(string $cat = 'config')
{ {
@ -61,11 +60,11 @@ class PreloadConfig extends BaseConfig
} }
// If not connected, do nothing // If not connected, do nothing
if (!$this->configModel->isConnected()) { if (!$this->configRepo->isConnected()) {
return; return;
} }
$config = $this->configModel->load(); $config = $this->configRepo->load();
$this->config_loaded = true; $this->config_loaded = true;
// load the whole category out of the DB into the cache // load the whole category out of the DB into the cache
@ -78,8 +77,8 @@ class PreloadConfig extends BaseConfig
public function get(string $cat, string $key, $default_value = null, bool $refresh = false) public function get(string $cat, string $key, $default_value = null, bool $refresh = false)
{ {
if ($refresh) { if ($refresh) {
if ($this->configModel->isConnected()) { if ($this->configRepo->isConnected()) {
$config = $this->configModel->get($cat, $key); $config = $this->configRepo->get($cat, $key);
if (isset($config)) { if (isset($config)) {
$this->configCache->set($cat, $key, $config, Cache::SOURCE_DB); $this->configCache->set($cat, $key, $config, Cache::SOURCE_DB);
} }
@ -95,7 +94,7 @@ class PreloadConfig extends BaseConfig
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public function set(string $cat, string $key, $value) public function set(string $cat, string $key, $value): bool
{ {
if (!$this->config_loaded) { if (!$this->config_loaded) {
$this->load(); $this->load();
@ -105,11 +104,11 @@ class PreloadConfig extends BaseConfig
$cached = $this->configCache->set($cat, $key, $value, Cache::SOURCE_DB); $cached = $this->configCache->set($cat, $key, $value, Cache::SOURCE_DB);
// If there is no connected adapter, we're finished // If there is no connected adapter, we're finished
if (!$this->configModel->isConnected()) { if (!$this->configRepo->isConnected()) {
return $cached; return $cached;
} }
$stored = $this->configModel->set($cat, $key, $value); $stored = $this->configRepo->set($cat, $key, $value);
return $cached && $stored; return $cached && $stored;
} }
@ -117,7 +116,7 @@ class PreloadConfig extends BaseConfig
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public function delete(string $cat, string $key) public function delete(string $cat, string $key): bool
{ {
if ($this->config_loaded) { if ($this->config_loaded) {
$this->load(); $this->load();
@ -125,26 +124,12 @@ class PreloadConfig extends BaseConfig
$cacheRemoved = $this->configCache->delete($cat, $key); $cacheRemoved = $this->configCache->delete($cat, $key);
if (!$this->configModel->isConnected()) { if (!$this->configRepo->isConnected()) {
return $cacheRemoved; return $cacheRemoved;
} }
$storeRemoved = $this->configModel->delete($cat, $key); $storeRemoved = $this->configRepo->delete($cat, $key);
return $cacheRemoved || $storeRemoved; return $cacheRemoved || $storeRemoved;
} }
public function testSetDouble()
{
$this->configModel->shouldReceive('isConnected')
->andReturn(true);
// constructor loading
$this->configModel->shouldReceive('load')
->with('config')
->andReturn(['config' => ['test' => 'it']])
->once();
parent::testSetDouble();
}
} }

View file

@ -19,11 +19,11 @@
* *
*/ */
namespace Friendica\Core\Config\Cache; namespace Friendica\Core\Config\Util;
use Exception;
use Friendica\Core\Addon; use Friendica\Core\Addon;
use Friendica\Core\Config\Cache\Cache; use Friendica\Core\Config\Exception\ConfigFileException;
use Friendica\Core\Config\ValueObject\Cache;
/** /**
* The ConfigFileLoader loads config-files and stores them in a ConfigCache ( @see Cache ) * The ConfigFileLoader loads config-files and stores them in a ConfigCache ( @see Cache )
@ -91,7 +91,7 @@ class ConfigFileLoader
* @param array $server The $_SERVER array * @param array $server The $_SERVER array
* @param bool $raw Setup the raw config format * @param bool $raw Setup the raw config format
* *
* @throws Exception * @throws ConfigFileException
*/ */
public function setupCache(Cache $config, array $server = [], bool $raw = false) public function setupCache(Cache $config, array $server = [], bool $raw = false)
{ {
@ -122,9 +122,9 @@ class ConfigFileLoader
* *
* @return array The config array (empty if no config found) * @return array The config array (empty if no config found)
* *
* @throws Exception if the configuration file isn't readable * @throws ConfigFileException if the configuration file isn't readable
*/ */
private function loadStaticConfig($name) private function loadStaticConfig(string $name): array
{ {
$configName = $this->staticDir . DIRECTORY_SEPARATOR . $name . '.config.php'; $configName = $this->staticDir . DIRECTORY_SEPARATOR . $name . '.config.php';
$iniName = $this->staticDir . DIRECTORY_SEPARATOR . $name . '.ini.php'; $iniName = $this->staticDir . DIRECTORY_SEPARATOR . $name . '.ini.php';
@ -143,9 +143,7 @@ class ConfigFileLoader
* *
* @param Cache $config The Config cache * @param Cache $config The Config cache
* *
* @return array The config array (empty if no config found) * @throws ConfigFileException if the configuration file isn't readable
*
* @throws Exception if the configuration file isn't readable
*/ */
private function loadCoreConfig(Cache $config) private function loadCoreConfig(Cache $config)
{ {
@ -158,8 +156,6 @@ class ConfigFileLoader
foreach ($this->getConfigFiles() as $configFile) { foreach ($this->getConfigFiles() as $configFile) {
$config->load($this->loadConfigFile($configFile), Cache::SOURCE_FILE); $config->load($this->loadConfigFile($configFile), Cache::SOURCE_FILE);
} }
return [];
} }
/** /**
@ -169,9 +165,9 @@ class ConfigFileLoader
* *
* @return array The config array (empty if no config found) * @return array The config array (empty if no config found)
* *
* @throws Exception if the configuration file isn't readable * @throws ConfigFileException if the configuration file isn't readable
*/ */
public function loadAddonConfig($name) public function loadAddonConfig(string $name): array
{ {
$filepath = $this->baseDir . DIRECTORY_SEPARATOR . // /var/www/html/ $filepath = $this->baseDir . DIRECTORY_SEPARATOR . // /var/www/html/
Addon::DIRECTORY . DIRECTORY_SEPARATOR . // addon/ Addon::DIRECTORY . DIRECTORY_SEPARATOR . // addon/
@ -193,9 +189,9 @@ class ConfigFileLoader
* *
* @return array The config array (empty if no config was found) * @return array The config array (empty if no config was found)
* *
* @throws Exception if the configuration file isn't readable * @throws ConfigFileException if the configuration file isn't readable
*/ */
public function loadEnvConfig(array $server) public function loadEnvConfig(array $server): array
{ {
$filepath = $this->staticDir . DIRECTORY_SEPARATOR . // /var/www/html/static/ $filepath = $this->staticDir . DIRECTORY_SEPARATOR . // /var/www/html/static/
"env.config.php"; // env.config.php "env.config.php"; // env.config.php
@ -224,10 +220,10 @@ class ConfigFileLoader
* *
* @return array * @return array
*/ */
private function getConfigFiles(bool $ini = false) private function getConfigFiles(bool $ini = false): array
{ {
$files = scandir($this->configDir); $files = scandir($this->configDir);
$found = array(); $found = [];
$filePattern = ($ini ? '*.ini.php' : '*.config.php'); $filePattern = ($ini ? '*.ini.php' : '*.config.php');
@ -252,7 +248,7 @@ class ConfigFileLoader
* *
* @deprecated since version 2018.09 * @deprecated since version 2018.09
*/ */
private function loadLegacyConfig($name = '') private function loadLegacyConfig(string $name = ''): array
{ {
$name = !empty($name) ? $name : self::CONFIG_HTCONFIG; $name = !empty($name) ? $name : self::CONFIG_HTCONFIG;
$fullName = $this->baseDir . DIRECTORY_SEPARATOR . '.' . $name . '.php'; $fullName = $this->baseDir . DIRECTORY_SEPARATOR . '.' . $name . '.php';
@ -322,17 +318,17 @@ class ConfigFileLoader
* @param string $filepath * @param string $filepath
* *
* @return array The configuration array * @return array The configuration array
* @throws Exception * @throws ConfigFileException
* @deprecated since version 2018.12 * @deprecated since version 2018.12
*/ */
private function loadINIConfigFile($filepath) private function loadINIConfigFile(string $filepath): array
{ {
$contents = include($filepath); $contents = include($filepath);
$config = parse_ini_string($contents, true, INI_SCANNER_TYPED); $config = parse_ini_string($contents, true, INI_SCANNER_TYPED);
if ($config === false) { if ($config === false) {
throw new Exception('Error parsing INI config file ' . $filepath); throw new ConfigFileException('Error parsing INI config file ' . $filepath);
} }
return $config; return $config;
@ -353,14 +349,14 @@ class ConfigFileLoader
* *
* @return array The config array0 * @return array The config array0
* *
* @throws Exception if the config cannot get loaded. * @throws ConfigFileException if the config cannot get loaded.
*/ */
private function loadConfigFile($filepath) private function loadConfigFile(string $filepath): array
{ {
$config = include($filepath); $config = include($filepath);
if (!is_array($config)) { if (!is_array($config)) {
throw new Exception('Error loading config file ' . $filepath); throw new ConfigFileException('Error loading config file ' . $filepath);
} }
return $config; return $config;

View file

@ -1,8 +1,11 @@
<?php <?php
namespace Friendica\Core\Config\Model; namespace Friendica\Core\Config\Util;
class DbaUtils /**
* Util class to help to convert from/to (p)config values
*/
class ValueConversion
{ {
/** /**
* Formats a DB value to a config value * Formats a DB value to a config value
@ -13,11 +16,11 @@ class DbaUtils
* *
* Keep in mind that there aren't any numeric/integer config values in the database * Keep in mind that there aren't any numeric/integer config values in the database
* *
* @param null|string $value * @param string|null $value
* *
* @return null|array|string * @return null|array|string
*/ */
public static function toConfigValue($value) public static function toConfigValue(?string $value)
{ {
if (!isset($value)) { if (!isset($value)) {
return null; return null;

View file

@ -19,8 +19,9 @@
* *
*/ */
namespace Friendica\Core\Config\Cache; namespace Friendica\Core\Config\ValueObject;
use Friendica\Core\Config\Util\ConfigFileLoader;
use ParagonIE\HiddenString\HiddenString; use ParagonIE\HiddenString\HiddenString;
/** /**
@ -45,7 +46,7 @@ class Cache
/** /**
* @var array * @var array
*/ */
private $config; private $config = [];
/** /**
* @var int[][] * @var int[][]
@ -97,11 +98,11 @@ class Cache
* Gets a value from the config cache. * Gets a value from the config cache.
* *
* @param string $cat Config category * @param string $cat Config category
* @param string $key Config key * @param string|null $key Config key
* *
* @return null|mixed Returns the value of the Config entry or null if not set * @return null|mixed Returns the value of the Config entry or null if not set
*/ */
public function get(string $cat, string $key = null) public function get(string $cat, ?string $key = null)
{ {
if (isset($this->config[$cat][$key])) { if (isset($this->config[$cat][$key])) {
return $this->config[$cat][$key]; return $this->config[$cat][$key];
@ -122,7 +123,7 @@ class Cache
* *
* @return bool True, if the value is set * @return bool True, if the value is set
*/ */
public function set(string $cat, string $key, $value, $source = self::SOURCE_DEFAULT) public function set(string $cat, string $key, $value, int $source = self::SOURCE_DEFAULT): bool
{ {
if (!isset($this->config[$cat])) { if (!isset($this->config[$cat])) {
$this->config[$cat] = []; $this->config[$cat] = [];
@ -155,7 +156,7 @@ class Cache
* *
* @return bool true, if deleted * @return bool true, if deleted
*/ */
public function delete(string $cat, string $key) public function delete(string $cat, string $key): bool
{ {
if (isset($this->config[$cat][$key])) { if (isset($this->config[$cat][$key])) {
unset($this->config[$cat][$key]); unset($this->config[$cat][$key]);
@ -173,9 +174,9 @@ class Cache
/** /**
* Returns the whole configuration * Returns the whole configuration
* *
* @return array The configuration * @return string[][] The configuration
*/ */
public function getAll() public function getAll(): array
{ {
return $this->config; return $this->config;
} }
@ -183,11 +184,11 @@ class Cache
/** /**
* Returns an array with missing categories/Keys * Returns an array with missing categories/Keys
* *
* @param array $config The array to check * @param string[][] $config The array to check
* *
* @return array * @return string[][]
*/ */
public function keyDiff(array $config) public function keyDiff(array $config): array
{ {
$return = []; $return = [];

View file

@ -23,7 +23,7 @@ namespace Friendica\Core;
use DOMDocument; use DOMDocument;
use Exception; use Exception;
use Friendica\Core\Config\Cache\Cache; use Friendica\Core\Config\ValueObject\Cache;
use Friendica\Database\Database; use Friendica\Database\Database;
use Friendica\Database\DBStructure; use Friendica\Database\DBStructure;
use Friendica\DI; use Friendica\DI;
@ -678,7 +678,7 @@ class Installer
/** /**
* Setup the default cache for a new installation * Setup the default cache for a new installation
* *
* @param \Friendica\Core\Config\Cache\Cache $configCache The configuration cache * @param \Friendica\Core\Config\ValueObject\Cache $configCache The configuration cache
* @param string $basePath The determined basepath * @param string $basePath The determined basepath
* *
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException

View file

@ -21,8 +21,8 @@
namespace Friendica\Core; namespace Friendica\Core;
use Friendica\Core\Config\IConfig; use Friendica\Core\Config\Capability\IManageConfigValues;
use Friendica\Core\Session\ISession; use Friendica\Core\Session\Capability\IHandleSessions;
use Friendica\Database\Database; use Friendica\Database\Database;
use Friendica\Util\Strings; use Friendica\Util\Strings;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
@ -62,7 +62,7 @@ class L10n
*/ */
private $logger; private $logger;
public function __construct(IConfig $config, Database $dba, LoggerInterface $logger, ISession $session, array $server, array $get) public function __construct(IManageConfigValues $config, Database $dba, LoggerInterface $logger, IHandleSessions $session, array $server, array $get)
{ {
$this->dba = $dba; $this->dba = $dba;
$this->logger = $logger; $this->logger = $logger;
@ -85,7 +85,7 @@ class L10n
/** /**
* Sets the language session variable * Sets the language session variable
*/ */
private function setSessionVariable(ISession $session) private function setSessionVariable(IHandleSessions $session)
{ {
if ($session->get('authenticated') && !$session->get('language')) { if ($session->get('authenticated') && !$session->get('language')) {
$session->set('language', $this->lang); $session->set('language', $this->lang);
@ -103,7 +103,7 @@ class L10n
} }
} }
private function setLangFromSession(ISession $session) private function setLangFromSession(IHandleSessions $session)
{ {
if ($session->get('language') !== $this->lang) { if ($session->get('language') !== $this->lang) {
$this->loadTranslationTable($session->get('language')); $this->loadTranslationTable($session->get('language'));

View file

@ -19,23 +19,22 @@
* *
*/ */
namespace Friendica\Core\Lock; namespace Friendica\Core\Lock\Capability;
use Friendica\Core\Cache\Enum\Duration; use Friendica\Core\Cache\Enum\Duration;
use Friendica\Core\Lock\Exception\LockPersistenceException;
/** /**
* Lock Interface * Lock Interface
*/ */
interface ILock interface ICanLock
{ {
/** /**
* Checks, if a key is currently locked to a or my process * Checks, if a key is currently locked to a or my process
* *
* @param string $key The name of the lock * @param string $key The name of the lock
*
* @return bool
*/ */
public function isLocked($key); public function isLocked(string $key): bool;
/** /**
* *
@ -45,9 +44,9 @@ interface ILock
* @param integer $timeout Seconds until we give up * @param integer $timeout Seconds until we give up
* @param integer $ttl Seconds The lock lifespan, must be one of the Cache constants * @param integer $ttl Seconds The lock lifespan, must be one of the Cache constants
* *
* @return boolean Was the lock successful? * @throws LockPersistenceException In case the underlying persistence throws errors
*/ */
public function acquire($key, $timeout = 120, $ttl = Duration::FIVE_MINUTES); public function acquire(string $key, int $timeout = 120, int $ttl = Duration::FIVE_MINUTES): bool;
/** /**
* Releases a lock if it was set by us * Releases a lock if it was set by us
@ -55,32 +54,36 @@ interface ILock
* @param string $key The Name of the lock * @param string $key The Name of the lock
* @param bool $override Overrides the lock to get released * @param bool $override Overrides the lock to get released
* *
* @return boolean Was the unlock successful? * @return bool Was the unlock successful?
*
* @throws LockPersistenceException In case the underlying persistence throws errors
*/ */
public function release($key, $override = false); public function release(string $key, bool $override = false): bool;
/** /**
* Releases all lock that were set by us * Releases all lock that were set by us
* *
* @param bool $override Override to release all locks * @param bool $override Override to release all locks
* *
* @return boolean Was the unlock of all locks successful? * @return bool Was the unlock of all locks successful?
*
* @throws LockPersistenceException In case the underlying persistence throws errors
*/ */
public function releaseAll($override = false); public function releaseAll(bool $override = false): bool;
/** /**
* Returns the name of the current lock * Returns the name of the current lock
*
* @return string
*/ */
public function getName(); public function getName(): string;
/** /**
* Lists all locks * Lists all locks
* *
* @param string prefix optional a prefix to search * @param string prefix optional a prefix to search
* *
* @return array Empty if it isn't supported by the cache driver * @return string[] Empty if it isn't supported by the cache driver
*
* @throws LockPersistenceException In case the underlying persistence throws errors
*/ */
public function getLocks(string $prefix = ''); public function getLocks(string $prefix = ''): array;
} }

View file

@ -0,0 +1,13 @@
<?php
namespace Friendica\Core\Lock\Exception;
use Throwable;
class InvalidLockDriverException extends \RuntimeException
{
public function __construct($message = "", Throwable $previous = null)
{
parent::__construct($message, 500, $previous);
}
}

View file

@ -0,0 +1,13 @@
<?php
namespace Friendica\Core\Lock\Exception;
use Throwable;
class LockPersistenceException extends \RuntimeException
{
public function __construct($message = "", Throwable $previous = null)
{
parent::__construct($message, 500, $previous);
}
}

View file

@ -21,11 +21,12 @@
namespace Friendica\Core\Lock\Factory; namespace Friendica\Core\Lock\Factory;
use Friendica\Core\Cache\Factory\CacheFactory; use Friendica\Core\Cache\Factory\Cache;
use Friendica\Core\Cache\IMemoryCache; use Friendica\Core\Cache\Capability\ICanCacheInMemory;
use Friendica\Core\Cache\Enum\Type; use Friendica\Core\Cache\Enum;
use Friendica\Core\Config\IConfig; use Friendica\Core\Config\Capability\IManageConfigValues;
use Friendica\Core\Lock; use Friendica\Core\Lock\Capability\ICanLock;
use Friendica\Core\Lock\Type;
use Friendica\Database\Database; use Friendica\Database\Database;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
@ -36,7 +37,7 @@ use Psr\Log\LoggerInterface;
* *
* A basic class to generate a LockDriver * A basic class to generate a LockDriver
*/ */
class LockFactory class Lock
{ {
/** /**
* @var string The default driver for caching * @var string The default driver for caching
@ -44,7 +45,7 @@ class LockFactory
const DEFAULT_DRIVER = 'default'; const DEFAULT_DRIVER = 'default';
/** /**
* @var IConfig The configuration to read parameters out of the config * @var IManageConfigValues The configuration to read parameters out of the config
*/ */
private $config; private $config;
@ -54,7 +55,7 @@ class LockFactory
private $dba; private $dba;
/** /**
* @var CacheFactory The memory cache driver in case we use it * @var Cache The memory cache driver in case we use it
*/ */
private $cacheFactory; private $cacheFactory;
@ -63,7 +64,7 @@ class LockFactory
*/ */
private $logger; private $logger;
public function __construct(CacheFactory $cacheFactory, IConfig $config, Database $dba, LoggerInterface $logger) public function __construct(Cache $cacheFactory, IManageConfigValues $config, Database $dba, LoggerInterface $logger)
{ {
$this->cacheFactory = $cacheFactory; $this->cacheFactory = $cacheFactory;
$this->config = $config; $this->config = $config;
@ -77,24 +78,24 @@ class LockFactory
try { try {
switch ($lock_type) { switch ($lock_type) {
case Type::MEMCACHE: case Enum\Type::MEMCACHE:
case Type::MEMCACHED: case Enum\Type::MEMCACHED:
case Type::REDIS: case Enum\Type::REDIS:
case Type::APCU: case Enum\Type::APCU:
$cache = $this->cacheFactory->create($lock_type); $cache = $this->cacheFactory->create($lock_type);
if ($cache instanceof IMemoryCache) { if ($cache instanceof ICanCacheInMemory) {
return new Lock\Type\CacheLock($cache); return new Type\CacheLock($cache);
} else { } else {
throw new \Exception(sprintf('Incompatible cache driver \'%s\' for lock used', $lock_type)); throw new \Exception(sprintf('Incompatible cache driver \'%s\' for lock used', $lock_type));
} }
break; break;
case 'database': case 'database':
return new Lock\Type\DatabaseLock($this->dba); return new Type\DatabaseLock($this->dba);
break; break;
case 'semaphore': case 'semaphore':
return new Lock\Type\SemaphoreLock(); return new Type\SemaphoreLock();
break; break;
default: default:
@ -114,14 +115,14 @@ class LockFactory
* 2. Cache Locking * 2. Cache Locking
* 3. Database Locking * 3. Database Locking
* *
* @return Lock\ILock * @return ICanLock
*/ */
private function useAutoDriver() private function useAutoDriver()
{ {
// 1. Try to use Semaphores for - local - locking // 1. Try to use Semaphores for - local - locking
if (function_exists('sem_get')) { if (function_exists('sem_get')) {
try { try {
return new Lock\Type\SemaphoreLock(); return new Type\SemaphoreLock();
} catch (\Exception $exception) { } catch (\Exception $exception) {
$this->logger->warning('Using Semaphore driver for locking failed.', ['exception' => $exception]); $this->logger->warning('Using Semaphore driver for locking failed.', ['exception' => $exception]);
} }
@ -129,11 +130,11 @@ class LockFactory
// 2. Try to use Cache Locking (don't use the DB-Cache Locking because it works different!) // 2. Try to use Cache Locking (don't use the DB-Cache Locking because it works different!)
$cache_type = $this->config->get('system', 'cache_driver', 'database'); $cache_type = $this->config->get('system', 'cache_driver', 'database');
if ($cache_type != Type::DATABASE) { if ($cache_type != Enum\Type::DATABASE) {
try { try {
$cache = $this->cacheFactory->create($cache_type); $cache = $this->cacheFactory->create($cache_type);
if ($cache instanceof IMemoryCache) { if ($cache instanceof ICanCacheInMemory) {
return new Lock\Type\CacheLock($cache); return new Type\CacheLock($cache);
} }
} catch (\Exception $exception) { } catch (\Exception $exception) {
$this->logger->warning('Using Cache driver for locking failed.', ['exception' => $exception]); $this->logger->warning('Using Cache driver for locking failed.', ['exception' => $exception]);
@ -141,6 +142,6 @@ class LockFactory
} }
// 3. Use Database Locking as a Fallback // 3. Use Database Locking as a Fallback
return new Lock\Type\DatabaseLock($this->dba); return new Type\DatabaseLock($this->dba);
} }
} }

View file

@ -21,12 +21,12 @@
namespace Friendica\Core\Lock\Type; namespace Friendica\Core\Lock\Type;
use Friendica\Core\Lock\ILock; use Friendica\Core\Lock\Capability\ICanLock;
/** /**
* Basic class for Locking with common functions (local acquired locks, releaseAll, ..) * Basic class for Locking with common functions (local acquired locks, releaseAll, ..)
*/ */
abstract class BaseLock implements ILock abstract class AbstractLock implements ICanLock
{ {
/** /**
* @var array The local acquired locks * @var array The local acquired locks
@ -40,7 +40,7 @@ abstract class BaseLock implements ILock
* *
* @return bool Returns true if the lock is set * @return bool Returns true if the lock is set
*/ */
protected function hasAcquiredLock($key) protected function hasAcquiredLock(string $key): bool
{ {
return isset($this->acquireLock[$key]) && $this->acquiredLocks[$key] === true; return isset($this->acquireLock[$key]) && $this->acquiredLocks[$key] === true;
} }
@ -50,7 +50,7 @@ abstract class BaseLock implements ILock
* *
* @param string $key The Name of the lock * @param string $key The Name of the lock
*/ */
protected function markAcquire($key) protected function markAcquire(string $key)
{ {
$this->acquiredLocks[$key] = true; $this->acquiredLocks[$key] = true;
} }
@ -60,7 +60,7 @@ abstract class BaseLock implements ILock
* *
* @param string $key The Name of the lock * @param string $key The Name of the lock
*/ */
protected function markRelease($key) protected function markRelease(string $key)
{ {
unset($this->acquiredLocks[$key]); unset($this->acquiredLocks[$key]);
} }
@ -68,7 +68,7 @@ abstract class BaseLock implements ILock
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public function releaseAll($override = false) public function releaseAll(bool $override = false): bool
{ {
$return = true; $return = true;

View file

@ -21,10 +21,13 @@
namespace Friendica\Core\Lock\Type; namespace Friendica\Core\Lock\Type;
use Friendica\Core\Cache\Capability\ICanCache;
use Friendica\Core\Cache\Capability\ICanCacheInMemory;
use Friendica\Core\Cache\Enum\Duration; use Friendica\Core\Cache\Enum\Duration;
use Friendica\Core\Cache\IMemoryCache; use Friendica\Core\Cache\Exception\CachePersistenceException;
use Friendica\Core\Lock\Exception\LockPersistenceException;
class CacheLock extends BaseLock class CacheLock extends AbstractLock
{ {
/** /**
* @var string The static prefix of all locks inside the cache * @var string The static prefix of all locks inside the cache
@ -32,16 +35,16 @@ class CacheLock extends BaseLock
const CACHE_PREFIX = 'lock:'; const CACHE_PREFIX = 'lock:';
/** /**
* @var \Friendica\Core\Cache\ICache; * @var ICanCache;
*/ */
private $cache; private $cache;
/** /**
* CacheLock constructor. * CacheLock constructor.
* *
* @param IMemoryCache $cache The CacheDriver for this type of lock * @param ICanCacheInMemory $cache The CacheDriver for this type of lock
*/ */
public function __construct(IMemoryCache $cache) public function __construct(ICanCacheInMemory $cache)
{ {
$this->cache = $cache; $this->cache = $cache;
} }
@ -49,15 +52,16 @@ class CacheLock extends BaseLock
/** /**
* (@inheritdoc) * (@inheritdoc)
*/ */
public function acquire($key, $timeout = 120, $ttl = Duration::FIVE_MINUTES) public function acquire(string $key, int $timeout = 120, int $ttl = Duration::FIVE_MINUTES): bool
{ {
$got_lock = false; $got_lock = false;
$start = time(); $start = time();
$cachekey = self::getLockKey($key); $lockKey = self::getLockKey($key);
try {
do { do {
$lock = $this->cache->get($cachekey); $lock = $this->cache->get($lockKey);
// When we do want to lock something that was already locked by us. // When we do want to lock something that was already locked by us.
if ((int)$lock == getmypid()) { if ((int)$lock == getmypid()) {
$got_lock = true; $got_lock = true;
@ -66,9 +70,9 @@ class CacheLock extends BaseLock
// When we do want to lock something new // When we do want to lock something new
if (is_null($lock)) { if (is_null($lock)) {
// At first initialize it with "0" // At first initialize it with "0"
$this->cache->add($cachekey, 0); $this->cache->add($lockKey, 0);
// Now the value has to be "0" because otherwise the key was used by another process meanwhile // Now the value has to be "0" because otherwise the key was used by another process meanwhile
if ($this->cache->compareSet($cachekey, 0, getmypid(), $ttl)) { if ($this->cache->compareSet($lockKey, 0, getmypid(), $ttl)) {
$got_lock = true; $got_lock = true;
$this->markAcquire($key); $this->markAcquire($key);
} }
@ -78,6 +82,9 @@ class CacheLock extends BaseLock
usleep(rand(10000, 200000)); usleep(rand(10000, 200000));
} }
} while (!$got_lock && ((time() - $start) < $timeout)); } while (!$got_lock && ((time() - $start) < $timeout));
} catch (CachePersistenceException $exception) {
throw new LockPersistenceException(sprintf('Cannot acquire lock for key %s', $key), $exception);
}
return $got_lock; return $got_lock;
} }
@ -85,14 +92,18 @@ class CacheLock extends BaseLock
/** /**
* (@inheritdoc) * (@inheritdoc)
*/ */
public function release($key, $override = false) public function release(string $key, bool $override = false): bool
{ {
$cachekey = self::getLockKey($key); $lockKey = self::getLockKey($key);
try {
if ($override) { if ($override) {
$return = $this->cache->delete($cachekey); $return = $this->cache->delete($lockKey);
} else { } else {
$return = $this->cache->compareDelete($cachekey, getmypid()); $return = $this->cache->compareDelete($lockKey, getmypid());
}
} catch (CachePersistenceException $exception) {
throw new LockPersistenceException(sprintf('Cannot release lock for key %s (override %b)', $key, $override), $exception);
} }
$this->markRelease($key); $this->markRelease($key);
@ -102,17 +113,21 @@ class CacheLock extends BaseLock
/** /**
* (@inheritdoc) * (@inheritdoc)
*/ */
public function isLocked($key) public function isLocked(string $key): bool
{ {
$cachekey = self::getLockKey($key); $lockKey = self::getLockKey($key);
$lock = $this->cache->get($cachekey); try {
$lock = $this->cache->get($lockKey);
} catch (CachePersistenceException $exception) {
throw new LockPersistenceException(sprintf('Cannot check lock state for key %s', $key), $exception);
}
return isset($lock) && ($lock !== false); return isset($lock) && ($lock !== false);
} }
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public function getName() public function getName(): string
{ {
return $this->cache->getName(); return $this->cache->getName();
} }
@ -120,11 +135,15 @@ class CacheLock extends BaseLock
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public function getLocks(string $prefix = '') public function getLocks(string $prefix = ''): array
{ {
try {
$locks = $this->cache->getAllKeys(self::CACHE_PREFIX . $prefix); $locks = $this->cache->getAllKeys(self::CACHE_PREFIX . $prefix);
} catch (CachePersistenceException $exception) {
throw new LockPersistenceException(sprintf('Cannot get locks with prefix %s', $prefix), $exception);
}
array_walk($locks, function (&$lock, $key) { array_walk($locks, function (&$lock) {
$lock = substr($lock, strlen(self::CACHE_PREFIX)); $lock = substr($lock, strlen(self::CACHE_PREFIX));
}); });
@ -134,7 +153,7 @@ class CacheLock extends BaseLock
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public function releaseAll($override = false) public function releaseAll(bool $override = false): bool
{ {
$success = parent::releaseAll($override); $success = parent::releaseAll($override);
@ -154,7 +173,7 @@ class CacheLock extends BaseLock
* *
* @return string The cache key used for the cache * @return string The cache key used for the cache
*/ */
private static function getLockKey($key) private static function getLockKey(string $key): string
{ {
return self::CACHE_PREFIX . $key; return self::CACHE_PREFIX . $key;
} }

View file

@ -23,13 +23,14 @@ namespace Friendica\Core\Lock\Type;
use Friendica\Core\Cache\Enum\Duration; use Friendica\Core\Cache\Enum\Duration;
use Friendica\Core\Lock\Enum\Type; use Friendica\Core\Lock\Enum\Type;
use Friendica\Core\Lock\Exception\LockPersistenceException;
use Friendica\Database\Database; use Friendica\Database\Database;
use Friendica\Util\DateTimeFormat; use Friendica\Util\DateTimeFormat;
/** /**
* Locking driver that stores the locks in the database * Locking driver that stores the locks in the database
*/ */
class DatabaseLock extends BaseLock class DatabaseLock extends AbstractLock
{ {
/** /**
* The current ID of the process * The current ID of the process
@ -44,25 +45,28 @@ class DatabaseLock extends BaseLock
private $dba; private $dba;
/** /**
* @param null|int $pid The Id of the current process (null means determine automatically) * @param int|null $pid The id of the current process (null means determine automatically)
*/ */
public function __construct(Database $dba, $pid = null) public function __construct(Database $dba, ?int $pid = null)
{ {
$this->dba = $dba; $this->dba = $dba;
$this->pid = isset($pid) ? $pid : getmypid(); $this->pid = $pid ?? getmypid();
} }
/** /**
* (@inheritdoc) * (@inheritdoc)
*/ */
public function acquire($key, $timeout = 120, $ttl = Duration::FIVE_MINUTES) public function acquire(string $key, int $timeout = 120, int $ttl = Duration::FIVE_MINUTES): bool
{ {
$got_lock = false; $got_lock = false;
$start = time(); $start = time();
try {
do { do {
$this->dba->lock('locks'); $this->dba->lock('locks');
$lock = $this->dba->selectFirst('locks', ['locked', 'pid'], ['`name` = ? AND `expires` >= ?', $key, DateTimeFormat::utcNow()]); $lock = $this->dba->selectFirst('locks', ['locked', 'pid'], [
'`name` = ? AND `expires` >= ?', $key,DateTimeFormat::utcNow()
]);
if ($this->dba->isResult($lock)) { if ($this->dba->isResult($lock)) {
if ($lock['locked']) { if ($lock['locked']) {
@ -72,11 +76,19 @@ class DatabaseLock extends BaseLock
} }
} }
if (!$lock['locked']) { if (!$lock['locked']) {
$this->dba->update('locks', ['locked' => true, 'pid' => $this->pid, 'expires' => DateTimeFormat::utc('now + ' . $ttl . 'seconds')], ['name' => $key]); $this->dba->update('locks', [
'locked' => true,
'pid' => $this->pid,
'expires' => DateTimeFormat::utc('now + ' . $ttl . 'seconds')
], ['name' => $key]);
$got_lock = true; $got_lock = true;
} }
} else { } else {
$this->dba->insert('locks', ['name' => $key, 'locked' => true, 'pid' => $this->pid, 'expires' => DateTimeFormat::utc('now + ' . $ttl . 'seconds')]); $this->dba->insert('locks', [
'name' => $key,
'locked' => true,
'pid' => $this->pid,
'expires' => DateTimeFormat::utc('now + ' . $ttl . 'seconds')]);
$got_lock = true; $got_lock = true;
$this->markAcquire($key); $this->markAcquire($key);
} }
@ -87,6 +99,9 @@ class DatabaseLock extends BaseLock
usleep(rand(100000, 2000000)); usleep(rand(100000, 2000000));
} }
} while (!$got_lock && ((time() - $start) < $timeout)); } while (!$got_lock && ((time() - $start) < $timeout));
} catch (\Exception $exception) {
throw new LockPersistenceException(sprintf('Cannot acquire lock for key %s', $key), $exception);
}
return $got_lock; return $got_lock;
} }
@ -94,7 +109,7 @@ class DatabaseLock extends BaseLock
/** /**
* (@inheritdoc) * (@inheritdoc)
*/ */
public function release($key, $override = false) public function release(string $key, bool $override = false): bool
{ {
if ($override) { if ($override) {
$where = ['name' => $key]; $where = ['name' => $key];
@ -102,11 +117,15 @@ class DatabaseLock extends BaseLock
$where = ['name' => $key, 'pid' => $this->pid]; $where = ['name' => $key, 'pid' => $this->pid];
} }
try {
if ($this->dba->exists('locks', $where)) { if ($this->dba->exists('locks', $where)) {
$return = $this->dba->delete('locks', $where); $return = $this->dba->delete('locks', $where);
} else { } else {
$return = false; $return = false;
} }
} catch (\Exception $exception) {
throw new LockPersistenceException(sprintf('Cannot release lock for key %s (override %b)', $key, $override), $exception);
}
$this->markRelease($key); $this->markRelease($key);
@ -116,7 +135,7 @@ class DatabaseLock extends BaseLock
/** /**
* (@inheritdoc) * (@inheritdoc)
*/ */
public function releaseAll($override = false) public function releaseAll(bool $override = false): bool
{ {
$success = parent::releaseAll($override); $success = parent::releaseAll($override);
@ -125,7 +144,12 @@ class DatabaseLock extends BaseLock
} else { } else {
$where = ['pid' => $this->pid]; $where = ['pid' => $this->pid];
} }
try {
$return = $this->dba->delete('locks', $where); $return = $this->dba->delete('locks', $where);
} catch (\Exception $exception) {
throw new LockPersistenceException(sprintf('Cannot release all lock (override %b)', $override), $exception);
}
$this->acquiredLocks = []; $this->acquiredLocks = [];
@ -135,9 +159,14 @@ class DatabaseLock extends BaseLock
/** /**
* (@inheritdoc) * (@inheritdoc)
*/ */
public function isLocked($key) public function isLocked(string $key): bool
{ {
$lock = $this->dba->selectFirst('locks', ['locked'], ['`name` = ? AND `expires` >= ?', $key, DateTimeFormat::utcNow()]); try {
$lock = $this->dba->selectFirst('locks', ['locked'], [
'`name` = ? AND `expires` >= ?', $key, DateTimeFormat::utcNow()]);
} catch (\Exception $exception) {
throw new LockPersistenceException(sprintf('Cannot check lock state for key %s', $key), $exception);
}
if ($this->dba->isResult($lock)) { if ($this->dba->isResult($lock)) {
return $lock['locked'] !== false; return $lock['locked'] !== false;
@ -149,7 +178,7 @@ class DatabaseLock extends BaseLock
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public function getName() public function getName(): string
{ {
return Type::DATABASE; return Type::DATABASE;
} }
@ -157,8 +186,9 @@ class DatabaseLock extends BaseLock
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public function getLocks(string $prefix = '') public function getLocks(string $prefix = ''): array
{ {
try {
if (empty($prefix)) { if (empty($prefix)) {
$where = ['`expires` >= ?', DateTimeFormat::utcNow()]; $where = ['`expires` >= ?', DateTimeFormat::utcNow()];
} else { } else {
@ -171,7 +201,11 @@ class DatabaseLock extends BaseLock
while ($key = $this->dba->fetch($stmt)) { while ($key = $this->dba->fetch($stmt)) {
array_push($keys, $key['name']); array_push($keys, $key['name']);
} }
} catch (\Exception $exception) {
throw new LockPersistenceException(sprintf('Cannot get lock with prefix %s', $prefix), $exception);
} finally {
$this->dba->close($stmt); $this->dba->close($stmt);
}
return $keys; return $keys;
} }

View file

@ -23,16 +23,17 @@ namespace Friendica\Core\Lock\Type;
use Friendica\Core\Cache\Enum\Duration; use Friendica\Core\Cache\Enum\Duration;
use Friendica\Core\Lock\Enum\Type; use Friendica\Core\Lock\Enum\Type;
use Friendica\Core\Lock\Exception\InvalidLockDriverException;
use function get_temppath; use function get_temppath;
class SemaphoreLock extends BaseLock class SemaphoreLock extends AbstractLock
{ {
private static $semaphore = []; private static $semaphore = [];
public function __construct() public function __construct()
{ {
if (!function_exists('sem_get')) { if (!function_exists('sem_get')) {
throw new \Exception('Semaphore lock not supported'); throw new InvalidLockDriverException('Semaphore lock not supported');
} }
} }
@ -57,11 +58,11 @@ class SemaphoreLock extends BaseLock
/** /**
* (@inheritdoc) * (@inheritdoc)
*/ */
public function acquire($key, $timeout = 120, $ttl = Duration::FIVE_MINUTES) public function acquire(string $key, int $timeout = 120, int $ttl = Duration::FIVE_MINUTES): bool
{ {
self::$semaphore[$key] = sem_get(self::semaphoreKey($key)); self::$semaphore[$key] = sem_get(self::semaphoreKey($key));
if (!empty(self::$semaphore[$key])) { if (!empty(self::$semaphore[$key])) {
if ((bool)sem_acquire(self::$semaphore[$key], ($timeout === 0))) { if (sem_acquire(self::$semaphore[$key], ($timeout === 0))) {
$this->markAcquire($key); $this->markAcquire($key);
return true; return true;
} }
@ -76,7 +77,7 @@ class SemaphoreLock extends BaseLock
* @param bool $override not necessary parameter for semaphore locks since the lock lives as long as the execution * @param bool $override not necessary parameter for semaphore locks since the lock lives as long as the execution
* of the using function * of the using function
*/ */
public function release($key, $override = false) public function release(string $key, bool $override = false): bool
{ {
$success = false; $success = false;
@ -96,7 +97,7 @@ class SemaphoreLock extends BaseLock
/** /**
* (@inheritdoc) * (@inheritdoc)
*/ */
public function isLocked($key) public function isLocked(string $key): bool
{ {
return isset(self::$semaphore[$key]); return isset(self::$semaphore[$key]);
} }
@ -104,7 +105,7 @@ class SemaphoreLock extends BaseLock
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public function getName() public function getName(): string
{ {
return Type::SEMAPHORE; return Type::SEMAPHORE;
} }
@ -112,7 +113,7 @@ class SemaphoreLock extends BaseLock
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public function getLocks(string $prefix = '') public function getLocks(string $prefix = ''): array
{ {
// We can just return our own semaphore keys, since we don't know // We can just return our own semaphore keys, since we don't know
// the state of other semaphores, even if the .sem files exists // the state of other semaphores, even if the .sem files exists
@ -136,7 +137,7 @@ class SemaphoreLock extends BaseLock
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public function releaseAll($override = false) public function releaseAll(bool $override = false): bool
{ {
// Semaphores are just alive during a run, so there is no need to release // Semaphores are just alive during a run, so there is no need to release
// You can just release your own locks // You can just release your own locks

View file

@ -19,16 +19,15 @@
* *
*/ */
namespace Friendica\Core\PConfig; namespace Friendica\Core\PConfig\Capability;
use Friendica\Core\Config\Cache\Cache; use Friendica\Core\PConfig\ValueObject;
/** /**
* Interface for accessing user specific configurations * Interface for accessing user specific configurations
*/ */
interface IPConfig interface IManagePersonalConfigValues
{ {
/** /**
* Loads all configuration values of a user's config family into a cached storage. * Loads all configuration values of a user's config family into a cached storage.
* *
@ -38,18 +37,16 @@ interface IPConfig
* @param string $cat The category of the configuration value * @param string $cat The category of the configuration value
* *
* @return array The loaded config array * @return array The loaded config array
* @see Cache
*
*/ */
function load(int $uid, string $cat = 'config'); public function load(int $uid, string $cat = 'config'): array;
/** /**
* Get a particular user's config variable given the category name * Get a particular user's config variable given the category name
* ($cat) and a key. * ($cat) and a key.
* *
* Get a particular user's config value from the given category ($cat) * Get a particular user's config value from the given category ($cat)
* and the $key with the $uid from a cached storage either from the $this->configAdapter * and the $key with the $uid from a cached storage either from the database
* (@see IConfigAdapter) or from the $this->configCache (@see PConfigCache). * or from the configCache
* *
* @param int $uid The user_id * @param int $uid The user_id
* @param string $cat The category of the configuration value * @param string $cat The category of the configuration value
@ -58,8 +55,9 @@ interface IPConfig
* @param boolean $refresh optional, If true the config is loaded from the db and not from the cache (default: false) * @param boolean $refresh optional, If true the config is loaded from the db and not from the cache (default: false)
* *
* @return mixed Stored value or null if it does not exist * @return mixed Stored value or null if it does not exist
*
*/ */
function get(int $uid, string $cat, string $key, $default_value = null, bool $refresh = false); public function get(int $uid, string $cat, string $key, $default_value = null, bool $refresh = false);
/** /**
* Sets a configuration value for a user * Sets a configuration value for a user
@ -76,14 +74,12 @@ interface IPConfig
* *
* @return bool Operation success * @return bool Operation success
*/ */
function set(int $uid, string $cat, string $key, $value); public function set(int $uid, string $cat, string $key, $value): bool;
/** /**
* Deletes the given key from the users's configuration. * Deletes the given key from the users configuration.
* *
* Removes the configured value from the stored cache in $this->configCache * Removes the configured value from the stored cache and removes it from the database with the given $uid.
* (@see ConfigCache) and removes it from the database (@see IConfigAdapter)
* with the given $uid.
* *
* @param int $uid The user_id * @param int $uid The user_id
* @param string $cat The category of the configuration value * @param string $cat The category of the configuration value
@ -91,13 +87,13 @@ interface IPConfig
* *
* @return bool * @return bool
*/ */
function delete(int $uid, string $cat, string $key); public function delete(int $uid, string $cat, string $key): bool;
/** /**
* Returns the Config Cache * Returns the Config Cache
* *
* @return \Friendica\Core\PConfig\Cache\Cache * @return ValueObject\Cache
*/ */
function getCache(); public function getCache(): ValueObject\Cache;
} }

View file

@ -0,0 +1,13 @@
<?php
namespace Friendica\Core\PConfig\Exception;
use Throwable;
class PConfigPersistenceException extends \RuntimeException
{
public function __construct($message = "", Throwable $previous = null)
{
parent::__construct($message, 500, $previous);
}
}

View file

@ -21,26 +21,27 @@
namespace Friendica\Core\PConfig\Factory; namespace Friendica\Core\PConfig\Factory;
use Friendica\Core\Config\Cache\Cache; use Friendica\Core\Config\ValueObject\Cache;
use Friendica\Core\PConfig\IPConfig; use Friendica\Core\PConfig\Capability\IManagePersonalConfigValues;
use Friendica\Core\PConfig\Model\PConfig as PConfigModel; use Friendica\Core\PConfig\Repository;
use Friendica\Core\PConfig\Type; use Friendica\Core\PConfig\Type;
use Friendica\Core\PConfig\ValueObject;
class PConfigFactory class PConfig
{ {
/** /**
* @param Cache $configCache The config cache * @param Cache $configCache The config cache
* @param \Friendica\Core\PConfig\Cache\Cache $pConfigCache The personal config cache * @param ValueObject\Cache $pConfigCache The personal config cache
* @param PConfigModel $configModel The configuration model * @param Repository\PConfig $configRepo The configuration model
* *
* @return IPConfig * @return IManagePersonalConfigValues
*/ */
public function create(Cache $configCache, \Friendica\Core\PConfig\Cache\Cache $pConfigCache, PConfigModel $configModel) public function create(Cache $configCache, ValueObject\Cache $pConfigCache, Repository\PConfig $configRepo): IManagePersonalConfigValues
{ {
if ($configCache->get('system', 'config_adapter') === 'preload') { if ($configCache->get('system', 'config_adapter') === 'preload') {
$configuration = new Type\PreloadPConfig($pConfigCache, $configModel); $configuration = new Type\PreloadPConfig($pConfigCache, $configRepo);
} else { } else {
$configuration = new Type\JitPConfig($pConfigCache, $configModel); $configuration = new Type\JitPConfig($pConfigCache, $configRepo);
} }
return $configuration; return $configuration;

View file

@ -19,9 +19,10 @@
* *
*/ */
namespace Friendica\Core\PConfig\Model; namespace Friendica\Core\PConfig\Repository;
use Friendica\Core\Config\Model\DbaUtils; use Friendica\Core\Config\Util\ValueConversion;
use Friendica\Core\PConfig\Exception\PConfigPersistenceException;
use Friendica\Database\Database; use Friendica\Database\Database;
/** /**
@ -29,15 +30,14 @@ use Friendica\Database\Database;
*/ */
class PConfig class PConfig
{ {
/** @var Database */ protected static $table_name = 'pconfig';
protected $dba;
/** /** @var Database */
* @param Database $dba The database connection of this model protected $db;
*/
public function __construct(Database $dba) public function __construct(Database $db)
{ {
$this->dba = $dba; $this->db = $db;
} }
/** /**
@ -45,9 +45,9 @@ class PConfig
* *
* @return bool * @return bool
*/ */
public function isConnected() public function isConnected(): bool
{ {
return $this->dba->isConnected(); return $this->db->isConnected();
} }
/** /**
@ -56,30 +56,35 @@ class PConfig
* @param int $uid The id of the user to load * @param int $uid The id of the user to load
* @param string|null $cat The category of the configuration values to load * @param string|null $cat The category of the configuration values to load
* *
* @return array The config array * @return string[][] The config array
* *
* @throws \Exception In case DB calls are invalid * @throws PConfigPersistenceException In case the persistence layer throws errors
*/ */
public function load(int $uid, string $cat = null) public function load(int $uid, ?string $cat = null): array
{ {
$return = []; $return = [];
try {
if (empty($cat)) { if (empty($cat)) {
$configs = $this->dba->select('pconfig', ['cat', 'v', 'k'], ['uid' => $uid]); $configs = $this->db->select(static::$table_name, ['cat', 'v', 'k'], ['uid' => $uid]);
} else { } else {
$configs = $this->dba->select('pconfig', ['cat', 'v', 'k'], ['cat' => $cat, 'uid' => $uid]); $configs = $this->db->select(static::$table_name, ['cat', 'v', 'k'], ['cat' => $cat, 'uid' => $uid]);
} }
while ($config = $this->dba->fetch($configs)) { while ($config = $this->db->fetch($configs)) {
$key = $config['k']; $key = $config['k'];
$value = DbaUtils::toConfigValue($config['v']); $value = ValueConversion::toConfigValue($config['v']);
// just save it in case it is set // just save it in case it is set
if (isset($value)) { if (isset($value)) {
$return[$config['cat']][$key] = $value; $return[$config['cat']][$key] = $value;
} }
} }
$this->dba->close($configs); } catch (\Exception $exception) {
throw new PConfigPersistenceException(sprintf('Cannot load config category %s for user %d', $cat, $uid), $exception);
} finally {
$this->db->close($configs);
}
return $return; return $return;
} }
@ -96,7 +101,7 @@ class PConfig
* *
* @return array|string|null Stored value or null if it does not exist * @return array|string|null Stored value or null if it does not exist
* *
* @throws \Exception In case DB calls are invalid * @throws PConfigPersistenceException In case the persistence layer throws errors
*/ */
public function get(int $uid, string $cat, string $key) public function get(int $uid, string $cat, string $key)
{ {
@ -104,15 +109,19 @@ class PConfig
return null; return null;
} }
$config = $this->dba->selectFirst('pconfig', ['v'], ['uid' => $uid, 'cat' => $cat, 'k' => $key]); try {
if ($this->dba->isResult($config)) { $config = $this->db->selectFirst('pconfig', ['v'], ['uid' => $uid, 'cat' => $cat, 'k' => $key]);
$value = DbaUtils::toConfigValue($config['v']); if ($this->db->isResult($config)) {
$value = ValueConversion::toConfigValue($config['v']);
// just return it in case it is set // just return it in case it is set
if (isset($value)) { if (isset($value)) {
return $value; return $value;
} }
} }
} catch (\Exception $exception) {
throw new PConfigPersistenceException(sprintf('Cannot get config value for category %s, key %s and user %d', $cat, $key, $uid), $exception);
}
return null; return null;
} }
@ -130,9 +139,9 @@ class PConfig
* *
* @return bool Operation success * @return bool Operation success
* *
* @throws \Exception In case DB calls are invalid * @throws PConfigPersistenceException In case the persistence layer throws errors
*/ */
public function set(int $uid, string $cat, string $key, $value) public function set(int $uid, string $cat, string $key, $value): bool
{ {
if (!$this->isConnected()) { if (!$this->isConnected()) {
return false; return false;
@ -148,11 +157,12 @@ class PConfig
return true; return true;
} }
$dbvalue = DbaUtils::toDbValue($value); try {
$dbValue = ValueConversion::toDbValue($value);
$result = $this->dba->update('pconfig', ['v' => $dbvalue], ['uid' => $uid, 'cat' => $cat, 'k' => $key], true); return $this->db->update(static::$table_name, ['v' => $dbValue], ['uid' => $uid, 'cat' => $cat, 'k' => $key], true);
} catch (\Exception $exception) {
return $result; throw new PConfigPersistenceException(sprintf('Cannot set config value for category %s, key %s and user %d', $cat, $key, $uid), $exception);
}
} }
/** /**
@ -164,14 +174,18 @@ class PConfig
* *
* @return bool Operation success * @return bool Operation success
* *
* @throws \Exception In case DB calls are invalid * @throws PConfigPersistenceException In case the persistence layer throws errors
*/ */
public function delete(int $uid, string $cat, string $key) public function delete(int $uid, string $cat, string $key): bool
{ {
if (!$this->isConnected()) { if (!$this->isConnected()) {
return false; return false;
} }
return $this->dba->delete('pconfig', ['uid' => $uid, 'cat' => $cat, 'k' => $key]); try {
return $this->db->delete('pconfig', ['uid' => $uid, 'cat' => $cat, 'k' => $key]);
} catch (\Exception $exception) {
throw new PConfigPersistenceException(sprintf('Cannot delete config value for category %s, key %s and user %d', $cat, $key, $uid), $exception);
}
} }
} }

View file

@ -21,45 +21,45 @@
namespace Friendica\Core\PConfig\Type; namespace Friendica\Core\PConfig\Type;
use Friendica\Core\PConfig\Cache\Cache; use Friendica\Core\PConfig\Repository;
use Friendica\Core\PConfig\IPConfig; use Friendica\Core\PConfig\ValueObject\Cache;
use Friendica\Model; use Friendica\Core\PConfig\Capability\IManagePersonalConfigValues;
/** /**
* This class is responsible for the user-specific configuration values in Friendica * This class is responsible for the user-specific configuration values in Friendica
* The values are set through the Config-DB-Table (per Config-DB-model @see Model\Config\PConfig) * The values are set through the Config-DB-Table (per Config-DB-model @see Repository\PConfig)
* *
* The configuration cache (@see Cache\PConfigCache) is used for temporary caching of database calls. This will * The configuration cache (@see Cache) is used for temporary caching of database calls. This will
* increase the performance. * increase the performance.
*/ */
abstract class BasePConfig implements IPConfig abstract class AbstractPConfigValues implements IManagePersonalConfigValues
{ {
/** /**
* @var \Friendica\Core\PConfig\Cache\Cache * @var Cache
*/ */
protected $configCache; protected $configCache;
/** /**
* @var \Friendica\Core\PConfig\Model\PConfig * @var Repository\PConfig
*/ */
protected $configModel; protected $configModel;
/** /**
* @param \Friendica\Core\PConfig\Cache\Cache $configCache The configuration cache * @param Cache $configCache The configuration cache
* @param \Friendica\Core\PConfig\Model\PConfig $configModel The configuration model * @param Repository\PConfig $configRepo The configuration model
*/ */
public function __construct(Cache $configCache, \Friendica\Core\PConfig\Model\PConfig $configModel) public function __construct(Cache $configCache, Repository\PConfig $configRepo)
{ {
$this->configCache = $configCache; $this->configCache = $configCache;
$this->configModel = $configModel; $this->configModel = $configRepo;
} }
/** /**
* Returns the Config Cache * Returns the Config Cache
* *
* @return \Friendica\Core\PConfig\Cache\Cache * @return Cache
*/ */
public function getCache() public function getCache(): Cache
{ {
return $this->configCache; return $this->configCache;
} }

View file

@ -21,8 +21,8 @@
namespace Friendica\Core\PConfig\Type; namespace Friendica\Core\PConfig\Type;
use Friendica\Core\PConfig\Cache\Cache; use Friendica\Core\PConfig\Repository;
use Friendica\Model; use Friendica\Core\PConfig\ValueObject;
/** /**
* This class implements the Just-In-Time configuration, which will cache * This class implements the Just-In-Time configuration, which will cache
@ -31,7 +31,7 @@ use Friendica\Model;
* Default Configuration type. * Default Configuration type.
* Provides the best performance for pages loading few configuration variables. * Provides the best performance for pages loading few configuration variables.
*/ */
class JitPConfig extends BasePConfig class JitPConfig extends AbstractPConfigValues
{ {
/** /**
* @var array Array of already loaded db values (even if there was no value) * @var array Array of already loaded db values (even if there was no value)
@ -39,12 +39,12 @@ class JitPConfig extends BasePConfig
private $db_loaded; private $db_loaded;
/** /**
* @param Cache $configCache The configuration cache * @param ValueObject\Cache $configCache The configuration cache
* @param \Friendica\Core\PConfig\Model\PConfig $configModel The configuration model * @param Repository\PConfig $configRepo The configuration model
*/ */
public function __construct(Cache $configCache, \Friendica\Core\PConfig\Model\PConfig $configModel) public function __construct(ValueObject\Cache $configCache, Repository\PConfig $configRepo)
{ {
parent::__construct($configCache, $configModel); parent::__construct($configCache, $configRepo);
$this->db_loaded = []; $this->db_loaded = [];
} }
@ -52,11 +52,11 @@ class JitPConfig extends BasePConfig
* {@inheritDoc} * {@inheritDoc}
* *
*/ */
public function load(int $uid, string $cat = 'config') public function load(int $uid, string $cat = 'config'): array
{ {
// If not connected or no uid, do nothing // If not connected or no uid, do nothing
if (!$uid || !$this->configModel->isConnected()) { if (!$uid || !$this->configModel->isConnected()) {
return; return [];
} }
$config = $this->configModel->load($uid, $cat); $config = $this->configModel->load($uid, $cat);
@ -84,14 +84,12 @@ class JitPConfig extends BasePConfig
// if the value isn't loaded or refresh is needed, load it to the cache // if the value isn't loaded or refresh is needed, load it to the cache
if ($this->configModel->isConnected() && if ($this->configModel->isConnected() &&
(empty($this->db_loaded[$uid][$cat][$key]) || (empty($this->db_loaded[$uid][$cat][$key]) || $refresh)) {
$refresh)) { $dbValue = $this->configModel->get($uid, $cat, $key);
$dbvalue = $this->configModel->get($uid, $cat, $key); if (isset($dbValue)) {
$this->configCache->set($uid, $cat, $key, $dbValue);
if (isset($dbvalue)) { unset($dbValue);
$this->configCache->set($uid, $cat, $key, $dbvalue);
unset($dbvalue);
} }
$this->db_loaded[$uid][$cat][$key] = true; $this->db_loaded[$uid][$cat][$key] = true;
@ -106,7 +104,7 @@ class JitPConfig extends BasePConfig
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public function set(int $uid, string $cat, string $key, $value) public function set(int $uid, string $cat, string $key, $value): bool
{ {
if (!$uid) { if (!$uid) {
return false; return false;
@ -130,7 +128,7 @@ class JitPConfig extends BasePConfig
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public function delete(int $uid, string $cat, string $key) public function delete(int $uid, string $cat, string $key): bool
{ {
if (!$uid) { if (!$uid) {
return false; return false;

View file

@ -21,8 +21,8 @@
namespace Friendica\Core\PConfig\Type; namespace Friendica\Core\PConfig\Type;
use Friendica\Core\PConfig\Cache\Cache; use Friendica\Core\PConfig\Repository;
use Friendica\Model; use Friendica\Core\PConfig\ValueObject;
/** /**
* This class implements the preload configuration, which will cache * This class implements the preload configuration, which will cache
@ -30,18 +30,18 @@ use Friendica\Model;
* *
* Minimizes the number of database queries to retrieve configuration values at the cost of memory. * Minimizes the number of database queries to retrieve configuration values at the cost of memory.
*/ */
class PreloadPConfig extends BasePConfig class PreloadPConfig extends AbstractPConfigValues
{ {
/** @var array */ /** @var array */
private $config_loaded; private $config_loaded;
/** /**
* @param \Friendica\Core\PConfig\Cache\Cache $configCache The configuration cache * @param ValueObject\Cache $configCache The configuration cache
* @param \Friendica\Core\PConfig\Model\PConfig $configModel The configuration model * @param Repository\PConfig $configRepo The configuration model
*/ */
public function __construct(Cache $configCache, \Friendica\Core\PConfig\Model\PConfig $configModel) public function __construct(ValueObject\Cache $configCache, Repository\PConfig $configRepo)
{ {
parent::__construct($configCache, $configModel); parent::__construct($configCache, $configRepo);
$this->config_loaded = []; $this->config_loaded = [];
} }
@ -51,16 +51,16 @@ class PreloadPConfig extends BasePConfig
* This loads all config values everytime load is called * This loads all config values everytime load is called
* *
*/ */
public function load(int $uid, string $cat = 'config') public function load(int $uid, string $cat = 'config'): array
{ {
// Don't load the whole configuration twice or with invalid uid // Don't load the whole configuration twice or with invalid uid
if (!$uid || !empty($this->config_loaded[$uid])) { if (!$uid || !empty($this->config_loaded[$uid])) {
return; return [];
} }
// If not connected, do nothing // If not connected, do nothing
if (!$this->configModel->isConnected()) { if (!$this->configModel->isConnected()) {
return; return [];
} }
$config = $this->configModel->load($uid); $config = $this->configModel->load($uid);
@ -101,7 +101,7 @@ class PreloadPConfig extends BasePConfig
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public function set(int $uid, string $cat, string $key, $value) public function set(int $uid, string $cat, string $key, $value): bool
{ {
if (!$uid) { if (!$uid) {
return false; return false;
@ -127,7 +127,7 @@ class PreloadPConfig extends BasePConfig
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public function delete(int $uid, string $cat, string $key) public function delete(int $uid, string $cat, string $key): bool
{ {
if (!$uid) { if (!$uid) {
return false; return false;

View file

@ -19,7 +19,7 @@
* *
*/ */
namespace Friendica\Core\PConfig\Cache; namespace Friendica\Core\PConfig\ValueObject;
use ParagonIE\HiddenString\HiddenString; use ParagonIE\HiddenString\HiddenString;
@ -31,7 +31,7 @@ class Cache
/** /**
* @var array * @var array
*/ */
private $config; private $config = [];
/** /**
* @var bool * @var bool
@ -53,7 +53,7 @@ class Cache
* @param int $uid * @param int $uid
* @param array $config * @param array $config
*/ */
public function load($uid, array $config) public function load(int $uid, array $config)
{ {
if (!is_int($uid)) { if (!is_int($uid)) {
return; return;
@ -63,7 +63,6 @@ class Cache
foreach ($categories as $category) { foreach ($categories as $category) {
if (isset($config[$category]) && is_array($config[$category])) { if (isset($config[$category]) && is_array($config[$category])) {
$keys = array_keys($config[$category]); $keys = array_keys($config[$category]);
foreach ($keys as $key) { foreach ($keys as $key) {
@ -81,11 +80,11 @@ class Cache
* *
* @param int $uid User Id * @param int $uid User Id
* @param string $cat Config category * @param string $cat Config category
* @param string $key Config key * @param string|null $key Config key
* *
* @return null|string The value of the config entry or null if not set * @return null|mixed The value of the config entry or null if not set
*/ */
public function get($uid, string $cat, string $key = null) public function get(int $uid, string $cat, ?string $key = null)
{ {
if (!is_int($uid)) { if (!is_int($uid)) {
return null; return null;
@ -112,7 +111,7 @@ class Cache
* *
* @return bool Set successful * @return bool Set successful
*/ */
public function set($uid, string $cat, string $key, $value) public function set(int $uid, string $cat, string $key, $value): bool
{ {
if (!is_int($uid)) { if (!is_int($uid)) {
return false; return false;
@ -147,7 +146,7 @@ class Cache
* *
* @return bool true, if deleted * @return bool true, if deleted
*/ */
public function delete($uid, string $cat, string $key) public function delete(int $uid, string $cat, string $key): bool
{ {
if (!is_int($uid)) { if (!is_int($uid)) {
return false; return false;
@ -171,9 +170,9 @@ class Cache
/** /**
* Returns the whole configuration * Returns the whole configuration
* *
* @return array The configuration * @return string[][] The configuration
*/ */
public function getAll() public function getAll(): array
{ {
return $this->config; return $this->config;
} }
@ -181,11 +180,11 @@ class Cache
/** /**
* Returns an array with missing categories/Keys * Returns an array with missing categories/Keys
* *
* @param array $config The array to check * @param string[][] $config The array to check
* *
* @return array * @return string[][]
*/ */
public function keyDiff(array $config) public function keyDiff(array $config): array
{ {
$return = []; $return = [];

View file

@ -22,7 +22,7 @@
namespace Friendica\Core; namespace Friendica\Core;
use Friendica\App; use Friendica\App;
use Friendica\Core\Config\IConfig; use Friendica\Core\Config\Capability\IManageConfigValues;
use Friendica\Model; use Friendica\Model;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
@ -48,7 +48,7 @@ class Process
private $mode; private $mode;
/** /**
* @var IConfig * @var IManageConfigValues
*/ */
private $config; private $config;
@ -67,7 +67,7 @@ class Process
*/ */
private $pid; private $pid;
public function __construct(LoggerInterface $logger, App\Mode $mode, IConfig $config, Model\Process $processModel, string $basepath, int $pid) public function __construct(LoggerInterface $logger, App\Mode $mode, IManageConfigValues $config, Model\Process $processModel, string $basepath, int $pid)
{ {
$this->logger = $logger; $this->logger = $logger;
$this->mode = $mode; $this->mode = $mode;
@ -176,7 +176,7 @@ class Process
if (count($data) != 2) { if (count($data) != 2) {
continue; continue;
} }
list($key, $val) = $data; [$key, $val] = $data;
$meminfo[$key] = (int)trim(str_replace('kB', '', $val)); $meminfo[$key] = (int)trim(str_replace('kB', '', $val));
$meminfo[$key] = (int)($meminfo[$key] / 1024); $meminfo[$key] = (int)($meminfo[$key] / 1024);
} }

View file

@ -19,19 +19,19 @@
* *
*/ */
namespace Friendica\Core\Session; namespace Friendica\Core\Session\Capability;
/** /**
* Contains all global supported Session methods * Contains all global supported Session methods
*/ */
interface ISession interface IHandleSessions
{ {
/** /**
* Start the current session * Start the current session
* *
* @return self The own Session instance * @return self The own Session instance
*/ */
public function start(); public function start(): IHandleSessions;
/** /**
* Checks if the key exists in this session * Checks if the key exists in this session
@ -40,7 +40,7 @@ interface ISession
* *
* @return boolean True, if it exists * @return boolean True, if it exists
*/ */
public function exists(string $name); public function exists(string $name): bool;
/** /**
* Retrieves a key from the session super global or the defaults if the key is missing or the value is falsy. * Retrieves a key from the session super global or the defaults if the key is missing or the value is falsy.

View file

@ -22,10 +22,12 @@
namespace Friendica\Core\Session\Factory; namespace Friendica\Core\Session\Factory;
use Friendica\App; use Friendica\App;
use Friendica\Core\Cache\ICache; use Friendica\Core\Cache\Capability\ICanCache;
use Friendica\Core\Cache\Enum\Type; use Friendica\Core\Cache\Enum;
use Friendica\Core\Config\IConfig; use Friendica\Core\Config\Capability\IManageConfigValues;
use Friendica\Core\Session; use Friendica\Core\Session\Capability\IHandleSessions;
use Friendica\Core\Session\Type;
use Friendica\Core\Session\Handler;
use Friendica\Database\Database; use Friendica\Database\Database;
use Friendica\Util\Profiler; use Friendica\Util\Profiler;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
@ -33,7 +35,7 @@ use Psr\Log\LoggerInterface;
/** /**
* Factory for creating a valid Session for this run * Factory for creating a valid Session for this run
*/ */
class SessionFactory class Session
{ {
/** @var string The plain, PHP internal session management */ /** @var string The plain, PHP internal session management */
const HANDLER_NATIVE = 'native'; const HANDLER_NATIVE = 'native';
@ -47,41 +49,42 @@ class SessionFactory
/** /**
* @param App\Mode $mode * @param App\Mode $mode
* @param App\BaseURL $baseURL * @param App\BaseURL $baseURL
* @param IConfig $config * @param IManageConfigValues $config
* @param Database $dba * @param Database $dba
* @param ICache $cache * @param ICanCache $cache
* @param LoggerInterface $logger * @param LoggerInterface $logger
* @param Profiler $profiler
* @param array $server * @param array $server
* *
* @return Session\ISession * @return IHandleSessions
*/ */
public function createSession(App\Mode $mode, App\BaseURL $baseURL, IConfig $config, Database $dba, ICache $cache, LoggerInterface $logger, Profiler $profiler, array $server = []) public function createSession(App\Mode $mode, App\BaseURL $baseURL, IManageConfigValues $config, Database $dba, ICanCache $cache, LoggerInterface $logger, Profiler $profiler, array $server = [])
{ {
$profiler->startRecording('session'); $profiler->startRecording('session');
$session = null; $session = null;
try { try {
if ($mode->isInstall() || $mode->isBackend()) { if ($mode->isInstall() || $mode->isBackend()) {
$session = new Session\Type\Memory(); $session = new Type\Memory();
} else { } else {
$session_handler = $config->get('system', 'session_handler', self::HANDLER_DEFAULT); $session_handler = $config->get('system', 'session_handler', self::HANDLER_DEFAULT);
$handler = null; $handler = null;
switch ($session_handler) { switch ($session_handler) {
case self::HANDLER_DATABASE: case self::HANDLER_DATABASE:
$handler = new Session\Handler\Database($dba, $logger, $server); $handler = new Handler\Database($dba, $logger, $server);
break; break;
case self::HANDLER_CACHE: case self::HANDLER_CACHE:
// In case we're using the db as cache driver, use the native db session, not the cache // In case we're using the db as cache driver, use the native db session, not the cache
if ($config->get('system', 'cache_driver') === Type::DATABASE) { if ($config->get('system', 'cache_driver') === Enum\Type::DATABASE) {
$handler = new Session\Handler\Database($dba, $logger, $server); $handler = new Handler\Database($dba, $logger, $server);
} else { } else {
$handler = new Session\Handler\Cache($cache); $handler = new Handler\Cache($cache, $logger);
} }
break; break;
} }
$session = new Session\Type\Native($baseURL, $handler); $session = new Type\Native($baseURL, $handler);
} }
} finally { } finally {
$profiler->stopRecording(); $profiler->stopRecording();

View file

@ -21,8 +21,10 @@
namespace Friendica\Core\Session\Handler; namespace Friendica\Core\Session\Handler;
use Friendica\Core\Cache\ICache; use Friendica\Core\Cache\Capability\ICanCache;
use Friendica\Core\Cache\Exception\CachePersistenceException;
use Friendica\Core\Session; use Friendica\Core\Session;
use Psr\Log\LoggerInterface;
use SessionHandlerInterface; use SessionHandlerInterface;
/** /**
@ -30,30 +32,38 @@ use SessionHandlerInterface;
*/ */
class Cache implements SessionHandlerInterface class Cache implements SessionHandlerInterface
{ {
/** @var ICache */ /** @var ICanCache */
private $cache; private $cache;
/** @var LoggerInterface */
private $logger;
public function __construct(ICache $cache) public function __construct(ICanCache $cache, LoggerInterface $logger)
{ {
$this->cache = $cache; $this->cache = $cache;
$this->logger = $logger;
} }
public function open($save_path, $session_name) public function open($path, $name): bool
{ {
return true; return true;
} }
public function read($session_id) public function read($id)
{ {
if (empty($session_id)) { if (empty($id)) {
return ''; return '';
} }
$data = $this->cache->get('session:' . $session_id); try {
$data = $this->cache->get('session:' . $id);
if (!empty($data)) { if (!empty($data)) {
Session::$exists = true; Session::$exists = true;
return $data; return $data;
} }
} catch (CachePersistenceException $exception) {
$this->logger->warning('Cannot read session.'. ['id' => $id, 'exception' => $exception]);
return '';
}
return ''; return '';
} }
@ -65,36 +75,45 @@ class Cache implements SessionHandlerInterface
* on the case. Uses the Session::expire for existing session, 5 minutes * on the case. Uses the Session::expire for existing session, 5 minutes
* for newly created session. * for newly created session.
* *
* @param string $session_id Session ID with format: [a-z0-9]{26} * @param string $id Session ID with format: [a-z0-9]{26}
* @param string $session_data Serialized session data * @param string $data Serialized session data
* *
* @return boolean Returns false if parameters are missing, true otherwise * @return bool Returns false if parameters are missing, true otherwise
* @throws \Exception
*/ */
public function write($session_id, $session_data) public function write($id, $data): bool
{ {
if (!$session_id) { if (!$id) {
return false; return false;
} }
if (!$session_data) { if (!$data) {
return $this->destroy($session_id); return $this->destroy($id);
} }
return $this->cache->set('session:' . $session_id, $session_data, Session::$expire); try {
return $this->cache->set('session:' . $id, $data, Session::$expire);
} catch (CachePersistenceException $exception) {
$this->logger->warning('Cannot write session', ['id' => $id, 'exception' => $exception]);
return false;
}
} }
public function close() public function close(): bool
{ {
return true; return true;
} }
public function destroy($id) public function destroy($id): bool
{ {
try {
return $this->cache->delete('session:' . $id); return $this->cache->delete('session:' . $id);
} catch (CachePersistenceException $exception) {
$this->logger->warning('Cannot destroy session', ['id' => $id, 'exception' => $exception]);
return false;
}
} }
public function gc($maxlifetime) public function gc($max_lifetime): bool
{ {
return true; return true;
} }

View file

@ -52,24 +52,29 @@ class Database implements SessionHandlerInterface
$this->server = $server; $this->server = $server;
} }
public function open($save_path, $session_name) public function open($path, $name): bool
{ {
return true; return true;
} }
public function read($session_id) public function read($id)
{ {
if (empty($session_id)) { if (empty($id)) {
return ''; return '';
} }
$session = $this->dba->selectFirst('session', ['data'], ['sid' => $session_id]); try {
$session = $this->dba->selectFirst('session', ['data'], ['sid' => $id]);
if ($this->dba->isResult($session)) { if ($this->dba->isResult($session)) {
Session::$exists = true; Session::$exists = true;
return $session['data']; return $session['data'];
} }
} catch (\Exception $exception) {
$this->logger->warning('Cannot read session.'. ['id' => $id, 'exception' => $exception]);
return '';
}
$this->logger->notice('no data for session', ['session_id' => $session_id, 'uri' => $this->server['REQUEST_URI'] ?? '']); $this->logger->notice('no data for session', ['session_id' => $id, 'uri' => $this->server['REQUEST_URI'] ?? '']);
return ''; return '';
} }
@ -81,49 +86,63 @@ class Database implements SessionHandlerInterface
* on the case. Uses the Session::expire global for existing session, 5 minutes * on the case. Uses the Session::expire global for existing session, 5 minutes
* for newly created session. * for newly created session.
* *
* @param string $session_id Session ID with format: [a-z0-9]{26} * @param string $id Session ID with format: [a-z0-9]{26}
* @param string $session_data Serialized session data * @param string $data Serialized session data
* *
* @return boolean Returns false if parameters are missing, true otherwise * @return bool Returns false if parameters are missing, true otherwise
* @throws \Exception
*/ */
public function write($session_id, $session_data) public function write($id, $data): bool
{ {
if (!$session_id) { if (!$id) {
return false; return false;
} }
if (!$session_data) { if (!$data) {
return $this->destroy($session_id); return $this->destroy($id);
} }
$expire = time() + Session::$expire; $expire = time() + Session::$expire;
$default_expire = time() + 300; $default_expire = time() + 300;
try {
if (Session::$exists) { if (Session::$exists) {
$fields = ['data' => $session_data, 'expire' => $expire]; $fields = ['data' => $data, 'expire' => $expire];
$condition = ["`sid` = ? AND (`data` != ? OR `expire` != ?)", $session_id, $session_data, $expire]; $condition = ["`sid` = ? AND (`data` != ? OR `expire` != ?)", $id, $data, $expire];
$this->dba->update('session', $fields, $condition); $this->dba->update('session', $fields, $condition);
} else { } else {
$fields = ['sid' => $session_id, 'expire' => $default_expire, 'data' => $session_data]; $fields = ['sid' => $id, 'expire' => $default_expire, 'data' => $data];
$this->dba->insert('session', $fields); $this->dba->insert('session', $fields);
} }
} catch (\Exception $exception) {
$this->logger->warning('Cannot write session.'. ['id' => $id, 'exception' => $exception]);
return false;
}
return true; return true;
} }
public function close() public function close(): bool
{ {
return true; return true;
} }
public function destroy($id) public function destroy($id): bool
{ {
try {
return $this->dba->delete('session', ['sid' => $id]); return $this->dba->delete('session', ['sid' => $id]);
} catch (\Exception $exception) {
$this->logger->warning('Cannot destroy session.'. ['id' => $id, 'exception' => $exception]);
return false;
}
} }
public function gc($maxlifetime) public function gc($max_lifetime): bool
{ {
try {
return $this->dba->delete('session', ["`expire` < ?", time()]); return $this->dba->delete('session', ["`expire` < ?", time()]);
} catch (\Exception $exception) {
$this->logger->warning('Cannot use garbage collector.'. ['exception' => $exception]);
return false;
}
} }
} }

View file

@ -21,15 +21,17 @@
namespace Friendica\Core\Session\Type; namespace Friendica\Core\Session\Type;
use Friendica\Core\Session\Capability\IHandleSessions;
/** /**
* Contains the base methods for $_SESSION interaction * Contains the base methods for $_SESSION interaction
*/ */
class AbstractSession class AbstractSession implements IHandleSessions
{ {
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public function start() public function start(): IHandleSessions
{ {
return $this; return $this;
} }
@ -37,7 +39,7 @@ class AbstractSession
/** /**
* {@inheritDoc}} * {@inheritDoc}}
*/ */
public function exists(string $name) public function exists(string $name): bool
{ {
return isset($_SESSION[$name]); return isset($_SESSION[$name]);
} }

View file

@ -21,14 +21,14 @@
namespace Friendica\Core\Session\Type; namespace Friendica\Core\Session\Type;
use Friendica\Core\Session\ISession; use Friendica\Core\Session\Capability\IHandleSessions;
/** /**
* Usable for backend processes (daemon/worker) and testing * Usable for backend processes (daemon/worker) and testing
* *
* @todo after replacing the last direct $_SESSION call, use a internal array instead of the global variable * @todo after replacing the last direct $_SESSION call, use a internal array instead of the global variable
*/ */
class Memory extends AbstractSession implements ISession class Memory extends AbstractSession implements IHandleSessions
{ {
public function __construct() public function __construct()
{ {

View file

@ -22,14 +22,14 @@
namespace Friendica\Core\Session\Type; namespace Friendica\Core\Session\Type;
use Friendica\App; use Friendica\App;
use Friendica\Core\Session\ISession; use Friendica\Core\Session\Capability\IHandleSessions;
use Friendica\Model\User\Cookie; use Friendica\Model\User\Cookie;
use SessionHandlerInterface; use SessionHandlerInterface;
/** /**
* The native Session class which uses the PHP internal Session functions * The native Session class which uses the PHP internal Session functions
*/ */
class Native extends AbstractSession implements ISession class Native extends AbstractSession implements IHandleSessions
{ {
public function __construct(App\BaseURL $baseURL, SessionHandlerInterface $handler = null) public function __construct(App\BaseURL $baseURL, SessionHandlerInterface $handler = null)
{ {
@ -49,7 +49,7 @@ class Native extends AbstractSession implements ISession
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public function start() public function start(): IHandleSessions
{ {
session_start(); session_start();
return $this; return $this;

View file

@ -22,7 +22,7 @@
namespace Friendica\Core; namespace Friendica\Core;
use Exception; use Exception;
use Friendica\Core\Config\IConfig; use Friendica\Core\Config\Capability\IManageConfigValues;
use Friendica\Database\Database; use Friendica\Database\Database;
use Friendica\Model\Storage; use Friendica\Model\Storage;
use Friendica\Network\HTTPException\InternalServerErrorException; use Friendica\Network\HTTPException\InternalServerErrorException;
@ -56,7 +56,7 @@ class StorageManager
/** @var Database */ /** @var Database */
private $dba; private $dba;
/** @var IConfig */ /** @var \Friendica\Core\Config\Capability\IManageConfigValues */
private $config; private $config;
/** @var LoggerInterface */ /** @var LoggerInterface */
private $logger; private $logger;
@ -68,14 +68,14 @@ class StorageManager
/** /**
* @param Database $dba * @param Database $dba
* @param IConfig $config * @param IManageConfigValues $config
* @param LoggerInterface $logger * @param LoggerInterface $logger
* @param L10n $l10n * @param L10n $l10n
* *
* @throws Storage\InvalidClassStorageException in case the active backend class is invalid * @throws Storage\InvalidClassStorageException in case the active backend class is invalid
* @throws Storage\StorageException in case of unexpected errors during the active backend class loading * @throws Storage\StorageException in case of unexpected errors during the active backend class loading
*/ */
public function __construct(Database $dba, IConfig $config, LoggerInterface $logger, L10n $l10n) public function __construct(Database $dba, IManageConfigValues $config, LoggerInterface $logger, L10n $l10n)
{ {
$this->dba = $dba; $this->dba = $dba;
$this->config = $config; $this->config = $config;

View file

@ -155,35 +155,35 @@ abstract class DI
// //
/** /**
* @return Core\Cache\ICache * @return \Friendica\Core\Cache\Capability\ICanCache
*/ */
public static function cache() public static function cache()
{ {
return self::$dice->create(Core\Cache\ICache::class); return self::$dice->create(Core\Cache\Capability\ICanCache::class);
} }
/** /**
* @return Core\Config\IConfig * @return \Friendica\Core\Config\Capability\IManageConfigValues
*/ */
public static function config() public static function config()
{ {
return self::$dice->create(Core\Config\IConfig::class); return self::$dice->create(Core\Config\Capability\IManageConfigValues::class);
} }
/** /**
* @return Core\PConfig\IPConfig * @return \Friendica\Core\PConfig\Capability\IManagePersonalConfigValues
*/ */
public static function pConfig() public static function pConfig()
{ {
return self::$dice->create(Core\PConfig\IPConfig::class); return self::$dice->create(Core\PConfig\Capability\IManagePersonalConfigValues::class);
} }
/** /**
* @return Core\Lock\ILock * @return \Friendica\Core\Lock\Capability\ICanLock
*/ */
public static function lock() public static function lock()
{ {
return self::$dice->create(Core\Lock\ILock::class); return self::$dice->create(Core\Lock\Capability\ICanLock::class);
} }
/** /**
@ -203,11 +203,11 @@ abstract class DI
} }
/** /**
* @return Core\Session\ISession * @return \Friendica\Core\Session\Capability\IHandleSessions
*/ */
public static function session() public static function session()
{ {
return self::$dice->create(Core\Session\ISession::class); return self::$dice->create(Core\Session\Capability\IHandleSessions::class);
} }
/** /**

View file

@ -21,7 +21,7 @@
namespace Friendica\Database; namespace Friendica\Database;
use Friendica\Core\Config\Cache\Cache; use Friendica\Core\Config\ValueObject\Cache;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Network\HTTPException\InternalServerErrorException; use Friendica\Network\HTTPException\InternalServerErrorException;
use Friendica\Util\DateTimeFormat; use Friendica\Util\DateTimeFormat;
@ -49,7 +49,7 @@ class Database
protected $connected = false; protected $connected = false;
/** /**
* @var Cache * @var \Friendica\Core\Config\ValueObject\Cache
*/ */
protected $configCache; protected $configCache;
/** /**

View file

@ -4,7 +4,7 @@ namespace Friendica\Factory;
use Friendica\App; use Friendica\App;
use Friendica\BaseFactory; use Friendica\BaseFactory;
use Friendica\Core\Config\IConfig; use Friendica\Core\Config\Capability\IManageConfigValues;
use Friendica\Network\HTTPClient; use Friendica\Network\HTTPClient;
use Friendica\Network\IHTTPClient; use Friendica\Network\IHTTPClient;
use Friendica\Util\Profiler; use Friendica\Util\Profiler;
@ -22,14 +22,14 @@ require_once __DIR__ . '/../../static/dbstructure.config.php';
class HTTPClientFactory extends BaseFactory class HTTPClientFactory extends BaseFactory
{ {
/** @var IConfig */ /** @var IManageConfigValues */
private $config; private $config;
/** @var Profiler */ /** @var Profiler */
private $profiler; private $profiler;
/** @var App\BaseURL */ /** @var App\BaseURL */
private $baseUrl; private $baseUrl;
public function __construct(LoggerInterface $logger, IConfig $config, Profiler $profiler, App\BaseURL $baseUrl) public function __construct(LoggerInterface $logger, IManageConfigValues $config, Profiler $profiler, App\BaseURL $baseUrl)
{ {
parent::__construct($logger); parent::__construct($logger);
$this->config = $config; $this->config = $config;

View file

@ -21,7 +21,7 @@
namespace Friendica\Factory; namespace Friendica\Factory;
use Friendica\Core\Config\IConfig; use Friendica\Core\Config\Capability\IManageConfigValues;
use Friendica\Core\Logger; use Friendica\Core\Logger;
use Friendica\Database\Database; use Friendica\Database\Database;
use Friendica\Network\HTTPException\InternalServerErrorException; use Friendica\Network\HTTPException\InternalServerErrorException;
@ -69,13 +69,13 @@ class LoggerFactory
* Creates a new PSR-3 compliant logger instances * Creates a new PSR-3 compliant logger instances
* *
* @param Database $database The Friendica Database instance * @param Database $database The Friendica Database instance
* @param IConfig $config The config * @param \Friendica\Core\Config\Capability\IManageConfigValues $config The config
* @param Profiler $profiler The profiler of the app * @param Profiler $profiler The profiler of the app
* @param FileSystem $fileSystem FileSystem utils * @param FileSystem $fileSystem FileSystem utils
* *
* @return LoggerInterface The PSR-3 compliant logger instance * @return LoggerInterface The PSR-3 compliant logger instance
*/ */
public function create(Database $database, IConfig $config, Profiler $profiler, FileSystem $fileSystem) public function create(Database $database, IManageConfigValues $config, Profiler $profiler, FileSystem $fileSystem)
{ {
if (empty($config->get('system', 'debugging', false))) { if (empty($config->get('system', 'debugging', false))) {
$logger = new VoidLogger(); $logger = new VoidLogger();
@ -156,7 +156,7 @@ class LoggerFactory
* *
* It should never get filled during normal usage of Friendica * It should never get filled during normal usage of Friendica
* *
* @param IConfig $config The config * @param \Friendica\Core\Config\Capability\IManageConfigValues $config The config
* @param Profiler $profiler The profiler of the app * @param Profiler $profiler The profiler of the app
* @param FileSystem $fileSystem FileSystem utils * @param FileSystem $fileSystem FileSystem utils
* *
@ -165,7 +165,7 @@ class LoggerFactory
* @throws InternalServerErrorException * @throws InternalServerErrorException
* @throws \Exception * @throws \Exception
*/ */
public static function createDev(IConfig $config, Profiler $profiler, FileSystem $fileSystem) public static function createDev(IManageConfigValues $config, Profiler $profiler, FileSystem $fileSystem)
{ {
$debugging = $config->get('system', 'debugging'); $debugging = $config->get('system', 'debugging');
$stream = $config->get('system', 'dlogfile'); $stream = $config->get('system', 'dlogfile');

View file

@ -21,7 +21,7 @@
namespace Friendica\Model\Storage; namespace Friendica\Model\Storage;
use Friendica\Core\Config\IConfig; use Friendica\Core\Config\Capability\IManageConfigValues;
use Friendica\Core\L10n; use Friendica\Core\L10n;
/** /**
@ -32,7 +32,7 @@ class FilesystemConfig implements IStorageConfiguration
// Default base folder // Default base folder
const DEFAULT_BASE_FOLDER = 'storage'; const DEFAULT_BASE_FOLDER = 'storage';
/** @var IConfig */ /** @var IManageConfigValues */
private $config; private $config;
/** @var string */ /** @var string */
@ -54,10 +54,10 @@ class FilesystemConfig implements IStorageConfiguration
/** /**
* Filesystem constructor. * Filesystem constructor.
* *
* @param IConfig $config * @param \Friendica\Core\Config\Capability\IManageConfigValues $config
* @param L10n $l10n * @param L10n $l10n
*/ */
public function __construct(IConfig $config, L10n $l10n) public function __construct(IManageConfigValues $config, L10n $l10n)
{ {
$this->config = $config; $this->config = $config;
$this->l10n = $l10n; $this->l10n = $l10n;

View file

@ -22,7 +22,7 @@
namespace Friendica\Model\User; namespace Friendica\Model\User;
use Friendica\App; use Friendica\App;
use Friendica\Core\Config\IConfig; use Friendica\Core\Config\Capability\IManageConfigValues;
/** /**
* Interacting with the Friendica Cookie of a user * Interacting with the Friendica Cookie of a user
@ -52,12 +52,12 @@ class Cookie
private $data; private $data;
/** /**
* @param IConfig $config * @param \Friendica\Core\Config\Capability\IManageConfigValues $config
* @param App\BaseURL $baseURL * @param App\BaseURL $baseURL
* @param array $SERVER The $_SERVER array * @param array $SERVER The $_SERVER array
* @param array $COOKIE The $_COOKIE array * @param array $COOKIE The $_COOKIE array
*/ */
public function __construct(IConfig $config, App\BaseURL $baseURL, array $SERVER = [], array $COOKIE = []) public function __construct(IManageConfigValues $config, App\BaseURL $baseURL, array $SERVER = [], array $COOKIE = [])
{ {
$this->sslEnabled = $baseURL->getSSLPolicy() === App\BaseURL::SSL_POLICY_FULL; $this->sslEnabled = $baseURL->getSSLPolicy() === App\BaseURL::SSL_POLICY_FULL;
$this->sitePrivateKey = $config->get('system', 'site_prvkey'); $this->sitePrivateKey = $config->get('system', 'site_prvkey');

View file

@ -22,18 +22,18 @@
namespace Friendica\Module\Admin; namespace Friendica\Module\Admin;
use Friendica\Core\Addon; use Friendica\Core\Addon;
use Friendica\Core\Config\Cache\Cache; use Friendica\Core\Config\ValueObject\Cache;
use Friendica\Core\Logger; use Friendica\Core\Logger;
use Friendica\Core\Renderer; use Friendica\Core\Renderer;
use Friendica\Core\Update; use Friendica\Core\Update;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\Database\DBStructure; use Friendica\Database\DBStructure;
use Friendica\DI; use Friendica\DI;
use Friendica\Core\Config\Factory\ConfigFactory; use Friendica\Core\Config\Factory\Config;
use Friendica\Model\Register; use Friendica\Model\Register;
use Friendica\Module\BaseAdmin; use Friendica\Module\BaseAdmin;
use Friendica\Network\HTTPException\InternalServerErrorException; use Friendica\Network\HTTPException\InternalServerErrorException;
use Friendica\Core\Config\Cache\ConfigFileLoader; use Friendica\Core\Config\Util\ConfigFileLoader;
use Friendica\Util\DateTimeFormat; use Friendica\Util\DateTimeFormat;
class Summary extends BaseAdmin class Summary extends BaseAdmin
@ -152,7 +152,7 @@ class Summary extends BaseAdmin
} }
// check legacy basepath settings // check legacy basepath settings
$configLoader = (new ConfigFactory())->createConfigFileLoader($a->getBasePath(), $_SERVER); $configLoader = (new Config())->createConfigFileLoader($a->getBasePath(), $_SERVER);
$configCache = new Cache(); $configCache = new Cache();
$configLoader->setupCache($configCache); $configLoader->setupCache($configCache);
$confBasepath = $configCache->get('system', 'basepath'); $confBasepath = $configCache->get('system', 'basepath');

View file

@ -24,7 +24,7 @@ namespace Friendica\Module;
use Friendica\App; use Friendica\App;
use Friendica\BaseModule; use Friendica\BaseModule;
use Friendica\Core; use Friendica\Core;
use Friendica\Core\Config\Cache\Cache; use Friendica\Core\Config\ValueObject\Cache;
use Friendica\Core\Renderer; use Friendica\Core\Renderer;
use Friendica\Core\Theme; use Friendica\Core\Theme;
use Friendica\DI; use Friendica\DI;
@ -371,7 +371,7 @@ class Install extends BaseModule
/** /**
* Checks the $_POST settings and updates the config Cache for it * Checks the $_POST settings and updates the config Cache for it
* *
* @param Cache $configCache The current config cache * @param \Friendica\Core\Config\ValueObject\Cache $configCache The current config cache
* @param array $post The $_POST data * @param array $post The $_POST data
* @param string $cat The category of the setting * @param string $cat The category of the setting
* @param string $key The key of the setting * @param string $key The key of the setting

View file

@ -27,9 +27,9 @@ use Friendica\App\BaseURL;
use Friendica\BaseFactory; use Friendica\BaseFactory;
use Friendica\Content\Text\BBCode; use Friendica\Content\Text\BBCode;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\PConfig\IPConfig; use Friendica\Core\PConfig\Capability\IManagePersonalConfigValues;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Core\Session\ISession; use Friendica\Core\Session\Capability\IHandleSessions;
use Friendica\Database\Database; use Friendica\Database\Database;
use Friendica\Model\Contact; use Friendica\Model\Contact;
use Friendica\Module\BaseNotifications; use Friendica\Module\BaseNotifications;
@ -51,14 +51,14 @@ class Introduction extends BaseFactory
private $baseUrl; private $baseUrl;
/** @var L10n */ /** @var L10n */
private $l10n; private $l10n;
/** @var IPConfig */ /** @var \Friendica\Core\PConfig\Capability\IManagePersonalConfigValues */
private $pConfig; private $pConfig;
/** @var ISession */ /** @var \Friendica\Core\Session\Capability\IHandleSessions */
private $session; private $session;
/** @var string */ /** @var string */
private $nick; private $nick;
public function __construct(LoggerInterface $logger, Database $dba, BaseURL $baseUrl, L10n $l10n, App $app, IPConfig $pConfig, ISession $session) public function __construct(LoggerInterface $logger, Database $dba, BaseURL $baseUrl, L10n $l10n, App $app, IManagePersonalConfigValues $pConfig, IHandleSessions $session)
{ {
parent::__construct($logger); parent::__construct($logger);

View file

@ -5,7 +5,7 @@ namespace Friendica\Navigation\Notifications\Repository;
use Friendica\App\BaseURL; use Friendica\App\BaseURL;
use Friendica\BaseRepository; use Friendica\BaseRepository;
use Friendica\Content\Text\Plaintext; use Friendica\Content\Text\Plaintext;
use Friendica\Core\Config\IConfig; use Friendica\Core\Config\Capability\IManageConfigValues;
use Friendica\Core\Hook; use Friendica\Core\Hook;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\System; use Friendica\Core\System;
@ -33,7 +33,7 @@ class Notify extends BaseRepository
/** @var BaseURL */ /** @var BaseURL */
protected $baseUrl; protected $baseUrl;
/** @var IConfig */ /** @var \Friendica\Core\Config\Capability\IManageConfigValues */
protected $config; protected $config;
/** @var Emailer */ /** @var Emailer */
@ -44,7 +44,7 @@ class Notify extends BaseRepository
protected static $table_name = 'notify'; protected static $table_name = 'notify';
public function __construct(Database $database, LoggerInterface $logger, L10n $l10n, BaseURL $baseUrl, IConfig $config, Emailer $emailer, Factory\Notification $notification, Factory\Notify $factory = null) public function __construct(Database $database, LoggerInterface $logger, L10n $l10n, BaseURL $baseUrl, IManageConfigValues $config, Emailer $emailer, Factory\Notification $notification, Factory\Notify $factory = null)
{ {
$this->l10n = $l10n; $this->l10n = $l10n;
$this->baseUrl = $baseUrl; $this->baseUrl = $baseUrl;

View file

@ -23,8 +23,8 @@ namespace Friendica\Security;
use Exception; use Exception;
use Friendica\App; use Friendica\App;
use Friendica\Core\Config\IConfig; use Friendica\Core\Config\Capability\IManageConfigValues;
use Friendica\Core\PConfig\IPConfig; use Friendica\Core\PConfig\Capability\IManagePersonalConfigValues;
use Friendica\Core\Hook; use Friendica\Core\Hook;
use Friendica\Core\Session; use Friendica\Core\Session;
use Friendica\Core\System; use Friendica\Core\System;
@ -46,7 +46,7 @@ use Psr\Log\LoggerInterface;
*/ */
class Authentication class Authentication
{ {
/** @var IConfig */ /** @var IManageConfigValues */
private $config; private $config;
/** @var App\Mode */ /** @var App\Mode */
private $mode; private $mode;
@ -60,25 +60,25 @@ class Authentication
private $logger; private $logger;
/** @var User\Cookie */ /** @var User\Cookie */
private $cookie; private $cookie;
/** @var Session\ISession */ /** @var \Friendica\Core\Session\Capability\IHandleSessions */
private $session; private $session;
/** @var IPConfig */ /** @var IManagePersonalConfigValues */
private $pConfig; private $pConfig;
/** /**
* Authentication constructor. * Authentication constructor.
* *
* @param IConfig $config * @param IManageConfigValues $config
* @param App\Mode $mode * @param App\Mode $mode
* @param App\BaseURL $baseUrl * @param App\BaseURL $baseUrl
* @param L10n $l10n * @param L10n $l10n
* @param Database $dba * @param Database $dba
* @param LoggerInterface $logger * @param LoggerInterface $logger
* @param User\Cookie $cookie * @param User\Cookie $cookie
* @param Session\ISession $session * @param \Friendica\Core\Session\Capability\IHandleSessions $session
* @param IPConfig $pConfig * @param IManagePersonalConfigValues $pConfig
*/ */
public function __construct(IConfig $config, App\Mode $mode, App\BaseURL $baseUrl, L10n $l10n, Database $dba, LoggerInterface $logger, User\Cookie $cookie, Session\ISession $session, IPConfig $pConfig) public function __construct(IManageConfigValues $config, App\Mode $mode, App\BaseURL $baseUrl, L10n $l10n, Database $dba, LoggerInterface $logger, User\Cookie $cookie, Session\Capability\IHandleSessions $session, IManagePersonalConfigValues $pConfig)
{ {
$this->config = $config; $this->config = $config;
$this->mode = $mode; $this->mode = $mode;

View file

@ -36,8 +36,8 @@ namespace Friendica\Security;
use Exception; use Exception;
use Friendica\App; use Friendica\App;
use Friendica\Core\Config\IConfig; use Friendica\Core\Config\Capability\IManageConfigValues;
use Friendica\Core\PConfig\IPConfig; use Friendica\Core\PConfig\Capability\IManagePersonalConfigValues;
use Friendica\Database\Database; use Friendica\Database\Database;
use Friendica\DI; use Friendica\DI;
use Friendica\Model\User; use Friendica\Model\User;
@ -54,11 +54,11 @@ class ExAuth
*/ */
private $appMode; private $appMode;
/** /**
* @var IConfig * @var \Friendica\Core\Config\Capability\IManageConfigValues
*/ */
private $config; private $config;
/** /**
* @var IPConfig * @var IManagePersonalConfigValues
*/ */
private $pConfig; private $pConfig;
/** /**
@ -72,13 +72,14 @@ class ExAuth
/** /**
* @param App\Mode $appMode * @param App\Mode $appMode
* @param IConfig $config * @param IManageConfigValues $config
* @param IPConfig $pConfig * @param \Friendica\Core\PConfig\Capability\IManagePersonalConfigValues $pConfig
* @param Database $dba * @param Database $dba
* @param App\BaseURL $baseURL * @param App\BaseURL $baseURL
*
* @throws Exception * @throws Exception
*/ */
public function __construct(App\Mode $appMode, IConfig $config, IPConfig $pConfig, Database $dba, App\BaseURL $baseURL) public function __construct(App\Mode $appMode, IManageConfigValues $config, IManagePersonalConfigValues $pConfig, Database $dba, App\BaseURL $baseURL)
{ {
$this->appMode = $appMode; $this->appMode = $appMode;
$this->config = $config; $this->config = $config;

View file

@ -23,7 +23,7 @@ namespace Friendica\Util\EMailer;
use Exception; use Exception;
use Friendica\App\BaseURL; use Friendica\App\BaseURL;
use Friendica\Core\Config\IConfig; use Friendica\Core\Config\Capability\IManageConfigValues;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Renderer; use Friendica\Core\Renderer;
use Friendica\Model\User; use Friendica\Model\User;
@ -42,7 +42,7 @@ abstract class MailBuilder
/** @var L10n */ /** @var L10n */
protected $l10n; protected $l10n;
/** @var IConfig */ /** @var IManageConfigValues */
protected $config; protected $config;
/** @var BaseURL */ /** @var BaseURL */
protected $baseUrl; protected $baseUrl;
@ -64,7 +64,7 @@ abstract class MailBuilder
/** @var int */ /** @var int */
protected $recipientUid = null; protected $recipientUid = null;
public function __construct(L10n $l10n, BaseURL $baseUrl, IConfig $config, LoggerInterface $logger) public function __construct(L10n $l10n, BaseURL $baseUrl, IManageConfigValues $config, LoggerInterface $logger)
{ {
$this->l10n = $l10n; $this->l10n = $l10n;
$this->baseUrl = $baseUrl; $this->baseUrl = $baseUrl;

View file

@ -24,7 +24,7 @@ namespace Friendica\Util\EMailer;
use Exception; use Exception;
use Friendica\App\BaseURL; use Friendica\App\BaseURL;
use Friendica\Content\Text\BBCode; use Friendica\Content\Text\BBCode;
use Friendica\Core\Config\IConfig; use Friendica\Core\Config\Capability\IManageConfigValues;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Renderer; use Friendica\Core\Renderer;
use Friendica\Network\HTTPException\InternalServerErrorException; use Friendica\Network\HTTPException\InternalServerErrorException;
@ -70,7 +70,7 @@ class NotifyMailBuilder extends MailBuilder
/** @var string The item link */ /** @var string The item link */
private $itemLink = ''; private $itemLink = '';
public function __construct(L10n $l10n, BaseURL $baseUrl, IConfig $config, LoggerInterface $logger, string $siteEmailAddress, string $siteName) public function __construct(L10n $l10n, BaseURL $baseUrl, IManageConfigValues $config, LoggerInterface $logger, string $siteEmailAddress, string $siteName)
{ {
parent::__construct($l10n, $baseUrl, $config, $logger); parent::__construct($l10n, $baseUrl, $config, $logger);

View file

@ -24,7 +24,7 @@ namespace Friendica\Util\EMailer;
use Exception; use Exception;
use Friendica\App\BaseURL; use Friendica\App\BaseURL;
use Friendica\Content\Text\BBCode; use Friendica\Content\Text\BBCode;
use Friendica\Core\Config\IConfig; use Friendica\Core\Config\Capability\IManageConfigValues;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Renderer; use Friendica\Core\Renderer;
use Friendica\Network\HTTPException\InternalServerErrorException; use Friendica\Network\HTTPException\InternalServerErrorException;
@ -45,7 +45,7 @@ class SystemMailBuilder extends MailBuilder
/** @var string */ /** @var string */
protected $siteAdmin; protected $siteAdmin;
public function __construct(L10n $l10n, BaseURL $baseUrl, IConfig $config, LoggerInterface $logger, public function __construct(L10n $l10n, BaseURL $baseUrl, IManageConfigValues $config, LoggerInterface $logger,
string $siteEmailAddress, string $siteName) string $siteEmailAddress, string $siteName)
{ {
parent::__construct($l10n, $baseUrl, $config, $logger); parent::__construct($l10n, $baseUrl, $config, $logger);

View file

@ -22,10 +22,10 @@
namespace Friendica\Util; namespace Friendica\Util;
use Friendica\App; use Friendica\App;
use Friendica\Core\Config\IConfig; use Friendica\Core\Config\Capability\IManageConfigValues;
use Friendica\Core\Hook; use Friendica\Core\Hook;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\PConfig\IPConfig; use Friendica\Core\PConfig\Capability\IManagePersonalConfigValues;
use Friendica\Network\HTTPException\InternalServerErrorException; use Friendica\Network\HTTPException\InternalServerErrorException;
use Friendica\Object\EMail\IEmail; use Friendica\Object\EMail\IEmail;
use Friendica\Protocol\Email; use Friendica\Protocol\Email;
@ -38,9 +38,9 @@ use Psr\Log\LoggerInterface;
*/ */
class Emailer class Emailer
{ {
/** @var IConfig */ /** @var \Friendica\Core\Config\Capability\IManageConfigValues */
private $config; private $config;
/** @var IPConfig */ /** @var \Friendica\Core\PConfig\Capability\IManagePersonalConfigValues */
private $pConfig; private $pConfig;
/** @var LoggerInterface */ /** @var LoggerInterface */
private $logger; private $logger;
@ -54,7 +54,7 @@ class Emailer
/** @var string */ /** @var string */
private $siteEmailName; private $siteEmailName;
public function __construct(IConfig $config, IPConfig $pConfig, App\BaseURL $baseURL, LoggerInterface $logger, public function __construct(IManageConfigValues $config, IManagePersonalConfigValues $pConfig, App\BaseURL $baseURL, LoggerInterface $logger,
L10n $defaultLang) L10n $defaultLang)
{ {
$this->config = $config; $this->config = $config;

View file

@ -21,8 +21,8 @@
namespace Friendica\Util; namespace Friendica\Util;
use Friendica\Core\Config\Cache\Cache; use Friendica\Core\Config\ValueObject\Cache;
use Friendica\Core\Config\IConfig; use Friendica\Core\Config\Capability\IManageConfigValues;
use Friendica\Core\System; use Friendica\Core\System;
use Psr\Container\ContainerExceptionInterface; use Psr\Container\ContainerExceptionInterface;
use Psr\Container\ContainerInterface; use Psr\Container\ContainerInterface;
@ -69,16 +69,16 @@ class Profiler implements ContainerInterface
/** /**
* Updates the enabling of the current profiler * Updates the enabling of the current profiler
* *
* @param IConfig $config * @param IManageConfigValues $config
*/ */
public function update(IConfig $config) public function update(IManageConfigValues $config)
{ {
$this->enabled = $config->get('system', 'profiler'); $this->enabled = $config->get('system', 'profiler');
$this->rendertime = $config->get('rendertime', 'callstack'); $this->rendertime = $config->get('rendertime', 'callstack');
} }
/** /**
* @param \Friendica\Core\Config\Cache\Cache $configCache The configuration cache * @param \Friendica\Core\Config\ValueObject\Cache $configCache The configuration cache
*/ */
public function __construct(Cache $configCache) public function __construct(Cache $configCache)
{ {

View file

@ -41,7 +41,7 @@ use Friendica\Core\PConfig;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Lock; use Friendica\Core\Lock;
use Friendica\Core\Process; use Friendica\Core\Process;
use Friendica\Core\Session\ISession; use Friendica\Core\Session\Capability\IHandleSessions;
use Friendica\Core\StorageManager; use Friendica\Core\StorageManager;
use Friendica\Database\Database; use Friendica\Database\Database;
use Friendica\Factory; use Friendica\Factory;
@ -74,8 +74,8 @@ return [
$_SERVER $_SERVER
] ]
], ],
Config\Cache\ConfigFileLoader::class => [ Config\Util\ConfigFileLoader::class => [
'instanceOf' => Config\Factory\ConfigFactory::class, 'instanceOf' => Config\Factory\Config::class,
'call' => [ 'call' => [
['createConfigFileLoader', [ ['createConfigFileLoader', [
[Dice::INSTANCE => '$basepath'], [Dice::INSTANCE => '$basepath'],
@ -83,8 +83,8 @@ return [
], Dice::CHAIN_CALL], ], Dice::CHAIN_CALL],
], ],
], ],
Config\Cache\Cache::class => [ Config\ValueObject\Cache::class => [
'instanceOf' => Config\Factory\ConfigFactory::class, 'instanceOf' => Config\Factory\Config::class,
'call' => [ 'call' => [
['createCache', [$_SERVER], Dice::CHAIN_CALL], ['createCache', [$_SERVER], Dice::CHAIN_CALL],
], ],
@ -95,14 +95,14 @@ return [
['determine', [], Dice::CHAIN_CALL], ['determine', [], Dice::CHAIN_CALL],
], ],
], ],
Config\IConfig::class => [ Config\Capability\IManageConfigValues::class => [
'instanceOf' => Config\Factory\ConfigFactory::class, 'instanceOf' => Config\Factory\Config::class,
'call' => [ 'call' => [
['create', [], Dice::CHAIN_CALL], ['create', [], Dice::CHAIN_CALL],
], ],
], ],
PConfig\IPConfig::class => [ PConfig\Capability\IManagePersonalConfigValues::class => [
'instanceOf' => PConfig\Factory\PConfigFactory::class, 'instanceOf' => PConfig\Factory\PConfig::class,
'call' => [ 'call' => [
['create', [], Dice::CHAIN_CALL], ['create', [], Dice::CHAIN_CALL],
] ]
@ -158,20 +158,20 @@ return [
['createDev', [], Dice::CHAIN_CALL], ['createDev', [], Dice::CHAIN_CALL],
] ]
], ],
Cache\ICache::class => [ Cache\Capability\ICanCache::class => [
'instanceOf' => Cache\Factory\CacheFactory::class, 'instanceOf' => Cache\Factory\Cache::class,
'call' => [ 'call' => [
['create', [], Dice::CHAIN_CALL], ['create', [], Dice::CHAIN_CALL],
], ],
], ],
Cache\IMemoryCache::class => [ Cache\Capability\ICanCacheInMemory::class => [
'instanceOf' => Cache\Factory\CacheFactory::class, 'instanceOf' => Cache\Factory\Cache::class,
'call' => [ 'call' => [
['create', [], Dice::CHAIN_CALL], ['create', [], Dice::CHAIN_CALL],
], ],
], ],
Lock\ILock::class => [ Lock\Capability\ICanLock::class => [
'instanceOf' => Lock\Factory\LockFactory::class, 'instanceOf' => Lock\Factory\Lock::class,
'call' => [ 'call' => [
['create', [], Dice::CHAIN_CALL], ['create', [], Dice::CHAIN_CALL],
], ],
@ -206,8 +206,8 @@ return [
$_SERVER, $_GET $_SERVER, $_GET
], ],
], ],
ISession::class => [ IHandleSessions::class => [
'instanceOf' => \Friendica\Core\Session\Factory\SessionFactory::class, 'instanceOf' => \Friendica\Core\Session\Factory\Session::class,
'call' => [ 'call' => [
['createSession', [$_SERVER], Dice::CHAIN_CALL], ['createSession', [$_SERVER], Dice::CHAIN_CALL],
['start', [], Dice::CHAIN_CALL], ['start', [], Dice::CHAIN_CALL],

View file

@ -6,10 +6,10 @@
namespace Friendica\Test; namespace Friendica\Test;
use Dice\Dice; use Dice\Dice;
use Friendica\Core\Config\Cache\Cache; use Friendica\Core\Config\ValueObject\Cache;
use Friendica\Core\Config\IConfig; use Friendica\Core\Config\Capability\IManageConfigValues;
use Friendica\Core\Session; use Friendica\Core\Session;
use Friendica\Core\Session\ISession; use Friendica\Core\Session\Capability\IHandleSessions;
use Friendica\Database\Database; use Friendica\Database\Database;
use Friendica\Database\DBStructure; use Friendica\Database\DBStructure;
use Friendica\DI; use Friendica\DI;
@ -33,10 +33,10 @@ abstract class FixtureTest extends DatabaseTest
$this->dice = (new Dice()) $this->dice = (new Dice())
->addRules(include __DIR__ . '/../static/dependencies.config.php') ->addRules(include __DIR__ . '/../static/dependencies.config.php')
->addRule(Database::class, ['instanceOf' => StaticDatabase::class, 'shared' => true]) ->addRule(Database::class, ['instanceOf' => StaticDatabase::class, 'shared' => true])
->addRule(ISession::class, ['instanceOf' => Session\Type\Memory::class, 'shared' => true, 'call' => null]); ->addRule(IHandleSessions::class, ['instanceOf' => Session\Type\Memory::class, 'shared' => true, 'call' => null]);
DI::init($this->dice); DI::init($this->dice);
/** @var IConfig $config */ /** @var IManageConfigValues $config */
$configCache = $this->dice->create(Cache::class); $configCache = $this->dice->create(Cache::class);
$configCache->set('database', 'disable_pdo', true); $configCache->set('database', 'disable_pdo', true);

View file

@ -42,7 +42,7 @@ trait AppMockTrait
protected $app; protected $app;
/** /**
* @var MockInterface|Config\IConfig The mocked Config Cache * @var MockInterface|\Friendica\Core\Config\Capability\IManageConfigValues The mocked Config Cache
*/ */
protected $configMock; protected $configMock;
@ -74,21 +74,21 @@ trait AppMockTrait
$this->dice = \Mockery::mock(Dice::class)->makePartial(); $this->dice = \Mockery::mock(Dice::class)->makePartial();
$this->dice = $this->dice->addRules(include __DIR__ . '/../../static/dependencies.config.php'); $this->dice = $this->dice->addRules(include __DIR__ . '/../../static/dependencies.config.php');
$this->configMock = \Mockery::mock(Config\Cache\Cache::class); $this->configMock = \Mockery::mock(Config\ValueObject\Cache::class);
$this->dice->shouldReceive('create') $this->dice->shouldReceive('create')
->with(Config\Cache\Cache::class) ->with(Config\ValueObject\Cache::class)
->andReturn($this->configMock); ->andReturn($this->configMock);
$this->mode = \Mockery::mock(App\Mode::class); $this->mode = \Mockery::mock(App\Mode::class);
$this->dice->shouldReceive('create') $this->dice->shouldReceive('create')
->with(App\Mode::class) ->with(App\Mode::class)
->andReturn($this->mode); ->andReturn($this->mode);
$configModel= \Mockery::mock(Config\Model\Config::class); $configModel= \Mockery::mock(Config\Repository\Config::class);
// Disable the adapter // Disable the adapter
$configModel->shouldReceive('isConnected')->andReturn(false); $configModel->shouldReceive('isConnected')->andReturn(false);
$config = new Config\Type\JitConfig($this->configMock, $configModel); $config = new Config\Type\JitConfig($this->configMock, $configModel);
$this->dice->shouldReceive('create') $this->dice->shouldReceive('create')
->with(Config\IConfig::class) ->with(Config\Capability\IManageConfigValues::class)
->andReturn($config); ->andReturn($config);
// Mocking App and most used functions // Mocking App and most used functions

View file

@ -23,15 +23,15 @@ namespace Friendica\Test\functional;
use Dice\Dice; use Dice\Dice;
use Friendica\App; use Friendica\App;
use Friendica\Core\Cache\ICache; use Friendica\Core\Cache\Capability\ICanCache;
use Friendica\Core\Cache\IMemoryCache; use Friendica\Core\Cache\Capability\ICanCacheInMemory;
use Friendica\Core\Config\Cache\Cache; use Friendica\Core\Config\ValueObject\Cache;
use Friendica\Core\Config\IConfig; use Friendica\Core\Config\Capability\IManageConfigValues;
use Friendica\Core\Lock\ILock; use Friendica\Core\Lock\Capability\ICanLock;
use Friendica\Database\Database; use Friendica\Database\Database;
use Friendica\Test\Util\VFSTrait; use Friendica\Test\Util\VFSTrait;
use Friendica\Util\BasePath; use Friendica\Util\BasePath;
use Friendica\Core\Config\Cache\ConfigFileLoader; use Friendica\Core\Config\Util\ConfigFileLoader;
use Friendica\Util\Profiler; use Friendica\Util\Profiler;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
@ -158,10 +158,10 @@ class DependencyCheckTest extends TestCase
public function testConfiguration() public function testConfiguration()
{ {
/** @var IConfig $config */ /** @var IManageConfigValues $config */
$config = $this->dice->create(IConfig::class); $config = $this->dice->create(IManageConfigValues::class);
self::assertInstanceOf(IConfig::class, $config); self::assertInstanceOf(IManageConfigValues::class, $config);
self::assertNotEmpty($config->get('database', 'username')); self::assertNotEmpty($config->get('database', 'username'));
} }
@ -176,8 +176,8 @@ class DependencyCheckTest extends TestCase
public function testDevLogger() public function testDevLogger()
{ {
/** @var IConfig $config */ /** @var IManageConfigValues $config */
$config = $this->dice->create(IConfig::class); $config = $this->dice->create(IManageConfigValues::class);
$config->set('system', 'dlogfile', $this->root->url() . '/friendica.log'); $config->set('system', 'dlogfile', $this->root->url() . '/friendica.log');
/** @var LoggerInterface $logger */ /** @var LoggerInterface $logger */
@ -188,26 +188,26 @@ class DependencyCheckTest extends TestCase
public function testCache() public function testCache()
{ {
/** @var ICache $cache */ /** @var ICanCache $cache */
$cache = $this->dice->create(ICache::class); $cache = $this->dice->create(ICanCache::class);
self::assertInstanceOf(ICache::class, $cache); self::assertInstanceOf(ICanCache::class, $cache);
} }
public function testMemoryCache() public function testMemoryCache()
{ {
/** @var IMemoryCache $cache */ /** @var ICanCacheInMemory $cache */
$cache = $this->dice->create(IMemoryCache::class); $cache = $this->dice->create(ICanCacheInMemory::class);
// We need to check "just" ICache, because the default Cache is DB-Cache, which isn't a memorycache // We need to check "just" ICache, because the default Cache is DB-Cache, which isn't a memorycache
self::assertInstanceOf(ICache::class, $cache); self::assertInstanceOf(ICanCache::class, $cache);
} }
public function testLock() public function testLock()
{ {
/** @var ILock $cache */ /** @var ICanLock $cache */
$lock = $this->dice->create(ILock::class); $lock = $this->dice->create(ICanLock::class);
self::assertInstanceOf(ILock::class, $lock); self::assertInstanceOf(ICanLock::class, $lock);
} }
} }

View file

@ -6,8 +6,8 @@
namespace Friendica\Test\legacy; namespace Friendica\Test\legacy;
use Friendica\App; use Friendica\App;
use Friendica\Core\Config\IConfig; use Friendica\Core\Config\Capability\IManageConfigValues;
use Friendica\Core\PConfig\IPConfig; use Friendica\Core\PConfig\Capability\IManagePersonalConfigValues;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\DI; use Friendica\DI;
use Friendica\Network\HTTPException; use Friendica\Network\HTTPException;
@ -45,7 +45,7 @@ class ApiTest extends FixtureTest
/** @var App */ /** @var App */
protected $app; protected $app;
/** @var IConfig */ /** @var IManageConfigValues */
protected $config; protected $config;
/** /**
@ -59,8 +59,8 @@ class ApiTest extends FixtureTest
parent::setUp(); parent::setUp();
/** @var IConfig $config */ /** @var \Friendica\Core\Config\Capability\IManageConfigValues $config */
$this->config = $this->dice->create(IConfig::class); $this->config = $this->dice->create(IManageConfigValues::class);
$this->config->set('system', 'url', 'http://localhost'); $this->config->set('system', 'url', 'http://localhost');
$this->config->set('system', 'hostname', 'localhost'); $this->config->set('system', 'hostname', 'localhost');
@ -813,7 +813,7 @@ class ApiTest extends FixtureTest
*/ */
public function testApiGetUserWithFrioSchema() public function testApiGetUserWithFrioSchema()
{ {
$pConfig = $this->dice->create(IPConfig::class); $pConfig = $this->dice->create(IManagePersonalConfigValues::class);
$pConfig->set($this->selfUser['id'], 'frio', 'schema', 'red'); $pConfig->set($this->selfUser['id'], 'frio', 'schema', 'red');
$user = api_get_user($this->app); $user = api_get_user($this->app);
self::assertSelfUser($user); self::assertSelfUser($user);
@ -829,7 +829,7 @@ class ApiTest extends FixtureTest
*/ */
public function testApiGetUserWithEmptyFrioSchema() public function testApiGetUserWithEmptyFrioSchema()
{ {
$pConfig = $this->dice->create(IPConfig::class); $pConfig = $this->dice->create(IManagePersonalConfigValues::class);
$pConfig->set($this->selfUser['id'], 'frio', 'schema', '---'); $pConfig->set($this->selfUser['id'], 'frio', 'schema', '---');
$user = api_get_user($this->app); $user = api_get_user($this->app);
self::assertSelfUser($user); self::assertSelfUser($user);
@ -845,7 +845,7 @@ class ApiTest extends FixtureTest
*/ */
public function testApiGetUserWithCustomFrioSchema() public function testApiGetUserWithCustomFrioSchema()
{ {
$pConfig = $this->dice->create(IPConfig::class); $pConfig = $this->dice->create(IManagePersonalConfigValues::class);
$pConfig->set($this->selfUser['id'], 'frio', 'schema', '---'); $pConfig->set($this->selfUser['id'], 'frio', 'schema', '---');
$pConfig->set($this->selfUser['id'], 'frio', 'nav_bg', '#123456'); $pConfig->set($this->selfUser['id'], 'frio', 'nav_bg', '#123456');
$pConfig->set($this->selfUser['id'], 'frio', 'link_color', '#123456'); $pConfig->set($this->selfUser['id'], 'frio', 'link_color', '#123456');

View file

@ -24,7 +24,7 @@ namespace Friendica\Test\src\App;
use Detection\MobileDetect; use Detection\MobileDetect;
use Friendica\App\Mode; use Friendica\App\Mode;
use Friendica\App\Module; use Friendica\App\Module;
use Friendica\Core\Config\Cache\Cache; use Friendica\Core\Config\ValueObject\Cache;
use Friendica\Database\Database; use Friendica\Database\Database;
use Friendica\Test\MockedTest; use Friendica\Test\MockedTest;
use Friendica\Test\Util\VFSTrait; use Friendica\Test\Util\VFSTrait;

View file

@ -22,10 +22,10 @@
namespace Friendica\Test\src\App; namespace Friendica\Test\src\App;
use Friendica\App; use Friendica\App;
use Friendica\Core\Cache\ICache; use Friendica\Core\Cache\Capability\ICanCache;
use Friendica\Core\Config\IConfig; use Friendica\Core\Config\Capability\IManageConfigValues;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Lock\ILock; use Friendica\Core\Lock\Capability\ICanLock;
use Friendica\LegacyModule; use Friendica\LegacyModule;
use Friendica\Module\HTTPException\PageNotFound; use Friendica\Module\HTTPException\PageNotFound;
use Friendica\Module\WellKnown\HostMeta; use Friendica\Module\WellKnown\HostMeta;
@ -172,18 +172,18 @@ class ModuleTest extends DatabaseTest
*/ */
public function testModuleClass($assert, string $name, string $command, bool $privAdd) public function testModuleClass($assert, string $name, string $command, bool $privAdd)
{ {
$config = Mockery::mock(IConfig::class); $config = Mockery::mock(IManageConfigValues::class);
$config->shouldReceive('get')->with('config', 'private_addons', false)->andReturn($privAdd)->atMost()->once(); $config->shouldReceive('get')->with('config', 'private_addons', false)->andReturn($privAdd)->atMost()->once();
$l10n = Mockery::mock(L10n::class); $l10n = Mockery::mock(L10n::class);
$l10n->shouldReceive('t')->andReturnUsing(function ($args) { return $args; }); $l10n->shouldReceive('t')->andReturnUsing(function ($args) { return $args; });
$cache = Mockery::mock(ICache::class); $cache = Mockery::mock(ICanCache::class);
$cache->shouldReceive('get')->with('routerDispatchData')->andReturn('')->atMost()->once(); $cache->shouldReceive('get')->with('routerDispatchData')->andReturn('')->atMost()->once();
$cache->shouldReceive('get')->with('lastRoutesFileModifiedTime')->andReturn('')->atMost()->once(); $cache->shouldReceive('get')->with('lastRoutesFileModifiedTime')->andReturn('')->atMost()->once();
$cache->shouldReceive('set')->withAnyArgs()->andReturn(false)->atMost()->twice(); $cache->shouldReceive('set')->withAnyArgs()->andReturn(false)->atMost()->twice();
$lock = Mockery::mock(ILock::class); $lock = Mockery::mock(ICanLock::class);
$lock->shouldReceive('acquire')->andReturn(true); $lock->shouldReceive('acquire')->andReturn(true);
$lock->shouldReceive('isLocked')->andReturn(false); $lock->shouldReceive('isLocked')->andReturn(false);

View file

@ -22,9 +22,9 @@
namespace Friendica\Test\src\App; namespace Friendica\Test\src\App;
use Friendica\App\Router; use Friendica\App\Router;
use Friendica\Core\Cache\ICache; use Friendica\Core\Cache\Capability\ICanCache;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Lock\ILock; use Friendica\Core\Lock\Capability\ICanLock;
use Friendica\Module; use Friendica\Module;
use Friendica\Network\HTTPException\MethodNotAllowedException; use Friendica\Network\HTTPException\MethodNotAllowedException;
use Friendica\Network\HTTPException\NotFoundException; use Friendica\Network\HTTPException\NotFoundException;
@ -37,11 +37,11 @@ class RouterTest extends TestCase
/** @var L10n|MockInterface */ /** @var L10n|MockInterface */
private $l10n; private $l10n;
/** /**
* @var ICache * @var ICanCache
*/ */
private $cache; private $cache;
/** /**
* @var ILock * @var \Friendica\Core\Lock\Capability\ICanLock
*/ */
private $lock; private $lock;
@ -52,11 +52,11 @@ class RouterTest extends TestCase
$this->l10n = Mockery::mock(L10n::class); $this->l10n = Mockery::mock(L10n::class);
$this->l10n->shouldReceive('t')->andReturnUsing(function ($args) { return $args; }); $this->l10n->shouldReceive('t')->andReturnUsing(function ($args) { return $args; });
$this->cache = Mockery::mock(ICache::class); $this->cache = Mockery::mock(ICanCache::class);
$this->cache->shouldReceive('get')->andReturn(null); $this->cache->shouldReceive('get')->andReturn(null);
$this->cache->shouldReceive('set')->andReturn(false); $this->cache->shouldReceive('set')->andReturn(false);
$this->lock = Mockery::mock(ILock::class); $this->lock = Mockery::mock(ICanLock::class);
$this->lock->shouldReceive('acquire')->andReturn(true); $this->lock->shouldReceive('acquire')->andReturn(true);
$this->lock->shouldReceive('isLocked')->andReturn(false); $this->lock->shouldReceive('isLocked')->andReturn(false);
} }

View file

@ -24,7 +24,7 @@ namespace Friendica\Test\src\Console;
use Dice\Dice; use Dice\Dice;
use Friendica\App; use Friendica\App;
use Friendica\Console\AutomaticInstallation; use Friendica\Console\AutomaticInstallation;
use Friendica\Core\Config\Cache\Cache; use Friendica\Core\Config\ValueObject\Cache;
use Friendica\Core\Installer; use Friendica\Core\Installer;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger; use Friendica\Core\Logger;
@ -53,7 +53,7 @@ class AutomaticInstallationConsoleTest extends ConsoleTest
private $assertFileDb; private $assertFileDb;
/** /**
* @var \Friendica\Core\Config\Cache\Cache The configuration cache to check after each test * @var \Friendica\Core\Config\ValueObject\Cache The configuration cache to check after each test
*/ */
private $configCache; private $configCache;

View file

@ -24,7 +24,7 @@ namespace Friendica\Test\src\Console;
use Friendica\App; use Friendica\App;
use Friendica\App\Mode; use Friendica\App\Mode;
use Friendica\Console\Config; use Friendica\Console\Config;
use Friendica\Core\Config\IConfig; use Friendica\Core\Config\Capability\IManageConfigValues;
use Mockery; use Mockery;
use Mockery\LegacyMockInterface; use Mockery\LegacyMockInterface;
use Mockery\MockInterface; use Mockery\MockInterface;
@ -35,7 +35,7 @@ class ConfigConsoleTest extends ConsoleTest
* @var App\Mode|MockInterface $appMode * @var App\Mode|MockInterface $appMode
*/ */
private $appMode; private $appMode;
/** @var IConfig|LegacyMockInterface|MockInterface */ /** @var IManageConfigValues|LegacyMockInterface|MockInterface */
private $configMock; private $configMock;
protected function setUp() : void protected function setUp() : void
@ -52,7 +52,7 @@ class ConfigConsoleTest extends ConsoleTest
$this->appMode->shouldReceive('has') $this->appMode->shouldReceive('has')
->andReturn(true); ->andReturn(true);
$this->configMock = Mockery::mock(IConfig::class); $this->configMock = Mockery::mock(IManageConfigValues::class);
} }
public function testSetGetKeyValue() public function testSetGetKeyValue()

Some files were not shown because too many files have changed in this diff Show more