From 950ad4fff5cbb832d32dd9c2e52916a7a5f78dda Mon Sep 17 00:00:00 2001 From: nuxsmin Date: Wed, 8 Aug 2018 15:26:14 +0200 Subject: [PATCH] * [ADD] Unit testing. Work in progress * [MOD] Code refactoring --- .../web/Controllers/BootstrapController.php | 2 +- .../web/Controllers/Traits/JsonTrait.php | 12 +- lib/SP/Core/Events/EventReceiver.php | 5 - lib/SP/Http/Json.php | 11 +- lib/SP/Mvc/Model/QueryAssignment.php | 2 +- lib/SP/Mvc/Model/QueryCondition.php | 2 +- lib/SP/Mvc/View/View.php | 251 ------------------ lib/SP/Mvc/View/ViewInterface.php | 152 ----------- lib/SP/Plugin/PluginManager.php | 2 +- lib/SP/Providers/Auth/Browser/Browser.php | 38 +-- lib/SP/Providers/Auth/Database/Database.php | 5 +- lib/SP/Providers/EventsTrait.php | 2 +- lib/SP/Providers/Log/DatabaseLogHandler.php | 16 +- lib/SP/Providers/Log/FileLogHandler.php | 52 ++-- lib/SP/Providers/Log/RemoteSyslogHandler.php | 56 ++-- lib/SP/Providers/Log/SyslogHandler.php | 56 ++-- lib/SP/Providers/Mail/MailHandler.php | 16 +- lib/SP/Providers/Mail/MailProvider.php | 2 +- .../Notification/NotificationHandler.php | 155 ++++++----- lib/SP/Repositories/Repository.php | 16 +- lib/SP/Services/Install/MySQL.php | 55 ++-- .../Upgrade/UpgradeDatabaseService.php | 15 +- .../Database/DatabaseFileInterface.php | 7 +- lib/SP/Storage/Database/MySQLFileParser.php | 31 ++- phpunit.xml | 6 + test/res/config/config.xml | 8 +- 26 files changed, 270 insertions(+), 705 deletions(-) delete mode 100644 lib/SP/Mvc/View/View.php delete mode 100644 lib/SP/Mvc/View/ViewInterface.php diff --git a/app/modules/web/Controllers/BootstrapController.php b/app/modules/web/Controllers/BootstrapController.php index a708fe84..05c16e91 100644 --- a/app/modules/web/Controllers/BootstrapController.php +++ b/app/modules/web/Controllers/BootstrapController.php @@ -102,7 +102,7 @@ final class BootstrapController extends SimpleControllerBase */ private function getAuthBasicAutologinEnabled() { - return Browser::getServerAuthUser() && $this->configData->isAuthBasicAutoLoginEnabled(); + return $this->dic->get(Browser::class)->getServerAuthUser() !== null && $this->configData->isAuthBasicAutoLoginEnabled(); } /** diff --git a/app/modules/web/Controllers/Traits/JsonTrait.php b/app/modules/web/Controllers/Traits/JsonTrait.php index 7446889b..2dbb5038 100644 --- a/app/modules/web/Controllers/Traits/JsonTrait.php +++ b/app/modules/web/Controllers/Traits/JsonTrait.php @@ -41,6 +41,8 @@ trait JsonTrait * @param int $status Status code * @param string $description Untranslated description string * @param array|null $messages Untranslated massages array of strings + * + * @return bool */ protected function returnJsonResponse($status, $description, array $messages = null) { @@ -52,7 +54,7 @@ trait JsonTrait $jsonResponse->setMessages($messages); } - Json::fromDic()->returnJson($jsonResponse); + return Json::fromDic()->returnJson($jsonResponse); } /** @@ -62,6 +64,8 @@ trait JsonTrait * @param int $status Status code * @param string $description Untranslated description string * @param array $messages + * + * @return bool */ protected function returnJsonResponseData($data, $status = JsonResponse::JSON_SUCCESS, $description = null, array $messages = null) { @@ -77,7 +81,7 @@ trait JsonTrait $jsonResponse->setMessages($messages); } - Json::fromDic()->returnJson($jsonResponse); + return Json::fromDic()->returnJson($jsonResponse); } /** @@ -85,6 +89,8 @@ trait JsonTrait * * @param \Exception $exception * @param int $status Status code + * + * @return bool */ protected function returnJsonResponseException(\Exception $exception, $status = JsonResponse::JSON_ERROR) { @@ -96,6 +102,6 @@ trait JsonTrait $jsonResponse->setMessages([$exception->getHint()]); } - Json::fromDic()->returnJson($jsonResponse); + return Json::fromDic()->returnJson($jsonResponse); } } \ No newline at end of file diff --git a/lib/SP/Core/Events/EventReceiver.php b/lib/SP/Core/Events/EventReceiver.php index 3655dfce..88463e64 100644 --- a/lib/SP/Core/Events/EventReceiver.php +++ b/lib/SP/Core/Events/EventReceiver.php @@ -33,11 +33,6 @@ use SplObserver; */ interface EventReceiver extends SplObserver { - /** - * Inicialización del observador - */ - public function init(); - /** * Evento de actualización * diff --git a/lib/SP/Http/Json.php b/lib/SP/Http/Json.php index eee09bf8..e7cfe5f2 100644 --- a/lib/SP/Http/Json.php +++ b/lib/SP/Http/Json.php @@ -127,13 +127,16 @@ final class Json * Devuelve una respuesta en formato JSON * * @param string $data JSON string + * + * @return bool */ public function returnRawJson($data) { - $this->response + return $this->response ->header('Content-type', 'application/json; charset=utf-8') ->body($data) - ->send(true); + ->send(true) + ->isSent(); } /** @@ -141,7 +144,7 @@ final class Json * * @param JsonResponse $jsonResponse * - * @return void + * @return bool */ public function returnJson(JsonResponse $jsonResponse) { @@ -156,7 +159,7 @@ final class Json $this->response->body(json_encode($jsonResponse)); } - $this->response->send(true); + return $this->response->send(true)->isSent(); } /** diff --git a/lib/SP/Mvc/Model/QueryAssignment.php b/lib/SP/Mvc/Model/QueryAssignment.php index 4a260aea..9ebc8c9a 100644 --- a/lib/SP/Mvc/Model/QueryAssignment.php +++ b/lib/SP/Mvc/Model/QueryAssignment.php @@ -65,7 +65,7 @@ final class QueryAssignment public function setFields(array $fields, array $values) { $this->fields = array_map(function ($value) { - return strpos($value, '=') === false ? $value . ' = ?' : $value; + return strpos($value, '=') === false ? "$value = ?" : $value; }, $fields); $this->values = array_merge($this->values, $values); diff --git a/lib/SP/Mvc/Model/QueryCondition.php b/lib/SP/Mvc/Model/QueryCondition.php index 9e44e098..62db9928 100644 --- a/lib/SP/Mvc/Model/QueryCondition.php +++ b/lib/SP/Mvc/Model/QueryCondition.php @@ -51,7 +51,7 @@ final class QueryCondition */ public function addFilter($query, array $params = null) { - $this->query[] = '(' . $query . ')'; + $this->query[] = "($query)"; if ($params !== null) { $this->param = array_merge($this->param, $params); diff --git a/lib/SP/Mvc/View/View.php b/lib/SP/Mvc/View/View.php deleted file mode 100644 index 4e61d704..00000000 --- a/lib/SP/Mvc/View/View.php +++ /dev/null @@ -1,251 +0,0 @@ -. - */ - -namespace SP\Mvc\View; - -/** - * Class View - * - * @package SP\Lib\Mvc\View - */ -final class View implements ViewInterface -{ - /** - * @var array - */ - protected $vars = []; - /** - * @var \Twig_Environment - */ - protected $view; - /** - * @var array - */ - protected $template = [ - 'namespace' => '', - 'controller' => '', - 'action' => '' - ]; - /** - * @var string - */ - protected $layouts = '_layouts'; - /** - * @var string - */ - protected $partials = '_partials'; - - /** - * View constructor. - * - * @param \Twig_Environment $view - */ - public function __construct(\Twig_Environment $view) - { - $this->view = $view; - $this->vars['view'] = $this; - } - - /** - * Asignar una variable - * - * @param $name - * @param $value - * - * @return $this - */ - public function assign($name, $value) - { - if ($name === 'view') { - return $this; - } - - $this->vars[$name] = $value; - - return $this; - } - - /** - * Establecer variables - * - * @param array $vars - * - * @return $this - */ - public function setVars(array $vars) - { - $this->vars = $vars; - - return $this; - } - - /** - * Renderizar plantilla - * - * @param $template - * @param string $path - * - * @return string - */ - public function render($template, $path = null) - { - $this->template['action'] = $template; - - if (null !== $path) { - return $this->view->load($this->template['namespace'] . '/' . trim($path, '/') . '/' . $template)->render($this->vars); - } - - return $this->view->load(implode('/', $this->template))->render($this->vars); - } - - /** - * Establecer namespace para las plantillas - * - * @param $name - * - * @return $this - */ - public function setNamespace($name) - { - $this->template['namespace'] = '@' . $name; - - return $this; - } - - /** - * Establecer el controlador - * - * @param $name - * - * @return $this - */ - public function setController($name) - { - $this->template['controller'] = $name; - - return $this; - } - - /** - * Devolver el namespace - * - * @return string - */ - public function getNamespace() - { - return $this->template['namespace']; - } - - /** - * Devolver el controlador - * - * @return string - */ - public function getController() - { - return $this->template['controller']; - } - - /** - * Devolver el directorio a la vista actual - * - * @return string - */ - public function getDir() - { - return $this->template['namespace'] . '/' . $this->template['controller']; - } - - /** - * Devolver el directorio de layouts - * - * @return string - */ - public function getLayoutsDir() - { - return $this->template['namespace'] . '/' . $this->layouts; - } - - /** - * Devolver el directorio de layouts - * - * @return string - */ - public function getLayouts() - { - return $this->layouts; - } - - /** - * Establecer el directorio de layouts - * - * @param string $layouts - */ - public function setLayouts($layouts) - { - $this->layouts = $layouts; - } - - /** - * Devolver una variable - * - * @param $name - * - * @return mixed - */ - public function get($name) - { - return isset($this->vars[$name]) ? $this->vars[$name] : null; - } - - /** - * Devolver la ruta a los partials - * - * @return string - */ - public function getPartialsDir() - { - return $this->template['namespace'] . '/' . $this->partials; - } - - /** - * Devolver el directorio de partials - * - * @return string - */ - public function getPartials() - { - return $this->partials; - } - - /** - * Establecer el directorio de partials - * - * @param string $partials - */ - public function setPartials($partials) - { - $this->partials = $partials; - } -} \ No newline at end of file diff --git a/lib/SP/Mvc/View/ViewInterface.php b/lib/SP/Mvc/View/ViewInterface.php deleted file mode 100644 index 853108e0..00000000 --- a/lib/SP/Mvc/View/ViewInterface.php +++ /dev/null @@ -1,152 +0,0 @@ -. - */ - -namespace SP\Mvc\View; - -/** - * Interface ViewInterface - * - * @package SP\Lib\Mvc\View - */ -interface ViewInterface -{ - /** - * Añadir una variable - * - * @param $name - * @param $value - * - * @return $this - */ - public function assign($name, $value); - - /** - * Devolver una variable - * - * @param $name - * - * @return mixed - */ - public function get($name); - - /** - * Establecer variables - * - * @param array $vars - * - * @return $this - */ - public function setVars(array $vars); - - /** - * Renderizar plantilla - * - * @param $template - * @param null $path - * - * @return string - */ - public function render($template, $path = null); - - /** - * Establecer namespace para las plantillas - * - * @param $name - * - * @return $this - */ - public function setNamespace($name); - - /** - * Establecer el controlador - * - * @param $name - * - * @return $this - */ - public function setController($name); - - /** - * Devolver el namespace - * - * @return string - */ - public function getNamespace(); - - /** - * Devolver el controlador - * - * @return string - */ - public function getController(); - - /** - * Devolver la ruta a la vista actual - * - * @return string - */ - public function getDir(); - - /** - * Devolver la ruta a los layouts - * - * @return string - */ - public function getLayoutsDir(); - - /** - * Devolver el directorio de layouts - * - * @return string - */ - public function getLayouts(); - - /** - * Establecer el directorio de layouts - * - * @param string $layouts - */ - public function setLayouts($layouts); - - /** - * Devolver la ruta a los partials - * - * @return string - */ - public function getPartialsDir(); - - /** - * Devolver el directorio de partials - * - * @return string - */ - public function getPartials(); - - /** - * Establecer el directorio de partials - * - * @param string $partials - */ - public function setPartials($partials); -} \ No newline at end of file diff --git a/lib/SP/Plugin/PluginManager.php b/lib/SP/Plugin/PluginManager.php index cfb3cf90..75e0c984 100644 --- a/lib/SP/Plugin/PluginManager.php +++ b/lib/SP/Plugin/PluginManager.php @@ -38,7 +38,7 @@ use SP\Services\Plugin\PluginService; * * @package SP\Plugin */ -class PluginManager +final class PluginManager { /** * @var array Plugins habilitados diff --git a/lib/SP/Providers/Auth/Browser/Browser.php b/lib/SP/Providers/Auth/Browser/Browser.php index 4f562c68..41759800 100644 --- a/lib/SP/Providers/Auth/Browser/Browser.php +++ b/lib/SP/Providers/Auth/Browser/Browser.php @@ -26,6 +26,7 @@ namespace SP\Providers\Auth\Browser; use SP\Config\ConfigData; use SP\DataModel\UserLoginData; +use SP\Http\Request; use SP\Providers\Auth\AuthInterface; /** @@ -41,15 +42,21 @@ final class Browser implements AuthInterface * @var ConfigData */ private $configData; + /** + * @var Request + */ + private $request; /** * Browser constructor. * * @param ConfigData $configData + * @param Request $request */ - public function __construct(ConfigData $configData) + public function __construct(ConfigData $configData, Request $request) { $this->configData = $configData; + $this->request = $request; } /** @@ -69,7 +76,7 @@ final class Browser implements AuthInterface } if ($this->configData->isAuthBasicAutoLoginEnabled()) { - $authUser = self::getServerAuthUser(); + $authUser = $this->getServerAuthUser(); $authPass = $this->getAuthPass(); if ($authUser !== null && $authPass !== null) { @@ -106,13 +113,12 @@ final class Browser implements AuthInterface public function checkServerAuthUser($login) { $domain = $this->configData->getAuthBasicDomain(); + $authUser = $this->getServerAuthUser(); - if (!empty($domain)) { - $login = self::getServerAuthUser() . '@' . $domain; + if (!empty($domain) && !empty($authUser)) { + $login = $authUser . '@' . $domain; } - $authUser = self::getServerAuthUser(); - return $authUser !== null && $authUser === $login ?: null; } @@ -121,14 +127,18 @@ final class Browser implements AuthInterface * * @return string */ - public static function getServerAuthUser() + public function getServerAuthUser() { - if (isset($_SERVER['PHP_AUTH_USER']) && !empty($_SERVER['PHP_AUTH_USER'])) { - return $_SERVER['PHP_AUTH_USER']; + $authUser = $this->request->getServer('PHP_AUTH_USER'); + + if (!empty($authUser)) { + return $authUser; } - if (isset($_SERVER['REMOTE_USER']) && !empty($_SERVER['REMOTE_USER'])) { - return $_SERVER['REMOTE_USER']; + $remoteUser = $this->request->getServer('REMOTE_USER'); + + if (!empty($remoteUser)) { + return $remoteUser; } return null; @@ -141,10 +151,8 @@ final class Browser implements AuthInterface */ protected function getAuthPass() { - if (isset($_SERVER['PHP_AUTH_PW']) && !empty($_SERVER['PHP_AUTH_PW'])) { - return $_SERVER['PHP_AUTH_PW']; - } + $authPass = $this->request->getServer('PHP_AUTH_PW'); - return null; + return !empty($authPass) ? $authPass : null; } } \ No newline at end of file diff --git a/lib/SP/Providers/Auth/Database/Database.php b/lib/SP/Providers/Auth/Database/Database.php index 8009b090..7e6c026f 100644 --- a/lib/SP/Providers/Auth/Database/Database.php +++ b/lib/SP/Providers/Auth/Database/Database.php @@ -111,15 +111,14 @@ final class Database implements AuthInterface if ($userLoginResponse->getIsMigrate() && $this->checkMigrateUser($userLoginResponse)) { return $this->userPassService->migrateUserPassById($userLoginResponse->getId(), $this->userLoginData->getLoginPass()); - } return Hash::checkHashKey($this->userLoginData->getLoginPass(), $userLoginResponse->getPass()); } catch (\Exception $e) { processException($e); - - return false; } + + return false; } /** diff --git a/lib/SP/Providers/EventsTrait.php b/lib/SP/Providers/EventsTrait.php index 6f66be10..e7cf190e 100644 --- a/lib/SP/Providers/EventsTrait.php +++ b/lib/SP/Providers/EventsTrait.php @@ -38,6 +38,6 @@ trait EventsTrait */ protected function parseEventsToRegex(array $events) { - return str_replace('.', '\\.', implode('|', $events)); + return implode('|', array_map('preg_quote', $events)); } } \ No newline at end of file diff --git a/lib/SP/Providers/Log/DatabaseLogHandler.php b/lib/SP/Providers/Log/DatabaseLogHandler.php index 1e9a8229..4e6a3a8b 100644 --- a/lib/SP/Providers/Log/DatabaseLogHandler.php +++ b/lib/SP/Providers/Log/DatabaseLogHandler.php @@ -70,15 +70,15 @@ final class DatabaseLogHandler extends Provider implements EventReceiver /** * @var EventlogService */ - protected $eventlogService; + private $eventlogService; /** * @var string */ - protected $events; + private $events; /** * @var Language */ - protected $language; + private $language; /** * Receive update from subject @@ -94,15 +94,7 @@ final class DatabaseLogHandler extends Provider implements EventReceiver */ public function update(SplSubject $subject) { - // TODO: Implement update() method. - } - - /** - * Inicialización del observador - */ - public function init() - { - // TODO: Implement init() method. + $this->updateEvent('update', new Event($subject)); } /** diff --git a/lib/SP/Providers/Log/FileLogHandler.php b/lib/SP/Providers/Log/FileLogHandler.php index b4e5840e..b64f2dca 100644 --- a/lib/SP/Providers/Log/FileLogHandler.php +++ b/lib/SP/Providers/Log/FileLogHandler.php @@ -51,38 +51,11 @@ final class FileLogHandler extends Provider implements EventReceiver /** * @var string */ - protected $events; + private $events; /** * @var Language */ - protected $language; - - /** - * Inicialización del observador - */ - public function init() - { - // TODO: Implement init() method. - } - - /** - * Evento de actualización - * - * @param string $eventType Nombre del evento - * @param Event $event Objeto del evento - */ - public function updateEvent($eventType, Event $event) - { - $this->language->setAppLocales(); - - if (($e = $event->getSource()) instanceof \Exception) { - logger(sprintf(self::MESSAGE_FORMAT, $eventType, __($e->getMessage()))); - } elseif (($eventMessage = $event->getEventMessage()) !== null) { - logger(sprintf(self::MESSAGE_FORMAT, $eventType, $eventMessage->composeText(';'))); - } - - $this->language->unsetAppLocales(); - } + private $language; /** * Devuelve los eventos que implementa el observador @@ -118,7 +91,26 @@ final class FileLogHandler extends Provider implements EventReceiver */ public function update(SplSubject $subject) { - // TODO: Implement update() method. + $this->updateEvent('update', new Event($subject)); + } + + /** + * Evento de actualización + * + * @param string $eventType Nombre del evento + * @param Event $event Objeto del evento + */ + public function updateEvent($eventType, Event $event) + { + $this->language->setAppLocales(); + + if (($e = $event->getSource()) instanceof \Exception) { + logger(sprintf(self::MESSAGE_FORMAT, $eventType, __($e->getMessage()))); + } elseif (($eventMessage = $event->getEventMessage()) !== null) { + logger(sprintf(self::MESSAGE_FORMAT, $eventType, $eventMessage->composeText(';'))); + } + + $this->language->unsetAppLocales(); } /** diff --git a/lib/SP/Providers/Log/RemoteSyslogHandler.php b/lib/SP/Providers/Log/RemoteSyslogHandler.php index eb225f80..a01d94b6 100644 --- a/lib/SP/Providers/Log/RemoteSyslogHandler.php +++ b/lib/SP/Providers/Log/RemoteSyslogHandler.php @@ -72,43 +72,15 @@ final class RemoteSyslogHandler extends Provider implements EventReceiver /** * @var string */ - protected $events; + private $events; /** * @var Logger */ - protected $logger; + private $logger; /** * @var Language */ - protected $language; - - /** - * Inicialización del observador - */ - public function init() - { - // TODO: Implement init() method. - } - - /** - * Evento de actualización - * - * @param string $eventType Nombre del evento - * @param Event $event Objeto del evento - */ - public function updateEvent($eventType, Event $event) - { - $this->language->setAppLocales(); - - if (($e = $event->getSource()) instanceof \Exception) { - /** @var \Exception $e */ - $this->logger->error(sprintf(self::MESSAGE_FORMAT, $eventType, __($e->getMessage()))); - } elseif (($eventMessage = $event->getEventMessage()) !== null) { - $this->logger->debug(sprintf(self::MESSAGE_FORMAT, $eventType, $eventMessage->composeText(';'))); - } - - $this->language->unsetAppLocales(); - } + private $language; /** * Devuelve los eventos que implementa el observador @@ -144,7 +116,27 @@ final class RemoteSyslogHandler extends Provider implements EventReceiver */ public function update(SplSubject $subject) { - // TODO: Implement update() method. + $this->updateEvent('update', new Event($subject)); + } + + /** + * Evento de actualización + * + * @param string $eventType Nombre del evento + * @param Event $event Objeto del evento + */ + public function updateEvent($eventType, Event $event) + { + $this->language->setAppLocales(); + + if (($e = $event->getSource()) instanceof \Exception) { + /** @var \Exception $e */ + $this->logger->error(sprintf(self::MESSAGE_FORMAT, $eventType, __($e->getMessage()))); + } elseif (($eventMessage = $event->getEventMessage()) !== null) { + $this->logger->debug(sprintf(self::MESSAGE_FORMAT, $eventType, $eventMessage->composeText(';'))); + } + + $this->language->unsetAppLocales(); } /** diff --git a/lib/SP/Providers/Log/SyslogHandler.php b/lib/SP/Providers/Log/SyslogHandler.php index 18a0b18e..a0ddb305 100644 --- a/lib/SP/Providers/Log/SyslogHandler.php +++ b/lib/SP/Providers/Log/SyslogHandler.php @@ -71,43 +71,15 @@ final class SyslogHandler extends Provider implements EventReceiver /** * @var string */ - protected $events; + private $events; /** * @var Logger */ - protected $logger; + private $logger; /** * @var Language */ - protected $language; - - /** - * Inicialización del observador - */ - public function init() - { - // TODO: Implement init() method. - } - - /** - * Evento de actualización - * - * @param string $eventType Nombre del evento - * @param Event $event Objeto del evento - */ - public function updateEvent($eventType, Event $event) - { - $this->language->setAppLocales(); - - if (($e = $event->getSource()) instanceof \Exception) { - /** @var \Exception $e */ - $this->logger->error(sprintf(self::MESSAGE_FORMAT, $eventType, __($e->getMessage()))); - } elseif (($eventMessage = $event->getEventMessage()) !== null) { - $this->logger->debug(sprintf(self::MESSAGE_FORMAT, $eventType, $eventMessage->composeText(';'))); - } - - $this->language->unsetAppLocales(); - } + private $language; /** * Devuelve los eventos que implementa el observador @@ -143,7 +115,27 @@ final class SyslogHandler extends Provider implements EventReceiver */ public function update(SplSubject $subject) { - // TODO: Implement update() method. + $this->updateEvent('update', new Event($subject)); + } + + /** + * Evento de actualización + * + * @param string $eventType Nombre del evento + * @param Event $event Objeto del evento + */ + public function updateEvent($eventType, Event $event) + { + $this->language->setAppLocales(); + + if (($e = $event->getSource()) instanceof \Exception) { + /** @var \Exception $e */ + $this->logger->error(sprintf(self::MESSAGE_FORMAT, $eventType, __($e->getMessage()))); + } elseif (($eventMessage = $event->getEventMessage()) !== null) { + $this->logger->debug(sprintf(self::MESSAGE_FORMAT, $eventType, $eventMessage->composeText(';'))); + } + + $this->language->unsetAppLocales(); } /** diff --git a/lib/SP/Providers/Mail/MailHandler.php b/lib/SP/Providers/Mail/MailHandler.php index 38a560c1..c33a4d6e 100644 --- a/lib/SP/Providers/Mail/MailHandler.php +++ b/lib/SP/Providers/Mail/MailHandler.php @@ -59,23 +59,15 @@ final class MailHandler extends Provider implements EventReceiver /** * @var \SP\Services\Mail\MailService */ - protected $mailService; + private $mailService; /** * @var string */ - protected $events; + private $events; /** * @var Request */ - protected $request; - - /** - * Inicialización del observador - */ - public function init() - { - // TODO: Implement init() method. - } + private $request; /** * Evento de actualización @@ -136,7 +128,7 @@ final class MailHandler extends Provider implements EventReceiver */ public function update(SplSubject $subject) { - // TODO: Implement update() method. + $this->updateEvent('update', new Event($subject)); } /** diff --git a/lib/SP/Providers/Mail/MailProvider.php b/lib/SP/Providers/Mail/MailProvider.php index ac20a273..38765a34 100644 --- a/lib/SP/Providers/Mail/MailProvider.php +++ b/lib/SP/Providers/Mail/MailProvider.php @@ -39,7 +39,7 @@ final class MailProvider extends Provider /** * @var PHPMailer */ - protected $mailer; + private $mailer; /** * @var bool */ diff --git a/lib/SP/Providers/Notification/NotificationHandler.php b/lib/SP/Providers/Notification/NotificationHandler.php index db7633e6..54d6e496 100644 --- a/lib/SP/Providers/Notification/NotificationHandler.php +++ b/lib/SP/Providers/Notification/NotificationHandler.php @@ -28,6 +28,7 @@ use DI\Container; use SP\Core\Events\Event; use SP\Core\Events\EventReceiver; use SP\DataModel\NotificationData; +use SP\Providers\EventsTrait; use SP\Providers\Provider; use SP\Services\Notification\NotificationService; use SplSubject; @@ -39,6 +40,8 @@ use SplSubject; */ final class NotificationHandler extends Provider implements EventReceiver { + use EventsTrait; + const EVENTS = [ 'request.account', 'show.account.link' @@ -47,87 +50,11 @@ final class NotificationHandler extends Provider implements EventReceiver /** * @var NotificationService */ - protected $notificationService; + private $notificationService; /** * @var string */ - protected $events; - - /** - * Inicialización del observador - */ - public function init() - { - // TODO: Implement init() method. - } - - /** - * Evento de actualización - * - * @param string $eventType Nombre del evento - * @param Event $event Objeto del evento - */ - public function updateEvent($eventType, Event $event) - { - switch ($eventType) { - case 'request.account': - $this->requestAccountNotification($event); - break; - case 'show.account.link': - $this->showAccountLinkNotification($event); - break; - } - } - - /** - * @param Event $event - */ - protected function requestAccountNotification(Event $event) - { - $eventMessage = $event->getEventMessage(); - $data = $eventMessage->getData(); - - foreach ($data['userId'] as $userId) { - $notificationData = new NotificationData(); - $notificationData->setType(__('Solicitud')); - $notificationData->setComponent(__('Cuentas')); - $notificationData->setUserId($userId); - $notificationData->setDescription($eventMessage); - - $this->notify($notificationData); - } - } - - /** - * @param NotificationData $notificationData - */ - protected function notify(NotificationData $notificationData) - { - try { - $this->notificationService->create($notificationData); - } catch (\Exception $e) { - processException($e); - } - } - - /** - * @param Event $event - */ - protected function showAccountLinkNotification(Event $event) - { - $eventMessage = $event->getEventMessage(); - $data = $eventMessage->getData(); - - if ($data['notify'] === true) { - $notificationData = new NotificationData(); - $notificationData->setType(__('Notificación')); - $notificationData->setComponent(__('Cuentas')); - $notificationData->setUserId($data['userId']); - $notificationData->setDescription($eventMessage); - - $this->notify($notificationData); - } - } + private $events; /** * Devuelve los eventos que implementa el observador @@ -163,7 +90,75 @@ final class NotificationHandler extends Provider implements EventReceiver */ public function update(SplSubject $subject) { - // TODO: Implement update() method. + $this->updateEvent('update', new Event($subject)); + } + + /** + * Evento de actualización + * + * @param string $eventType Nombre del evento + * @param Event $event Objeto del evento + */ + public function updateEvent($eventType, Event $event) + { + switch ($eventType) { + case 'request.account': + $this->requestAccountNotification($event); + break; + case 'show.account.link': + $this->showAccountLinkNotification($event); + break; + } + } + + /** + * @param Event $event + */ + private function requestAccountNotification(Event $event) + { + $eventMessage = $event->getEventMessage(); + $data = $eventMessage->getData(); + + foreach ($data['userId'] as $userId) { + $notificationData = new NotificationData(); + $notificationData->setType(__('Solicitud')); + $notificationData->setComponent(__('Cuentas')); + $notificationData->setUserId($userId); + $notificationData->setDescription($eventMessage); + + $this->notify($notificationData); + } + } + + /** + * @param NotificationData $notificationData + */ + private function notify(NotificationData $notificationData) + { + try { + $this->notificationService->create($notificationData); + } catch (\Exception $e) { + processException($e); + } + } + + /** + * @param Event $event + */ + private function showAccountLinkNotification(Event $event) + { + $eventMessage = $event->getEventMessage(); + $data = $eventMessage->getData(); + + if ($data['notify'] === true) { + $notificationData = new NotificationData(); + $notificationData->setType(__('Notificación')); + $notificationData->setComponent(__('Cuentas')); + $notificationData->setUserId($data['userId']); + $notificationData->setDescription($eventMessage); + + $this->notify($notificationData); + } } /** @@ -176,6 +171,6 @@ final class NotificationHandler extends Provider implements EventReceiver { $this->notificationService = $dic->get(NotificationService::class); - $this->events = str_replace('.', '\\.', implode('|', self::EVENTS)); + $this->events = $this->parseEventsToRegex(self::EVENTS); } } \ No newline at end of file diff --git a/lib/SP/Repositories/Repository.php b/lib/SP/Repositories/Repository.php index b40de027..a71953cd 100644 --- a/lib/SP/Repositories/Repository.php +++ b/lib/SP/Repositories/Repository.php @@ -24,9 +24,7 @@ namespace SP\Repositories; -use SP\Config\Config; use SP\Core\Context\ContextInterface; -use SP\Core\Events\EventDispatcher; use SP\Storage\Database\Database; /** @@ -36,18 +34,10 @@ use SP\Storage\Database\Database; */ abstract class Repository { - /** - * @var Config - */ - protected $config; /** * @var ContextInterface */ protected $context; - /** - * @var EventDispatcher - */ - protected $eventDispatcher; /** * @var Database */ @@ -56,17 +46,13 @@ abstract class Repository /** * Repository constructor. * - * @param Config $config * @param Database $database * @param ContextInterface $session - * @param EventDispatcher $eventDispatcher */ - final public function __construct(Config $config, Database $database, ContextInterface $session, EventDispatcher $eventDispatcher) + final public function __construct(Database $database, ContextInterface $session) { - $this->config = $config; $this->db = $database; $this->context = $session; - $this->eventDispatcher = $eventDispatcher; if (method_exists($this, 'initialize')) { $this->initialize(); diff --git a/lib/SP/Services/Install/MySQL.php b/lib/SP/Services/Install/MySQL.php index 010b2b7e..6e3191d0 100644 --- a/lib/SP/Services/Install/MySQL.php +++ b/lib/SP/Services/Install/MySQL.php @@ -32,6 +32,7 @@ use SP\Storage\Database\DatabaseUtil; use SP\Storage\Database\DBStorageInterface; use SP\Storage\Database\MySQLFileParser; use SP\Storage\Database\MySQLHandler; +use SP\Storage\File\FileException; use SP\Storage\File\FileHandler; use SP\Util\Util; @@ -298,16 +299,6 @@ final class MySQL implements DatabaseSetupInterface */ public function createDBStructure() { - $fileName = SQL_PATH . DIRECTORY_SEPARATOR . 'dbstructure.sql'; - - if (!file_exists($fileName)) { - throw new SPException( - __u('El archivo de estructura de la BBDD no existe'), - SPException::CRITICAL, - __u('No es posible crear la BBDD de la aplicación. Descárguela de nuevo.') - ); - } - try { $dbc = $this->mysqlHandler->getConnectionSimple(); @@ -323,26 +314,36 @@ final class MySQL implements DatabaseSetupInterface ); } + try { + $parser = new MySQLFileParser(new FileHandler(SQL_PATH . DIRECTORY_SEPARATOR . 'dbstructure.sql')); - foreach ((new MySQLFileParser()) - ->parse(new FileHandler($fileName)) as $query) { - try { + foreach ($parser->parse() as $query) { $dbc->exec($query); - } catch (PDOException $e) { - processException($e); - - logger('Query: ' . $query); - - $this->rollback(); - - throw new SPException( - sprintf(__('Error al crear la BBDD (\'%s\')'), $e->getMessage()), - SPException::CRITICAL, - __u('Error al crear la estructura de la Base de Datos.'), - $e->getCode(), - $e - ); } + } catch (PDOException $e) { + processException($e); + + $this->rollback(); + + throw new SPException( + sprintf(__('Error al crear la BBDD (\'%s\')'), $e->getMessage()), + SPException::CRITICAL, + __u('Error al crear la estructura de la Base de Datos.'), + $e->getCode(), + $e + ); + } catch (FileException $e) { + processException($e); + + $this->rollback(); + + throw new SPException( + sprintf(__('Error al crear la BBDD (\'%s\')'), $e->getMessage()), + SPException::ERROR, + $e->getMessage(), + $e->getCode(), + $e + ); } } diff --git a/lib/SP/Services/Upgrade/UpgradeDatabaseService.php b/lib/SP/Services/Upgrade/UpgradeDatabaseService.php index e267c59b..c45cbe81 100644 --- a/lib/SP/Services/Upgrade/UpgradeDatabaseService.php +++ b/lib/SP/Services/Upgrade/UpgradeDatabaseService.php @@ -152,14 +152,9 @@ final class UpgradeDatabaseService extends Service implements UpgradeInterface $queries = $this->getQueriesFromFile($version); if (count($queries) === 0) { - logger(__('No es necesario actualizar la Base de Datos.')); + logger(__('El archivo de actualización no contiene datos'), 'ERROR'); - $this->eventDispatcher->notifyEvent('upgrade.db.process', - new Event($this, EventMessage::factory() - ->addDescription(__u('No es necesario actualizar la Base de Datos.'))) - ); - - return true; + throw new UpgradeException(__u('El archivo de actualización no contiene datos'), UpgradeException::ERROR, $version); } foreach ($queries as $query) { @@ -205,10 +200,12 @@ final class UpgradeDatabaseService extends Service implements UpgradeInterface */ private function getQueriesFromFile($filename) { - $file = SQL_PATH . DIRECTORY_SEPARATOR . str_replace('.', '', $filename) . '.sql'; + $fileName = SQL_PATH . DIRECTORY_SEPARATOR . str_replace('.', '', $filename) . '.sql'; try { - return (new MySQLFileParser())->parse(new FileHandler($file), '$$'); + $parser = new MySQLFileParser(new FileHandler($fileName)); + + return $parser->parse('$$'); } catch (FileException $e) { processException($e); diff --git a/lib/SP/Storage/Database/DatabaseFileInterface.php b/lib/SP/Storage/Database/DatabaseFileInterface.php index 728cbcc2..fa38aef5 100644 --- a/lib/SP/Storage/Database/DatabaseFileInterface.php +++ b/lib/SP/Storage/Database/DatabaseFileInterface.php @@ -24,8 +24,6 @@ namespace SP\Storage\Database; -use SP\Storage\File\FileHandler; - /** * Interface DatabaseFileInterface * @@ -36,10 +34,9 @@ interface DatabaseFileInterface /** * Parses a database script file and returns an array of lines parsed * - * @param FileHandler $fileHandler - * @param string $delimiter + * @param string $delimiter * * @return array */ - public function parse(FileHandler $fileHandler, $delimiter = ';'); + public function parse($delimiter = ';'); } \ No newline at end of file diff --git a/lib/SP/Storage/Database/MySQLFileParser.php b/lib/SP/Storage/Database/MySQLFileParser.php index f00a4a42..4e96191a 100644 --- a/lib/SP/Storage/Database/MySQLFileParser.php +++ b/lib/SP/Storage/Database/MySQLFileParser.php @@ -34,22 +34,38 @@ use SP\Storage\File\FileHandler; */ final class MySQLFileParser implements DatabaseFileInterface { + /** + * @var FileHandler + */ + private $fileHandler; + + /** + * MySQLFileParser constructor. + * + * @param FileHandler $fileHandler + */ + public function __construct(FileHandler $fileHandler) + { + $this->fileHandler = $fileHandler; + } + /** * Parses a database script file and returns an array of lines parsed * - * @param \SP\Storage\File\FileHandler $fileHandler - * @param string $delimiter + * @param string $delimiter * * @return array * @throws FileException */ - public function parse(FileHandler $fileHandler, $delimiter = ';') + public function parse($delimiter = ';') { $queries = []; $query = ''; $delimiterLength = strlen($delimiter); - $handle = $fileHandler->open('rb'); + $this->fileHandler->checkIsReadable(); + + $handle = $this->fileHandler->open('rb'); while (($buffer = fgets($handle)) !== false) { $buffer = trim($buffer); @@ -60,10 +76,9 @@ final class MySQLFileParser implements DatabaseFileInterface ) { // CHecks if delimiter based EOL is reached $end = strrpos($buffer, $delimiter) === $length - $delimiterLength; - // Checks if line is an SQL statement wrapped by a comment - $setComment = preg_match('#^(?/\*!\d+.*\*/)#', $buffer, $matches); - if ($setComment) { + // Checks if line is an SQL statement wrapped by a comment + if (preg_match('#^(?/\*!\d+.*\*/)#', $buffer, $matches)) { if (!$end) { $query .= $matches['stmt'] . PHP_EOL; } else { @@ -83,7 +98,7 @@ final class MySQLFileParser implements DatabaseFileInterface } } - $fileHandler->close(); + $this->fileHandler->close(); return $queries; } diff --git a/phpunit.xml b/phpunit.xml index 3eb7d85b..1c449897 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -16,6 +16,12 @@ ./lib/SP + + ./lib/SP/DataModel + ./lib/SP/Html/Assets + ./lib/SP/Html/DataGrid + ./lib/SP/Config/ConfigData.php + diff --git a/test/res/config/config.xml b/test/res/config/config.xml index 7ee7de46..1251ab17 100644 --- a/test/res/config/config.xml +++ b/test/res/config/config.xml @@ -9,11 +9,11 @@ 1 1 - 3888857db15931e50441f6883ede96d91c083781 + 000b2db8af6fd590e594af19112c828447811683 0 0 - 1533671493 - d71d680b518afdf0e13550e796cfe4919b7489fe + 1533733194 + d25fdd227d15ecd3c67b032f22c2b8034292ad87 @@ -32,7 +32,7 @@ 0 - e1b0a6c6eccc7bf24964e0835166852b0770bb97 + 2af7a5b01fa3959248f9e054b5c2c88a0646016b PDF JPG