From 8cbb762c39d90f6497d2d5f2babb57d3997cd15f Mon Sep 17 00:00:00 2001 From: Henning Leutz <leutz@pcsg.de> Date: Thu, 21 Sep 2023 14:22:35 +0200 Subject: [PATCH] refactor: psr12 + code style --- src/QUI/ERP/Coupons/CodeGenerator.php | 20 +- .../Coupons/CodeGenerators/SimpleString.php | 14 +- src/QUI/ERP/Coupons/CodeGenerators/Uuid.php | 2 +- src/QUI/ERP/Coupons/CouponCode.php | 37 ++-- src/QUI/ERP/Coupons/Handler.php | 188 ++++++++++-------- .../Products/DigitalCouponProductType.php | 4 +- .../Products/PhysicalCouponProductType.php | 4 +- 7 files changed, 145 insertions(+), 124 deletions(-) diff --git a/src/QUI/ERP/Coupons/CodeGenerator.php b/src/QUI/ERP/Coupons/CodeGenerator.php index 65e532b..99b4052 100644 --- a/src/QUI/ERP/Coupons/CodeGenerator.php +++ b/src/QUI/ERP/Coupons/CodeGenerator.php @@ -3,8 +3,12 @@ namespace QUI\ERP\Coupons; use QUI; +use QUI\Exception; use QUI\Utils\System\File; +use function basename; +use function call_user_func; + /** * Class CodeGenerator * @@ -16,9 +20,9 @@ class CodeGenerator * Generate a new, random Invite Code * * @return string - * @throws \QUI\Exception + * @throws Exception */ - public static function generate() + public static function generate(): string { $generator = '\\QUI\\ERP\\Coupons\\CodeGenerators\\' . self::getCurrentGenerator(); @@ -29,16 +33,16 @@ public static function generate() $prefix = ''; } - return \call_user_func($generator . '::generate', $prefix); + return call_user_func($generator . '::generate', $prefix); } /** * Get CodeGenerator that is currently set * * @return string - FQ class name - * @throws \QUI\Exception + * @throws Exception */ - protected static function getCurrentGenerator() + protected static function getCurrentGenerator(): string { $Config = QUI::getPackage('quiqqer/coupons')->getConfig(); $currentGenerator = $Config->get('settings', 'codeGenerator'); @@ -54,15 +58,15 @@ protected static function getCurrentGenerator() * Get list of all available CodeGenerators * * @return array - * @throws \QUI\Exception + * @throws Exception */ - public static function getList() + public static function getList(): array { $dir = QUI::getPackage('quiqqer/coupons')->getDir() . 'src/QUI/ERP/Coupons/CodeGenerators'; $generators = []; foreach (File::readDir($dir, true) as $file) { - $generators[] = \basename($file, '.php'); + $generators[] = basename($file, '.php'); } return $generators; diff --git a/src/QUI/ERP/Coupons/CodeGenerators/SimpleString.php b/src/QUI/ERP/Coupons/CodeGenerators/SimpleString.php index bc17f69..060098d 100644 --- a/src/QUI/ERP/Coupons/CodeGenerators/SimpleString.php +++ b/src/QUI/ERP/Coupons/CodeGenerators/SimpleString.php @@ -9,6 +9,10 @@ use QUI\ERP\Coupons\CodeGeneratorInterface; use QUI\ERP\Coupons\Handler; +use function array_merge; +use function random_int; +use function range; + /** * Class SimpleString * @@ -25,11 +29,11 @@ class SimpleString implements CodeGeneratorInterface * @return string * @throws \Exception */ - public static function generate($prefix = '') + public static function generate($prefix = ''): string { - $characters = \array_merge( - \range('A', 'Z'), - \range(0, 9) + $characters = array_merge( + range('A', 'Z'), + range(0, 9) ); $count = count($characters) - 1; @@ -38,7 +42,7 @@ public static function generate($prefix = '') $code = $prefix; for ($i = 0; $i < self::CODE_LENGTH; $i++) { - $code .= $characters[\random_int(0, $count)]; + $code .= $characters[random_int(0, $count)]; } } while (Handler::existsCode($code)); diff --git a/src/QUI/ERP/Coupons/CodeGenerators/Uuid.php b/src/QUI/ERP/Coupons/CodeGenerators/Uuid.php index 26e76f8..662b3c2 100644 --- a/src/QUI/ERP/Coupons/CodeGenerators/Uuid.php +++ b/src/QUI/ERP/Coupons/CodeGenerators/Uuid.php @@ -13,7 +13,7 @@ class Uuid implements CodeGeneratorInterface * @param string $prefix (optional) * @return string */ - public static function generate($prefix = '') + public static function generate($prefix = ''): string { return $prefix . UuidCreator::uuid1()->toString(); } diff --git a/src/QUI/ERP/Coupons/CouponCode.php b/src/QUI/ERP/Coupons/CouponCode.php index b2cec78..4793245 100644 --- a/src/QUI/ERP/Coupons/CouponCode.php +++ b/src/QUI/ERP/Coupons/CouponCode.php @@ -16,6 +16,7 @@ use function is_array; use function is_null; use function json_decode; +use function json_encode; use function method_exists; /** @@ -28,7 +29,7 @@ class CouponCode * * @var int */ - protected $id; + protected int $id; /** * Actual code @@ -68,16 +69,16 @@ class CouponCode /** * Creation Date * - * @var \DateTime + * @var DateTime|null */ - protected $CreateDate; + protected ?DateTime $CreateDate = null; /** * Date until the CouponCode is valid * - * @var \DateTime + * @var DateTime|null */ - protected $ValidUntilDate = null; + protected ?DateTime $ValidUntilDate = null; /** * CouponCode title @@ -106,7 +107,7 @@ class CouponCode * @param int $id - Invite Code ID * * @throws CouponCodeException - * @throws \Exception + * @throws Exception */ public function __construct(int $id) { @@ -192,7 +193,7 @@ public function getCode(): string } /** - * @return \DateTime + * @return DateTime */ public function getCreateDate(): DateTime { @@ -210,7 +211,7 @@ public function getUsages(): array } /** - * @return \DateTime|null + * @return DateTime|null */ public function getValidUntilDate(): ?DateTime { @@ -275,13 +276,13 @@ public function getGroupIds(): array * * Hint: This may invalidate the code for future use * - * @param QUI\Users\User $User - The user that redeems the CouponCode [if omitted use Session User] - * @param QUI\ERP\Order\Order $Order (optional) - Link redemption to a specific Order + * @param QUI\Interfaces\Users\User $User - The user that redeems the CouponCode [if omitted use Session User] + * @param QUI\ERP\Order\Order|null $Order (optional) - Link redemption to a specific Order * @return void * @throws CouponCodeException * @throws QUI\Exception */ - public function redeem($User = null, $Order = null) + public function redeem(QUI\Interfaces\Users\User $User = null, QUI\ERP\Order\Order $Order = null) { if (is_null($User)) { $User = QUI::getUserBySession(); @@ -305,7 +306,7 @@ public function redeem($User = null, $Order = null) QUI::getDataBase()->update( Handler::getTable(), - ['usages' => \json_encode($this->usages)], + ['usages' => json_encode($this->usages)], ['id' => $this->id] ); @@ -327,7 +328,7 @@ public function redeem($User = null, $Order = null) * @return void * @throws CouponCodeException - Thrown if not redeemable by the given User */ - public function checkRedemption($User) + public function checkRedemption(QUI\Interfaces\Users\User $User) { if (!$this->isValid()) { throw new CouponCodeException([ @@ -449,7 +450,7 @@ public function checkRedemption($User) * @param OrderInterface|null $Order * @throws CouponCodeException */ - public function checkOrderRedemption($Order) + public function checkOrderRedemption(?OrderInterface $Order) { if ($Order === null) { return; @@ -495,11 +496,11 @@ public function checkOrderRedemption($Order) /** * Check if the given User can redeem this CouponCode * - * @param QUI\Users\User $User - If omitted, use session user - * @param OrderInterface $Order + * @param QUI\Interfaces\Users\User $User - If omitted, use session user + * @param OrderInterface|null $Order * @return bool */ - public function isRedeemable($User = null, $Order = null): bool + public function isRedeemable(QUI\Interfaces\Users\User $User = null, OrderInterface $Order = null): bool { try { $this->checkRedemption($User); @@ -553,7 +554,7 @@ public function hasUserRedeemed(QUI\Interfaces\Users\User $User): bool * Permanently delete this CouponCode * * @return void - * @throws \QUI\Permissions\Exception + * @throws QUI\Permissions\Exception */ public function delete() { diff --git a/src/QUI/ERP/Coupons/Handler.php b/src/QUI/ERP/Coupons/Handler.php index cd62db5..0a292f7 100644 --- a/src/QUI/ERP/Coupons/Handler.php +++ b/src/QUI/ERP/Coupons/Handler.php @@ -2,10 +2,21 @@ namespace QUI\ERP\Coupons; +use DateInterval; +use DateTime; +use Exception; +use PDO; use QUI; +use QUI\ERP\Discount\Handler as DiscountHandler; use QUI\Utils\Grid; use QUI\Utils\Security\Orthos; -use QUI\ERP\Discount\Handler as DiscountHandler; + +use function current; +use function explode; +use function implode; +use function is_null; +use function json_encode; +use function preg_replace; /** * Class Handler @@ -34,7 +45,7 @@ class Handler * * @var CouponCode[] */ - protected static $couponCodes = []; + protected static array $couponCodes = []; /** * Get CouponCode @@ -43,7 +54,7 @@ class Handler * @return CouponCode * @throws CouponCodeException */ - public static function getCouponCode($id) + public static function getCouponCode(int $id): CouponCode { if (isset(self::$couponCodes[$id])) { return self::$couponCodes[$id]; @@ -61,18 +72,19 @@ public static function getCouponCode($id) * @return CouponCode * * @throws CouponCodeException + * @throws QUI\Database\Exception */ - public static function getCouponCodeByCode($code) + public static function getCouponCodeByCode(string $code): CouponCode { $result = QUI::getDataBase()->fetch([ 'select' => [ 'id' ], - 'from' => self::getTable(), - 'where' => [ + 'from' => self::getTable(), + 'where' => [ 'code' => $code ], - 'limit' => 1 + 'limit' => 1 ]); if (empty($result)) { @@ -95,9 +107,9 @@ public static function getCouponCodeByCode($code) * @param array $settings (optional) - If omitted a random default CouponCode is generated * @return CouponCode * - * @throws \Exception + * @throws Exception */ - public static function createCouponCode($discountIds, $settings = []) + public static function createCouponCode(array $discountIds, array $settings = []): CouponCode { $DiscountHandler = DiscountHandler::getInstance(); @@ -112,19 +124,19 @@ public static function createCouponCode($discountIds, $settings = []) foreach ($discountIds as $discountId) { try { $DiscountHandler->getChild($discountId); - } catch (\Exception $Exception) { + } catch (Exception $Exception) { throw new CouponCodeException([ 'quiqqer/coupons', 'exception.Handler.discount_error', [ 'discountId' => $discountId, - 'error' => $Exception->getMessage() + 'error' => $Exception->getMessage() ] ]); } } - $Now = new \DateTime(); + $Now = new DateTime(); if (!empty($settings['code'])) { if (self::existsCode($settings['code'])) { @@ -149,24 +161,24 @@ public static function createCouponCode($discountIds, $settings = []) } $couponCode = [ - 'title' => empty($settings['title']) ? null : $settings['title'], - 'createDate' => $Now->format('Y-m-d H:i:s'), - 'code' => $code, - 'maxUsages' => $maxUsages, - 'discountIds' => \json_encode($discountIds) + 'title' => empty($settings['title']) ? null : $settings['title'], + 'createDate' => $Now->format('Y-m-d H:i:s'), + 'code' => $code, + 'maxUsages' => $maxUsages, + 'discountIds' => json_encode($discountIds) ]; if (!empty($settings['validUntilDate'])) { - $ValidUntil = new \DateTime($settings['validUntilDate']); + $ValidUntil = new DateTime($settings['validUntilDate']); $couponCode['validUntilDate'] = $ValidUntil->format('Y-m-d H:i:s'); } if (!empty($settings['userIds'])) { - $couponCode['userIds'] = \json_encode(\explode(",", $settings['userIds'])); + $couponCode['userIds'] = json_encode(explode(",", $settings['userIds'])); } if (!empty($settings['groupIds'])) { - $couponCode['groupIds'] = \json_encode(\explode(",", $settings['groupIds'])); + $couponCode['groupIds'] = json_encode(explode(",", $settings['groupIds'])); } QUI::getDataBase()->insert( @@ -185,9 +197,9 @@ public static function createCouponCode($discountIds, $settings = []) * @param array $settings (optional) - If omitted a random default CouponCode is generated * @return CouponCode * - * @throws \Exception + * @throws Exception */ - public static function editCouponCode($id, $discountIds, $settings = []) + public static function editCouponCode(int $id, array $discountIds, array $settings = []): CouponCode { QUI\Permissions\Permission::checkPermission(self::PERMISSION_EDIT); @@ -208,23 +220,25 @@ public static function editCouponCode($id, $discountIds, $settings = []) foreach ($discountIds as $discountId) { try { $DiscountHandler->getChild($discountId); - } catch (\Exception $Exception) { + } catch (Exception $Exception) { throw new CouponCodeException([ 'quiqqer/coupons', 'exception.Handler.discount_error', [ 'discountId' => $discountId, - 'error' => $Exception->getMessage() + 'error' => $Exception->getMessage() ] ]); } } - $Now = new \DateTime(); + $Now = new DateTime(); if (!empty($settings['code'])) { - if ($CouponCode->getCode() !== $settings['code'] - && self::existsCode($settings['code'])) { + if ( + $CouponCode->getCode() !== $settings['code'] + && self::existsCode($settings['code']) + ) { throw new CouponCodeException([ 'quiqqer/coupons', 'exception.Handler.code_already_exists', @@ -246,28 +260,28 @@ public static function editCouponCode($id, $discountIds, $settings = []) } $couponCode = [ - 'title' => empty($settings['title']) ? null : $settings['title'], - 'createDate' => $Now->format('Y-m-d H:i:s'), - 'code' => $code, - 'maxUsages' => $maxUsages, - 'discountIds' => \json_encode($discountIds) + 'title' => empty($settings['title']) ? null : $settings['title'], + 'createDate' => $Now->format('Y-m-d H:i:s'), + 'code' => $code, + 'maxUsages' => $maxUsages, + 'discountIds' => json_encode($discountIds) ]; if (!empty($settings['validUntilDate'])) { - $ValidUntil = new \DateTime($settings['validUntilDate']); + $ValidUntil = new DateTime($settings['validUntilDate']); $couponCode['validUntilDate'] = $ValidUntil->format('Y-m-d H:i:s'); } else { $couponCode['validUntilDate'] = null; } if (!empty($settings['userIds'])) { - $couponCode['userIds'] = \json_encode(\explode(",", $settings['userIds'])); + $couponCode['userIds'] = json_encode(explode(",", $settings['userIds'])); } else { $couponCode['userIds'] = null; } if (!empty($settings['groupIds'])) { - $couponCode['groupIds'] = \json_encode(\explode(",", $settings['groupIds'])); + $couponCode['groupIds'] = json_encode(explode(",", $settings['groupIds'])); } else { $couponCode['groupIds'] = null; } @@ -289,11 +303,11 @@ public static function editCouponCode($id, $discountIds, $settings = []) * @return CouponCode[]|int * @throws CouponCodeException */ - public static function search($searchParams, $countOnly = false) + public static function search(array $searchParams, bool $countOnly = false) { $couponCodes = []; - $Grid = new Grid($searchParams); - $gridParams = $Grid->parseDBParams($searchParams); + $Grid = new Grid($searchParams); + $gridParams = $Grid->parseDBParams($searchParams); $binds = []; $where = []; @@ -304,7 +318,7 @@ public static function search($searchParams, $countOnly = false) $sql = "SELECT id"; } - $sql .= " FROM `".self::getTable()."`"; + $sql .= " FROM `" . self::getTable() . "`"; if (!empty($searchParams['search'])) { $searchColumns = [ @@ -316,49 +330,47 @@ public static function search($searchParams, $countOnly = false) $whereOr = []; foreach ($searchColumns as $searchColumn) { - $whereOr[] = '`'.$searchColumn.'` LIKE :search'; + $whereOr[] = '`' . $searchColumn . '` LIKE :search'; } if (!empty($whereOr)) { - $where[] = '('.\implode(' OR ', $whereOr).')'; + $where[] = '(' . implode(' OR ', $whereOr) . ')'; $binds['search'] = [ - 'value' => '%'.$searchParams['search'].'%', - 'type' => \PDO::PARAM_STR + 'value' => '%' . $searchParams['search'] . '%', + 'type' => PDO::PARAM_STR ]; } } // build WHERE query string if (!empty($where)) { - $sql .= " WHERE ".\implode(" AND ", $where); + $sql .= " WHERE " . implode(" AND ", $where); } // ORDER if (!empty($searchParams['sortOn']) ) { $sortOn = Orthos::clear($searchParams['sortOn']); - $order = "ORDER BY ".$sortOn; + $order = "ORDER BY " . $sortOn; - if (isset($searchParams['sortBy']) && - !empty($searchParams['sortBy']) - ) { - $order .= " ".Orthos::clear($searchParams['sortBy']); + if (!empty($searchParams['sortBy'])) { + $order .= " " . Orthos::clear($searchParams['sortBy']); } else { $order .= " ASC"; } - $sql .= " ".$order; + $sql .= " " . $order; } else { $sql .= " ORDER BY id DESC"; } // LIMIT if (!empty($gridParams['limit']) && !$countOnly) { - $sql .= " LIMIT ".$gridParams['limit']; + $sql .= " LIMIT " . $gridParams['limit']; } else { if (!$countOnly) { - $sql .= " LIMIT ".(int)20; + $sql .= " LIMIT " . 20; } } @@ -366,22 +378,22 @@ public static function search($searchParams, $countOnly = false) // bind search values foreach ($binds as $var => $bind) { - $Stmt->bindValue(':'.$var, $bind['value'], $bind['type']); + $Stmt->bindValue(':' . $var, $bind['value'], $bind['type']); } try { $Stmt->execute(); - $result = $Stmt->fetchAll(\PDO::FETCH_ASSOC); - } catch (\Exception $Exception) { + $result = $Stmt->fetchAll(PDO::FETCH_ASSOC); + } catch (Exception $Exception) { QUI\System\Log::addError( - self::class.' :: search() -> '.$Exception->getMessage() + self::class . ' :: search() -> ' . $Exception->getMessage() ); return []; } if ($countOnly) { - return (int)\current(\current($result)); + return (int)current(current($result)); } foreach ($result as $row) { @@ -392,20 +404,22 @@ public static function search($searchParams, $countOnly = false) } /** - * Check if an invite code already eixsts + * Check if a CouponCode exists by its code * - * @param string $code - * @return bool + * @param string $code The code of the CouponCode + * @return bool Returns true if the CouponCode exists, false otherwise + * + * @throws QUI\Database\Exception */ - public static function existsCode($code) + public static function existsCode(string $code): bool { $result = QUI::getDataBase()->fetch([ 'select' => 'id', - 'from' => self::getTable(), - 'where' => [ + 'from' => self::getTable(), + 'where' => [ 'code' => $code ], - 'limit' => 1 + 'limit' => 1 ]); return !empty($result); @@ -419,7 +433,7 @@ public static function existsCode($code) public static function getRegistrationSite() { try { - $Conf = QUI::getPackage('quiqqer/coupons')->getConfig(); + $Conf = QUI::getPackage('quiqqer/coupons')->getConfig(); $regSite = $Conf->get('settings', 'registrationSite'); } catch (QUI\Exception $Exception) { QUI\System\Log::writeDebugException($Exception); @@ -433,7 +447,7 @@ public static function getRegistrationSite() try { return QUI\Projects\Site\Utils::getSiteByLink($regSite); - } catch (\Exception $Exception) { + } catch (Exception $Exception) { return false; } } @@ -441,28 +455,27 @@ public static function getRegistrationSite() /** * Deletes all CouponCodes that are expired * - * @param int $days (optional) - Delete expired Codes that are older than X days [default: delete all] + * @param int|null $days (optional) - Delete expired Codes that are older than X days [default: delete all] * @return void * - * @throws \Exception + * @throws Exception */ - public static function deleteExpiredCouponCodes($days = null) + public static function deleteExpiredCouponCodes(int $days = null) { - $Now = new \DateTime(); + $Now = new DateTime(); $where = [ 'validUntilDate' => [ - 'type' => '<=', + 'type' => '<=', 'value' => $Now->format('Y-m-d H:i:s') ] ]; - if (!\is_null($days)) { - $days = (int)$days; - $OldDate = new \DateTime(); - $OldDate->sub(new \DateInterval('P'.$days.'D')); + if (!is_null($days)) { + $OldDate = new DateTime(); + $OldDate->sub(new DateInterval('P' . $days . 'D')); $where['validUntilDate'] = [ - 'type' => '<=', + 'type' => '<=', 'value' => $OldDate->format('Y-m-d H:i:s') ]; } @@ -476,27 +489,26 @@ public static function deleteExpiredCouponCodes($days = null) /** * Deletes all CouponCodes that have been redeemed * - * @param int $days (optional) - Delete redeemed Codes that are older than X days [default: delete all] + * @param int|null $days (optional) - Delete redeemed Codes that are older than X days [default: delete all] * @return void * - * @throws \Exception + * @throws Exception */ - public static function deleteRedeemedCouponCodes($days = null) + public static function deleteRedeemedCouponCodes(int $days = null) { $where = [ 'useDate' => [ - 'type' => 'NOT', + 'type' => 'NOT', 'value' => null ] ]; - if (!\is_null($days)) { - $days = (int)$days; - $OldDate = new \DateTime(); - $OldDate->sub(new \DateInterval('P'.$days.'D')); + if (!is_null($days)) { + $OldDate = new DateTime(); + $OldDate->sub(new DateInterval('P' . $days . 'D')); $where['useDate'] = [ - 'type' => '<=', + 'type' => '<=', 'value' => $OldDate->format('Y-m-d H:i:s') ]; } @@ -513,9 +525,9 @@ public static function deleteRedeemedCouponCodes($days = null) * @param string $code * @return string */ - public static function sanitizeCode($code) + public static function sanitizeCode(string $code): string { - return \preg_replace('#[^A-Za-z0-9\.\-_\*&$% ]#i', '', $code); + return preg_replace('#[^A-Za-z0-9\.\-_\*&$% ]#i', '', $code); } /** @@ -523,7 +535,7 @@ public static function sanitizeCode($code) * * @return string */ - public static function getTable() + public static function getTable(): string { return QUI::getDBTableName('quiqqer_coupons'); } diff --git a/src/QUI/ERP/Coupons/Products/DigitalCouponProductType.php b/src/QUI/ERP/Coupons/Products/DigitalCouponProductType.php index 311d516..87109fa 100644 --- a/src/QUI/ERP/Coupons/Products/DigitalCouponProductType.php +++ b/src/QUI/ERP/Coupons/Products/DigitalCouponProductType.php @@ -52,7 +52,7 @@ public function __construct($pid, $product = []) * @param QUI\Locale $Locale * @return string */ - public static function getTypeTitle($Locale = null) + public static function getTypeTitle($Locale = null): string { if ($Locale === null) { $Locale = QUI::getLocale(); @@ -65,7 +65,7 @@ public static function getTypeTitle($Locale = null) * @param QUI\Locale $Locale * @return string */ - public static function getTypeDescription($Locale = null) + public static function getTypeDescription($Locale = null): string { if ($Locale === null) { $Locale = QUI::getLocale(); diff --git a/src/QUI/ERP/Coupons/Products/PhysicalCouponProductType.php b/src/QUI/ERP/Coupons/Products/PhysicalCouponProductType.php index 4af98ca..c997533 100644 --- a/src/QUI/ERP/Coupons/Products/PhysicalCouponProductType.php +++ b/src/QUI/ERP/Coupons/Products/PhysicalCouponProductType.php @@ -51,7 +51,7 @@ public function __construct($pid, $product = []) * @param QUI\Locale $Locale * @return string */ - public static function getTypeTitle($Locale = null) + public static function getTypeTitle($Locale = null): string { if ($Locale === null) { $Locale = QUI::getLocale(); @@ -64,7 +64,7 @@ public static function getTypeTitle($Locale = null) * @param QUI\Locale $Locale * @return string */ - public static function getTypeDescription($Locale = null) + public static function getTypeDescription($Locale = null): string { if ($Locale === null) { $Locale = QUI::getLocale(); -- GitLab