Skip to content

Commit

Permalink
Some refactoring and catch exceptions when getting services
Browse files Browse the repository at this point in the history
  • Loading branch information
sowbiba committed Dec 11, 2023
1 parent f6f45ed commit 3733969
Show file tree
Hide file tree
Showing 38 changed files with 559 additions and 363 deletions.
33 changes: 24 additions & 9 deletions src/Api/Security/AdminAuthenticationProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
use PrestaShop\PrestaShop\Core\Crypto\Hashing;
use PrestaShop\PrestaShop\Core\Domain\Employee\Exception\EmployeeException;
use PrestaShop\PrestaShop\Core\Exception\CoreException;
use Shop;
use Tab;
use Tools;

Expand Down Expand Up @@ -80,6 +81,9 @@ public function __construct(
$this->cacheProvider = $cacheProvider;
}

/**
* @throws \Doctrine\DBAL\Exception
*/
public function createApiUser(): ?Employee
{
$moduleCacheDir = sprintf('%s/var/modules/ps_mbo/', rtrim(_PS_ROOT_DIR_, '/'));
Expand Down Expand Up @@ -132,14 +136,13 @@ public function createApiUser(): ?Employee
return $employee;
}

/**
* @throws \Doctrine\DBAL\Exception
*/
public function getApiUser(): ?Employee
{
/**
* @var \Doctrine\DBAL\Connection $connection
*/
$connection = $this->connection;
//Get employee ID
$qb = $connection->createQueryBuilder();
$qb = $this->connection->createQueryBuilder();
$qb->select('e.id_employee')
->from($this->dbPrefix . 'employee', 'e')
->andWhere('e.email = :email')
Expand All @@ -158,7 +161,7 @@ public function getApiUser(): ?Employee
}

/**
* @throws EmployeeException
* @throws \Doctrine\DBAL\Exception
*/
public function ensureApiUserExistence(): ?Employee
{
Expand All @@ -171,6 +174,9 @@ public function ensureApiUserExistence(): ?Employee
return $apiUser;
}

/**
* @throws \Doctrine\DBAL\Exception
*/
public function deletePossibleApiUser(): void
{
$connection = $this->connection;
Expand Down Expand Up @@ -211,6 +217,10 @@ public function apiUserLogin(Employee $apiUser): Cookie
return $cookie;
}

/**
* @throws EmployeeException
* @throws \Doctrine\DBAL\Exception
*/
public function getAdminToken(): string
{
$cacheKey = $this->getAdminTokenCacheKey();
Expand All @@ -234,6 +244,10 @@ public function getAdminToken(): string
return $this->cacheProvider->fetch($cacheKey);
}

/**
* @throws EmployeeException
* @throws \Doctrine\DBAL\Exception
*/
public function getMboJWT(): string
{
$cacheKey = $this->getJwtTokenCacheKey();
Expand All @@ -254,7 +268,8 @@ public function getMboJWT(): string
return $jwtToken;
}

$this->cacheProvider->save($cacheKey, $jwtToken, 0); // Lifetime infinite, will be purged when MBO is uninstalled
// Lifetime infinite, will be purged when MBO is uninstalled
$this->cacheProvider->save($cacheKey, $jwtToken, 0);

return $this->cacheProvider->fetch($cacheKey);
}
Expand Down Expand Up @@ -288,8 +303,8 @@ private function logFailedEmployeeException(Exception $e): void
'shop_mbo_uuid' => Config::getShopMboUuid(),
'shop_mbo_admin_mail' => Config::getShopMboAdminMail(),
'shop_url' => Config::getShopUrl(),
'multishop' => \Shop::isFeatureActive(),
'number_of_shops' => \Shop::getTotalShops(false, null),
'multishop' => Shop::isFeatureActive(),
'number_of_shops' => Shop::getTotalShops(false, null),
]);
}
}
34 changes: 31 additions & 3 deletions src/Api/Service/ModuleTransitionExecutor.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,14 @@
use PrestaShop\Module\Mbo\Helpers\ErrorHelper;
use PrestaShop\Module\Mbo\Module\Command\ModuleStatusTransitionCommand;
use PrestaShop\Module\Mbo\Module\CommandHandler\ModuleStatusTransitionCommandHandler;
use PrestaShop\Module\Mbo\Module\Exception\ModuleNewVersionNotFoundException;
use PrestaShop\Module\Mbo\Module\Exception\ModuleNotFoundException;
use PrestaShop\Module\Mbo\Module\Exception\TransitionCommandToModuleStatusException;
use PrestaShop\Module\Mbo\Module\Exception\TransitionFailedException;
use PrestaShop\Module\Mbo\Module\Exception\UnauthorizedModuleTransitionException;
use PrestaShop\Module\Mbo\Module\Exception\UnexpectedModuleSourceContentException;
use PrestaShop\Module\Mbo\Module\Exception\UnknownModuleTransitionCommandException;
use PrestaShop\Module\Mbo\Module\Module;
use PrestaShop\Module\Mbo\Module\ValueObject\ModuleTransitionCommand;
use PrestaShop\PrestaShop\Core\Cache\Clearer\CacheClearerInterface;
use Symfony\Component\HttpFoundation\Session\Session;
Expand Down Expand Up @@ -54,6 +62,16 @@ public function canExecute(string $service): bool

/**
* {@inheritDoc}
*
* @throws UnknownModuleTransitionCommandException
* @throws QueryParamsException
* @throws ModuleNewVersionNotFoundException
* @throws ModuleNotFoundException
* @throws TransitionCommandToModuleStatusException
* @throws TransitionFailedException
* @throws UnauthorizedModuleTransitionException
* @throws UnexpectedModuleSourceContentException
* @throws \Exception
*/
public function execute(...$parameters): array
{
Expand All @@ -73,16 +91,26 @@ public function execute(...$parameters): array
throw new QueryParamsException('You need transition and module parameters');
}

try {
$session = $psMbo->get('session');
if (!$session instanceof Session) {
throw new \Exception('ModuleTransitionExecutor : Session not found');
}
} catch (\Exception $e) {
ErrorHelper::reportError($e);
throw $e;
}
// Authenticate user to addons if credentials are provided
$this->authenticateAddonsUser($psMbo->get('session'));
$this->authenticateAddonsUser($session);

$command = new ModuleStatusTransitionCommand($transition, $moduleName, $moduleId, $moduleVersion, $source);

/** @var \PrestaShop\Module\Mbo\Module\Module $module */
$module = $this->moduleStatusTransitionCommandHandler->handle($command);

$moduleUrls = $module->get('urls');
$configUrl = (bool) $module->get('is_configurable') && isset($moduleUrls['configure']) ? $this->generateTokenizedModuleActionUrl($moduleUrls['configure']) : null;
$configUrl = $module->get('is_configurable') && isset($moduleUrls['configure'])
? $this->generateTokenizedModuleActionUrl($moduleUrls['configure'])
: null;

if (ModuleTransitionCommand::MODULE_COMMAND_DOWNLOAD === $transition) {
// Clear the cache after download to force reload module services
Expand Down
29 changes: 29 additions & 0 deletions src/Exception/ExpectedServiceNotFoundException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License version 3.0
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/AFL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @author PrestaShop SA and Contributors <[email protected]>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/AFL-3.0 Academic Free License version 3.0
*/
declare(strict_types=1);

namespace PrestaShop\Module\Mbo\Exception;

use Exception;

class ExpectedServiceNotFoundException extends Exception
{

}
47 changes: 9 additions & 38 deletions src/Module/ActionsManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ class ActionsManager

/**
* @var Repository
* @TODO : Not needed anymore
*/
private $moduleRepository;

Expand Down Expand Up @@ -69,54 +70,24 @@ public function downloadModule(int $moduleId): string

/**
* @throws UnexpectedModuleSourceContentException
* @throws ModuleNewVersionNotFoundException
* @throws SourceHandlerNotFoundException
* @throws FileNotFoundException
*/
public function downloadAndReplaceModuleFiles(string $moduleName, string $source): void
{
if (is_string($source) && AddonsUrlSourceRetriever::assertIsAddonsUrl($source) && strpos($source, 'shop_url') === false) {
if (
AddonsUrlSourceRetriever::assertIsAddonsUrl($source)
&& strpos($source, 'shop_url') === false
) {
$source .= '&shop_url=' . Config::getShopUrl();
}

$this->filesManager->canInstallFromSource($source);

$this->filesManager->deleteModuleDirectory($moduleName);

$this->filesManager->installFromSource($source);
}

/**
* @param string $moduleName
*
* @return \stdClass|null
*/
public function findVersionForUpdate(string $moduleName): ?\stdClass
{
$db = \Db::getInstance();
$request = 'SELECT `version` FROM `' . _DB_PREFIX_ . "module` WHERE name='" . $moduleName . "'";

/** @var string|false $moduleCurrentVersion */
$moduleCurrentVersion = $db->getValue($request);

if (!$moduleCurrentVersion) {
return null;
}
// We need to clear cache to get fresh data from addons
$this->moduleRepository->clearCache();

$module = $this->moduleRepository->getApiModule($moduleName);

if (null === $module) {
return null;
if ('ps_mbo' === $moduleName) {
$this->filesManager->deleteModuleDirectory($moduleName);
}

$versionAvailable = (string) $module->version_available;

// If the current installed version is greater or equal than the one returned by Addons, do nothing
if (version_compare($versionAvailable, $moduleCurrentVersion, 'gt')) {
return $module;
}

return null;
$this->filesManager->installFromSource($source);
}
}
2 changes: 1 addition & 1 deletion src/Module/Command/ModuleStatusTransitionCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ public function __construct(
$this->moduleId = $moduleId;
$this->moduleVersion = $moduleVersion;

if (in_array($command, [ModuleTransitionCommand::MODULE_COMMAND_DOWNLOAD])) {
if ($command == ModuleTransitionCommand::MODULE_COMMAND_DOWNLOAD) {
if ('undefined' === $source) {
$source = null;
}
Expand Down
57 changes: 31 additions & 26 deletions src/Module/CommandHandler/ModuleStatusTransitionCommandHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,7 @@
use PrestaShop\Module\Mbo\Module\ActionsManager;
use PrestaShop\Module\Mbo\Module\Command\ModuleStatusTransitionCommand;
use PrestaShop\Module\Mbo\Module\Exception\ModuleNewVersionNotFoundException;
use PrestaShop\Module\Mbo\Module\Exception\ModuleNotFoundException;
use PrestaShop\Module\Mbo\Module\Exception\TransitionCommandToModuleStatusException;
use PrestaShop\Module\Mbo\Module\Exception\TransitionFailedException;
use PrestaShop\Module\Mbo\Module\Exception\UnauthorizedModuleTransitionException;
use PrestaShop\Module\Mbo\Module\Exception\UnexpectedModuleSourceContentException;
use PrestaShop\Module\Mbo\Module\Module;
Expand All @@ -35,6 +33,7 @@
use PrestaShop\Module\Mbo\Module\TransitionModule;
use PrestaShop\Module\Mbo\Module\ValueObject\ModuleTransitionCommand;
use PrestaShop\Module\Mbo\Module\Workflow\ModuleStateMachine;
use PrestaShop\PrestaShop\Core\Module\SourceHandler\SourceHandlerNotFoundException;

final class ModuleStatusTransitionCommandHandler
{
Expand All @@ -47,10 +46,12 @@ final class ModuleStatusTransitionCommandHandler
* @var Repository
*/
private $moduleRepository;

/**
* @var ActionsManager
*/
private $actionsManager;

/**
* @var ModuleBuilder
*/
Expand All @@ -71,14 +72,12 @@ public function __construct(
/**
* @throws UnexpectedModuleSourceContentException
* @throws ModuleNewVersionNotFoundException
* @throws ModuleNotFoundException
* @throws UnauthorizedModuleTransitionException
* @throws TransitionCommandToModuleStatusException
* @throws TransitionFailedException
* @throws SourceHandlerNotFoundException
*/
public function handle(ModuleStatusTransitionCommand $command): Module
{
$apiModule = null;
$moduleName = $command->getModuleName();
$moduleId = $command->getModuleId();
$moduleVersion = $command->getModuleVersion();
Expand All @@ -88,37 +87,37 @@ public function handle(ModuleStatusTransitionCommand $command): Module
// If not exist, get it from the Module Distribution API
$dbModule = $this->moduleRepository->findInDatabaseByName($moduleName);

if (null !== $dbModule) {
$module = new TransitionModule(
$moduleName,
$dbModule['version'],
$dbModule['installed'],
$dbModule['active_on_mobile'],
$dbModule['active']
);
} else {
$module = new TransitionModule(
$moduleName,
$moduleVersion,
false,
false,
false
);
}
$module = new TransitionModule(
$moduleName,
$dbModule ? $dbModule['version'] : $moduleVersion,
$dbModule ? $dbModule['installed'] : false,
$dbModule ? $dbModule['active_on_mobile'] : false,
$dbModule ? $dbModule['active'] : false
);

// Check if transition asked can be mapped to an existing target status
$transitionCommand = $command->getCommand()->getValue();

// Download a module before upgrade is not an actual module transition, so it cannot be handled by the StateMachine
// Download a module before upgrade is not an actual module transition, we do not use the StateMachine
if (ModuleTransitionCommand::MODULE_COMMAND_DOWNLOAD === $transitionCommand) {
if (null === $source) {
$source = $this->actionsManager->downloadModule($moduleId);
}

$this->actionsManager->downloadAndReplaceModuleFiles($moduleName, $source);
} else {
if (!array_key_exists($transitionCommand, ModuleTransitionCommand::MAPPING_TRANSITION_COMMAND_TARGET_STATUS)) {
throw new TransitionCommandToModuleStatusException(sprintf('Unable to map module transition command given %s', $transitionCommand));
if (
!array_key_exists(
$transitionCommand,
ModuleTransitionCommand::MAPPING_TRANSITION_COMMAND_TARGET_STATUS
)
) {
throw new TransitionCommandToModuleStatusException(
sprintf(
'Unable to map module transition command given %s',
$transitionCommand
)
);
}

// Compute the state machine transition name
Expand All @@ -133,7 +132,13 @@ public function handle(ModuleStatusTransitionCommand $command): Module

// Check if the transition asked is possible
if (!$this->moduleStateMachine->can($module, $transitionName)) {
throw new UnauthorizedModuleTransitionException(sprintf('Transition "%s" is not possible for module "%s"', $transitionCommand, $moduleName));
throw new UnauthorizedModuleTransitionException(
sprintf(
'Transition "%s" is not possible for module "%s"',
$transitionCommand,
$moduleName
)
);
}

// Execute the transition
Expand Down
2 changes: 1 addition & 1 deletion src/Module/FilesManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ public function installFromSource(string $source): void
public function canInstallFromSource(string $source)
{
try {
$handler = $this->sourceHandlerFactory->getHandler($source);
$this->sourceHandlerFactory->getHandler($source);
} catch(SourceHandlerNotFoundException $e) {
ErrorHelper::reportError($e);
throw $e;
Expand Down
Loading

0 comments on commit 3733969

Please sign in to comment.