From aee4d0863e4a8f18dc8b65f346223609eb4a0384 Mon Sep 17 00:00:00 2001 From: Keywan Ghadami Date: Fri, 12 Feb 2021 17:37:17 +0100 Subject: [PATCH 1/5] add phive for dev tools --- .phive/phars.xml | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .phive/phars.xml diff --git a/.phive/phars.xml b/.phive/phars.xml new file mode 100644 index 00000000..b104a21c --- /dev/null +++ b/.phive/phars.xml @@ -0,0 +1,5 @@ + + + + + From d14f77ae9a6256dde97bdaf94855667f753983e0 Mon Sep 17 00:00:00 2001 From: Keywan Ghadami Date: Fri, 12 Feb 2021 17:39:05 +0100 Subject: [PATCH 2/5] codestyle and duplicate code cleanup --- Controller/AccountPasswordController.php | 143 ----- Controller/RegisterController.php | 108 ---- composer.json | 2 +- metadata.php | 3 +- .../Component}/UserComponent.php | 46 +- src/Controller/AccountPasswordController.php | 67 ++ .../Admin/OxpsPasswordPolicyAdmin.php | 87 +-- .../ControllerWithPasswordPolicy.php | 21 +- .../Controller}/ForgotPasswordController.php | 95 +-- .../Controller}/OxpsPasswordPolicy.php | 10 +- src/Controller/RegisterController.php | 34 + src/Controller/UserController.php | 34 + {Core => src/Core}/PasswordPolicyModule.php | 58 +- {Model => src/Model}/Attempt.php | 78 +-- .../module/Component/UserComponentTest.php | 21 +- .../AccountPasswordControllerTest.php | 25 +- .../Admin/OxpsPasswordPolicyAdminTest.php | 1 + .../ForgotPasswordControllerTest.php | 1 + .../Controller/OxpsPasswordPolicyTest.php | 1 + .../Controller/RegisterControllerTest.php | 1 + .../module/Core/PasswordPolicyModuleTest.php | 12 +- tests/unit/module/Model/AttemptTest.php | 1 + tests/unit/test_config.inc.php | 18 +- tests/unit/test_utils.php | 587 +++++++++--------- translations/de/passwordpolicy_lang.php | 1 + translations/en/passwordpolicy_lang.php | 1 + translations/fr/passwordpolicy_lang.php | 1 + translations/it/passwordpolicy_lang.php | 1 + views/admin/de/passwordpolicy_lang.php | 1 + views/admin/en/passwordpolicy_lang.php | 1 + views/admin/fr/passwordpolicy_lang.php | 1 + views/admin/it/passwordpolicy_lang.php | 1 + 32 files changed, 657 insertions(+), 805 deletions(-) delete mode 100644 Controller/AccountPasswordController.php delete mode 100644 Controller/RegisterController.php rename {Component => src/Component}/UserComponent.php (83%) create mode 100644 src/Controller/AccountPasswordController.php rename {Controller => src/Controller}/Admin/OxpsPasswordPolicyAdmin.php (52%) rename Controller/UserController.php => src/Controller/ControllerWithPasswordPolicy.php (79%) rename {Controller => src/Controller}/ForgotPasswordController.php (67%) rename {Controller => src/Controller}/OxpsPasswordPolicy.php (88%) create mode 100644 src/Controller/RegisterController.php create mode 100644 src/Controller/UserController.php rename {Core => src/Core}/PasswordPolicyModule.php (84%) rename {Model => src/Model}/Attempt.php (74%) diff --git a/Controller/AccountPasswordController.php b/Controller/AccountPasswordController.php deleted file mode 100644 index a11323aa..00000000 --- a/Controller/AccountPasswordController.php +++ /dev/null @@ -1,143 +0,0 @@ -. - * - * @author OXID Professional services - * @link https://www.oxid-esales.com - * @copyright (C) OXID eSales AG 2003-2021 - */ - -namespace OxidProfessionalServices\PasswordPolicy\Controller; - -use \OxidProfessionalServices\PasswordPolicy\Core\PasswordPolicyModule; - -/** - * Password policy main controller - */ -class AccountPasswordController extends AccountPasswordController_parent -{ - - /** - * @var object $_oPasswordPolicy Password policy module instance. - */ - protected $_oPasswordPolicy; - - - /** - * Overridden init method, that creates password policy module object. - */ - public function init() - { - - // Parent call - $this->_oxpsPasswordPolicyAccountPassword_init_parent(); - - $this->setPasswordPolicy(); - } - - - /** - * Set Password Policy instance - * - * @param mixed $mPasswordPolicy - */ - public function setPasswordPolicy($oPasswordPolicy = null) - { - $this->_oPasswordPolicy = is_object($oPasswordPolicy) ? $oPasswordPolicy : oxNew(PasswordPolicyModule::class); - } - - /** - * @return object Password policy module instance. - */ - public function getPasswordPolicy() - { - return $this->_oPasswordPolicy; - } - - - /** - * Overridden password changing form page render method to add password policy parameters. - * - * @return string - */ - public function render() - { - - // Assign current settings values - $this->_aViewData = array_merge($this->_aViewData, $this->getPasswordPolicy()->getModuleSettings()); - - // Parent call - return $this->_oxpsPasswordPolicyAccountPassword_render_parent(); - } - - - /** - * Overridden password changing callback method to add password policy validation. - * - * @return mixed - */ - public function changePassword() - { - /** @var oxConfig $oConfig */ - $oConfig = $this->getConfig(); - $oModule = $this->getPasswordPolicy(); - - // Validate password using password policy rules - if (is_object($oModule) and $oModule->validatePassword($oConfig->getRequestParameter('password_new'))) { - return false; - } - - // Parent call - return $this->_oxpsPasswordPolicyAccountPassword_changePassword_parent(); - } - - - /** - * Parent `init` call. Method required for mocking. - * - * @return mixed - */ - protected function _oxpsPasswordPolicyAccountPassword_init_parent() - { - // @codeCoverageIgnoreStart - return parent::init(); - // @codeCoverageIgnoreEnd - } - - /** - * Parent `render` call. Method required for mocking. - * - * @return mixed - */ - protected function _oxpsPasswordPolicyAccountPassword_render_parent() - { - // @codeCoverageIgnoreStart - return parent::render(); - // @codeCoverageIgnoreEnd - } - - /** - * Parent `changePassword` call. Method required for mocking. - * - * @return mixed - */ - protected function _oxpsPasswordPolicyAccountPassword_changePassword_parent() - { - // @codeCoverageIgnoreStart - return parent::changePassword(); - // @codeCoverageIgnoreEnd - } -} diff --git a/Controller/RegisterController.php b/Controller/RegisterController.php deleted file mode 100644 index e17b57bb..00000000 --- a/Controller/RegisterController.php +++ /dev/null @@ -1,108 +0,0 @@ -. - * - * @author OXID Professional services - * @link https://www.oxid-esales.com - * @copyright (C) OXID eSales AG 2003-2021 - */ - -namespace OxidProfessionalServices\PasswordPolicy\Controller; - -use \OxidProfessionalServices\PasswordPolicy\Core\PasswordPolicyModule; - -/** - * Overridden registration controller. - */ -class RegisterController extends RegisterController_parent -{ - - /** - * @var object $_oPasswordPolicy Password policy module instance. - */ - protected $_oPasswordPolicy; - - - /** - * Overridden init method, that creates password policy module object. - */ - public function init() - { - - // Parent call - $this->_oxpsPasswordPolicyRegister_init_parent(); - - $this->setPasswordPolicy(); - } - - /** - * Set Password Policy instance - * - * @param mixed $mPasswordPolicy - */ - public function setPasswordPolicy($oPasswordPolicy = null) - { - $this->_oPasswordPolicy = is_object($oPasswordPolicy) ? $oPasswordPolicy : oxNew(PasswordPolicyModule::class); - } - - /** - * @return object Password policy module instance. - */ - public function getPasswordPolicy() - { - return $this->_oPasswordPolicy; - } - - /** - * Overridden registration render method to add password policy parameters. - * - * @return string - */ - public function render() - { - - // Assign current settings values - $this->_aViewData = array_merge($this->_aViewData, $this->getPasswordPolicy()->getModuleSettings()); - - // Parent call - return $this->_oxpsPasswordPolicyRegister_render_parent(); - } - - - /** - * Parent `init` call. Method required for mocking. - * - * @return mixed - */ - protected function _oxpsPasswordPolicyRegister_init_parent() - { - // @codeCoverageIgnoreStart - return parent::init(); - // @codeCoverageIgnoreEnd - } - - /** - * Parent `render` call. Method required for mocking. - * - * @return mixed - */ - protected function _oxpsPasswordPolicyRegister_render_parent() - { - // @codeCoverageIgnoreStart - return parent::render(); - // @codeCoverageIgnoreEnd - } -} diff --git a/composer.json b/composer.json index 1157e1de..7f1595ac 100644 --- a/composer.json +++ b/composer.json @@ -14,7 +14,7 @@ }, "autoload": { "psr-4": { - "OxidProfessionalServices\\PasswordPolicy\\": "." + "OxidProfessionalServices\\PasswordPolicy\\": "src" } } } diff --git a/metadata.php b/metadata.php index e9ec0fc2..ada5f14f 100644 --- a/metadata.php +++ b/metadata.php @@ -58,7 +58,8 @@ ], 'controllers' => [ 'oxpspasswordpolicy' => \OxidProfessionalServices\PasswordPolicy\Controller\OxpsPasswordPolicy::class, - 'admin_oxpspasswordpolicy' => \OxidProfessionalServices\PasswordPolicy\Controller\Admin\OxpsPasswordPolicyAdmin::class, + 'admin_oxpspasswordpolicy' => + \OxidProfessionalServices\PasswordPolicy\Controller\Admin\OxpsPasswordPolicyAdmin::class, ], 'templates' => [ 'passwordpolicyaccountblocked.tpl' => 'oxps/passwordpolicy/views/pages/passwordpolicyaccountblocked.tpl', diff --git a/Component/UserComponent.php b/src/Component/UserComponent.php similarity index 83% rename from Component/UserComponent.php rename to src/Component/UserComponent.php index 539aba61..ee62ee8e 100644 --- a/Component/UserComponent.php +++ b/src/Component/UserComponent.php @@ -1,4 +1,5 @@ _oxpsPasswordPolicyUser_init_parent(); + $this->oxpsPasswordPolicyUserInitParent(); $this->setPasswordPolicy(); } @@ -64,7 +65,7 @@ public function init() */ public function setPasswordPolicy($oPasswordPolicy = null) { - $this->_oPasswordPolicy = is_object($oPasswordPolicy) ? $oPasswordPolicy : oxNew(PasswordPolicyModule::class); + $this->passwordPolicy = is_object($oPasswordPolicy) ? $oPasswordPolicy : oxNew(PasswordPolicyModule::class); } /** @@ -72,7 +73,7 @@ public function setPasswordPolicy($oPasswordPolicy = null) */ public function getPasswordPolicy() { - return $this->_oPasswordPolicy; + return $this->passwordPolicy; } /** @@ -82,7 +83,7 @@ public function getPasswordPolicy() public function login() { // Parent login call - $mLoginResponse = $this->_oxpsPasswordPolicyUser_login_parent(); + $mLoginResponse = $this->oxpsPasswordPolicyUserLoginParent(); $oUser = oxNew('oxUser'); @@ -91,7 +92,7 @@ public function login() // Continue with login attempts logic only if user id valid and user is loaded if (!empty($iUserId) and $oUser->load($iUserId) and $oUser->getId()) { - $this->_handleLoginAttempts($oUser); + $this->handleLoginAttempts($oUser); } return $mLoginResponse; @@ -108,14 +109,15 @@ public function createUser() $oModule = $this->getPasswordPolicy(); $oConfig = Registry::getConfig(); - if (is_object($oModule) and $oConfig->getRequestParameter('lgn_pwd') and + if ( + is_object($oModule) and $oConfig->getRequestParameter('lgn_pwd') and $oModule->validatePassword($oConfig->getRequestParameter('lgn_pwd')) ) { return false; } // Parent create user call - return $this->_oxpsPasswordPolicyUser_createUser_parent(); + return $this->oxpsPasswordPolicyUserCreateUserParent(); } @@ -126,17 +128,15 @@ public function createUser() * * @param object $oUser */ - protected function _handleLoginAttempts($oUser) + protected function handleLoginAttempts($oUser) { // User object must be valid and loaded if (($oUser instanceof oxUser) and $oUser->getId()) { - // Check user status if (empty($oUser->oxuser__oxactive->value)) { - // Redirect user to block page if he is not active. - $this->_redirectBlockedUser(); + $this->redirectBlockedUser(); return; } @@ -151,26 +151,22 @@ protected function _handleLoginAttempts($oUser) ); if ($this->getLoginStatus() == USER_LOGIN_FAIL) { - // Log attempts $oAttempt->log(); if ($oAttempt->maximumReached()) { - // Block user and redirect to blocked user page $oUser->oxuser__oxactive = new oxField(0); $oUser->save(); // Redirect user - $this->_redirectBlockedUser(); + $this->redirectBlockedUser(); return; } } else { - // Purge all login attempts for the user $oAttempt->clean(); } - } } @@ -179,7 +175,7 @@ protected function _handleLoginAttempts($oUser) * * @return null */ - protected function _redirectBlockedUser() + protected function redirectBlockedUser() { // @codeCoverageIgnoreStart // Not covering redirects. @@ -199,7 +195,7 @@ protected function _redirectBlockedUser() * * @return null */ - protected function _oxpsPasswordPolicyUser_init_parent() + protected function oxpsPasswordPolicyUserInitParent() { // @codeCoverageIgnoreStart return parent::init(); @@ -211,7 +207,7 @@ protected function _oxpsPasswordPolicyUser_init_parent() * * @return mixed */ - protected function _oxpsPasswordPolicyUser_login_parent() + protected function oxpsPasswordPolicyUserLoginParent() { // @codeCoverageIgnoreStart return parent::login(); @@ -223,7 +219,7 @@ protected function _oxpsPasswordPolicyUser_login_parent() * * @return mixed */ - protected function _oxpsPasswordPolicyUser_createUser_parent() + protected function oxpsPasswordPolicyUserCreateUserParent() { // @codeCoverageIgnoreStart return parent::createUser(); diff --git a/src/Controller/AccountPasswordController.php b/src/Controller/AccountPasswordController.php new file mode 100644 index 00000000..9b13a43a --- /dev/null +++ b/src/Controller/AccountPasswordController.php @@ -0,0 +1,67 @@ +. + * + * @author OXID Professional services + * @link https://www.oxid-esales.com + * @copyright (C) OXID eSales AG 2003-2021 + */ + +namespace OxidProfessionalServices\PasswordPolicy\Controller; + +use OxidProfessionalServices\PasswordPolicy\Core\PasswordPolicyModule; + +/** + * Password policy main controller + */ +class AccountPasswordController extends AccountPasswordController_parent +{ + use ControllerWithPasswordPolicy; + + /** + * Overridden password changing callback method to add password policy validation. + * + * @return mixed + */ + public function changePassword() + { + /** @var oxConfig $oConfig */ + $oConfig = $this->getConfig(); + $oModule = $this->getPasswordPolicy(); + + // Validate password using password policy rules + if (is_object($oModule) and $oModule->validatePassword($oConfig->getRequestParameter('password_new'))) { + return false; + } + + // Parent call + return $this->oxpsPasswordPolicyChangePasswordParent(); + } + + + /** + * Parent `changePassword` call. Method required for mocking. + * + * @return mixed + */ + protected function oxpsPasswordPolicyChangePasswordParent() + { + // @codeCoverageIgnoreStart + return parent::changePassword(); + // @codeCoverageIgnoreEnd + } +} diff --git a/Controller/Admin/OxpsPasswordPolicyAdmin.php b/src/Controller/Admin/OxpsPasswordPolicyAdmin.php similarity index 52% rename from Controller/Admin/OxpsPasswordPolicyAdmin.php rename to src/Controller/Admin/OxpsPasswordPolicyAdmin.php index afedec78..b34cf19b 100644 --- a/Controller/Admin/OxpsPasswordPolicyAdmin.php +++ b/src/Controller/Admin/OxpsPasswordPolicyAdmin.php @@ -1,4 +1,5 @@ _admin_OxpsPasswordPolicy_construct_parent(); + $this->adminOxpsPasswordPolicyConstructParent(); } @@ -54,7 +57,7 @@ function __construct() public function init() { // Parent init call - $this->_admin_OxpsPasswordPolicy_init_parent(); + $this->adminOxpsPasswordPolicyInitParent(); $this->setPasswordPolicy(); } @@ -67,7 +70,7 @@ public function init() */ public function setPasswordPolicy($oPasswordPolicy = null) { - $this->_oPasswordPolicy = is_object($oPasswordPolicy) ? $oPasswordPolicy : oxNew(PasswordPolicyModule::class); + $this->passwordPolicy = is_object($oPasswordPolicy) ? $oPasswordPolicy : oxNew(PasswordPolicyModule::class); } /** @@ -75,7 +78,7 @@ public function setPasswordPolicy($oPasswordPolicy = null) */ public function getPasswordPolicy() { - return $this->_oPasswordPolicy; + return $this->passwordPolicy; } @@ -91,7 +94,7 @@ public function render() $this->_aViewData = array_merge($this->_aViewData, $this->getPasswordPolicy()->getModuleSettings()); // Parent render call - return $this->_admin_OxpsPasswordPolicy_render_parent(); + return $this->adminOxpsPasswordPolicyRenderParent(); } @@ -103,55 +106,53 @@ public function render() public function save() { // Constants and initial params - $oConfig = $this->getConfig(); - $sPrefix = 'passwordpolicy_'; - $oModule = $this->getPasswordPolicy(); - $aRequirementsOptions = $oModule->getPasswordRequirementsOptions(); - $aRequirements = array(); + $config = $this->getConfig(); + $prefix = 'passwordpolicy_'; + $module = $this->getPasswordPolicy(); + $requirementsOptions = $module->getPasswordRequirementsOptions(); + $requirements = array(); // Get values from a request - $iMaxAttemptsAllowed = $oConfig->getRequestParameter($sPrefix . 'maxattemptsallowed'); - $iTrackingPeriod = $oConfig->getRequestParameter($sPrefix . 'trackingperiod'); - $blAllowUnblock = (bool)$oConfig->getRequestParameter($sPrefix . 'allowunblock'); - $iMinPasswordLength = (int)$oConfig->getRequestParameter($sPrefix . 'minpasswordlength'); - $iGoodPasswordLength = (int)$oConfig->getRequestParameter($sPrefix . 'goodpasswordlength'); - $iMaxPasswordLength = (int)$oConfig->getRequestParameter($sPrefix . 'maxpasswordlength'); - $aPasswordRequirements = (array)$oConfig->getRequestParameter($sPrefix . 'requirements'); + $maxAttemptsAllowed = $config->getRequestParameter($prefix . 'maxattemptsallowed'); + $trackingPeriod = $config->getRequestParameter($prefix . 'trackingperiod'); + $allowUnblock = (bool)$config->getRequestParameter($prefix . 'allowunblock'); + $minPasswordLength = (int)$config->getRequestParameter($prefix . 'minpasswordlength'); + $goodPasswordLength = (int)$config->getRequestParameter($prefix . 'goodpasswordlength'); + $maxPasswordLength = (int)$config->getRequestParameter($prefix . 'maxpasswordlength'); + $passwordRequirements = (array)$config->getRequestParameter($prefix . 'requirements'); // Validate values and save to settings - if (!is_null($iMaxAttemptsAllowed) and $oModule->validatePositiveInteger((int)$iMaxAttemptsAllowed)) { - $oModule->saveShopConfVar("int", "iMaxAttemptsAllowed", (int)$iMaxAttemptsAllowed); + if (!is_null($maxAttemptsAllowed) and $module->validatePositiveInteger((int)$maxAttemptsAllowed)) { + $module->saveShopConfVar("int", "iMaxAttemptsAllowed", (int)$maxAttemptsAllowed); } - if (!is_null($iTrackingPeriod) and $oModule->validatePositiveInteger((int)$iTrackingPeriod)) { - $oModule->saveShopConfVar("int", "iTrackingPeriod", (int)$iTrackingPeriod); + if (!is_null($trackingPeriod) and $module->validatePositiveInteger((int)$trackingPeriod)) { + $module->saveShopConfVar("int", "iTrackingPeriod", (int)$trackingPeriod); } - $oModule->saveShopConfVar("bool", "blAllowUnblock", $blAllowUnblock); + $module->saveShopConfVar("bool", "blAllowUnblock", $allowUnblock); - if (($iMinPasswordLength <= $iGoodPasswordLength) and ($iGoodPasswordLength <= $iMaxPasswordLength)) { - - if ($oModule->validatePositiveInteger($iMinPasswordLength, 6)) { - $oModule->saveShopConfVar("int", "iMinPasswordLength", $iMinPasswordLength); + if (($minPasswordLength <= $goodPasswordLength) and ($goodPasswordLength <= $maxPasswordLength)) { + if ($module->validatePositiveInteger($minPasswordLength, 6)) { + $module->saveShopConfVar("int", "iMinPasswordLength", $minPasswordLength); } - if ($oModule->validatePositiveInteger($iGoodPasswordLength)) { - $oModule->saveShopConfVar("int", "iGoodPasswordLength", $iGoodPasswordLength); + if ($module->validatePositiveInteger($goodPasswordLength)) { + $module->saveShopConfVar("int", "iGoodPasswordLength", $goodPasswordLength); } - if ($oModule->validatePositiveInteger($iMaxPasswordLength)) { - $oModule->saveShopConfVar("int", "iMaxPasswordLength", $iMaxPasswordLength); + if ($module->validatePositiveInteger($maxPasswordLength)) { + $module->saveShopConfVar("int", "iMaxPasswordLength", $maxPasswordLength); } } - if (is_array($aPasswordRequirements)) { - + if (is_array($passwordRequirements)) { // Check posted options and build array for saving - foreach ($aRequirementsOptions as $option) { - $aRequirements[$option] = !empty($aPasswordRequirements[$option]); + foreach ($requirementsOptions as $option) { + $requirements[$option] = !empty($passwordRequirements[$option]); } - $oModule->saveShopConfVar("aarr", "aPasswordRequirements", $aRequirements); + $module->saveShopConfVar("aarr", "aPasswordRequirements", $requirements); } $this->_aViewData["message"] = 'OXPS_PASSWORDPOLICY_ADMIN_SAVED'; @@ -163,7 +164,7 @@ public function save() * * @return null */ - protected function _admin_OxpsPasswordPolicy_construct_parent() + protected function adminOxpsPasswordPolicyConstructParent() { // @codeCoverageIgnoreStart return parent::__construct(); @@ -175,7 +176,7 @@ protected function _admin_OxpsPasswordPolicy_construct_parent() * * @return null */ - protected function _admin_OxpsPasswordPolicy_init_parent() + protected function adminOxpsPasswordPolicyInitParent() { // @codeCoverageIgnoreStart return parent::init(); @@ -187,7 +188,7 @@ protected function _admin_OxpsPasswordPolicy_init_parent() * * @return null */ - protected function _admin_OxpsPasswordPolicy_render_parent() + protected function adminOxpsPasswordPolicyRenderParent() { // @codeCoverageIgnoreStart return parent::render(); diff --git a/Controller/UserController.php b/src/Controller/ControllerWithPasswordPolicy.php similarity index 79% rename from Controller/UserController.php rename to src/Controller/ControllerWithPasswordPolicy.php index 667a8176..1849e262 100644 --- a/Controller/UserController.php +++ b/src/Controller/ControllerWithPasswordPolicy.php @@ -1,4 +1,5 @@ _oxpsPasswordPolicyUser_init_parent(); + $this->oxpsPasswordPolicyInitParent(); $this->setPasswordPolicy(); } @@ -52,7 +53,7 @@ public function init() * * @return mixed */ - protected function _oxpsPasswordPolicyUser_init_parent() + protected function oxpsPasswordPolicyInitParent() { // @codeCoverageIgnoreStart return parent::init(); @@ -66,7 +67,7 @@ protected function _oxpsPasswordPolicyUser_init_parent() */ public function setPasswordPolicy($oPasswordPolicy = null) { - $this->_oPasswordPolicy = is_object($oPasswordPolicy) ? $oPasswordPolicy : oxNew(PasswordPolicyModule::class); + $this->passwordPolicy = is_object($oPasswordPolicy) ? $oPasswordPolicy : oxNew(PasswordPolicyModule::class); } /** @@ -81,7 +82,7 @@ public function render() $this->_aViewData = array_merge($this->_aViewData, $this->getPasswordPolicy()->getModuleSettings()); // Parent call - return $this->_oxpsPasswordPolicyUser_render_parent(); + return $this->oxpsPasswordPolicyRenderParent(); } /** @@ -89,7 +90,7 @@ public function render() */ public function getPasswordPolicy() { - return $this->_oPasswordPolicy; + return $this->passwordPolicy; } /** @@ -97,7 +98,7 @@ public function getPasswordPolicy() * * @return mixed */ - protected function _oxpsPasswordPolicyUser_render_parent() + protected function oxpsPasswordPolicyRenderParent() { // @codeCoverageIgnoreStart return parent::render(); diff --git a/Controller/ForgotPasswordController.php b/src/Controller/ForgotPasswordController.php similarity index 67% rename from Controller/ForgotPasswordController.php rename to src/Controller/ForgotPasswordController.php index ef513004..0e7ec944 100644 --- a/Controller/ForgotPasswordController.php +++ b/src/Controller/ForgotPasswordController.php @@ -1,4 +1,5 @@ _oxpsPasswordPolicyForgotPwd_init_parent(); - - $this->setPasswordPolicy(); - } - - /** - * Set Password Policy instance - * - * @param mixed $mPasswordPolicy - */ - public function setPasswordPolicy($oPasswordPolicy = null) - { - $this->_oPasswordPolicy = is_object($oPasswordPolicy) ? $oPasswordPolicy : oxNew(PasswordPolicyModule::class); - } - - /** - * @return object Password policy module instance. - */ - public function getPasswordPolicy() - { - return $this->_oPasswordPolicy; - } - - - /** - * Overridden render method to add password policy parameters. - * - * @return string - */ - public function render() - { - // Assign current settings values - $this->_aViewData = array_merge($this->_aViewData, $this->getPasswordPolicy()->getModuleSettings()); - - // Parent call - return $this->_oxpsPasswordPolicyForgotPwd_render_parent(); - } - + use ControllerWithPasswordPolicy; /** * Overridden method. @@ -98,7 +48,6 @@ public function forgotPassword() // Check if unlock is allowed by settings if (is_object($oModule) and $oModule->getModuleSetting('blAllowUnblock')) { - $oUser = oxNew('oxUser'); // Try loading user by username @@ -106,7 +55,6 @@ public function forgotPassword() // Continue with temporary unblock if user exists and is blocked if (!empty($iUserId) and $oUser->load($iUserId) and empty($oUser->oxuser__oxactive->value)) { - // Unblock the user and mark the user ass required to be blocked after parent call. $oUser->oxuser__oxactive = new oxField(true); $oUser->save(); @@ -115,13 +63,12 @@ public function forgotPassword() } // Parent call - $mResponse = $this->_oxpsPasswordPolicyForgotPwd_forgotPassword_parent(); + $mResponse = $this->oxpsPasswordPolicyForgotPasswordParent(); // Reload and block user again if set. $oUser = oxNew('oxUser'); if (!empty($mBlockUser) and $oUser->load($mBlockUser)) { - $oUser->oxuser__oxactive = new oxField(false); $oUser->save(); } @@ -153,7 +100,6 @@ public function updatePassword() $blAllowUnblock = (is_object($oModule) and $oModule->getModuleSetting('blAllowUnblock')); if ($blAllowUnblock) { - // Save target user OXID. $oUser = oxNew('oxUser'); @@ -164,11 +110,10 @@ public function updatePassword() } // Parent call - $mParentReturn = $this->_oxpsPasswordPolicyForgotPwd_updatePassword_parent(); + $mParentReturn = $this->oxpsPasswordPolicyUpdatePasswordParent(); // Check if unlock is allowed by settings, user is valid and update was successful if ($blAllowUnblock and $mUnblockUser and ($mParentReturn == 'forgotpwd?success=1')) { - $oUser = oxNew('oxUser'); // Load user by @@ -182,36 +127,12 @@ public function updatePassword() } - /** - * Parent `init` call. Method required for mocking. - * - * @return null - */ - protected function _oxpsPasswordPolicyForgotPwd_init_parent() - { - // @codeCoverageIgnoreStart - return parent::init(); - // @codeCoverageIgnoreEnd - } - - /** - * Parent `render` call. Method required for mocking. - * - * @return null - */ - protected function _oxpsPasswordPolicyForgotPwd_render_parent() - { - // @codeCoverageIgnoreStart - return parent::render(); - // @codeCoverageIgnoreEnd - } - /** * Parent `forgotPassword` call. Method required for mocking. * * @return mixed */ - protected function _oxpsPasswordPolicyForgotPwd_forgotPassword_parent() + protected function oxpsPasswordPolicyForgotPasswordParent() { // @codeCoverageIgnoreStart return parent::forgotPassword(); @@ -223,7 +144,7 @@ protected function _oxpsPasswordPolicyForgotPwd_forgotPassword_parent() * * @return mixed */ - protected function _oxpsPasswordPolicyForgotPwd_updatePassword_parent() + protected function oxpsPasswordPolicyUpdatePasswordParent() { // @codeCoverageIgnoreStart return parent::updatePassword(); diff --git a/Controller/OxpsPasswordPolicy.php b/src/Controller/OxpsPasswordPolicy.php similarity index 88% rename from Controller/OxpsPasswordPolicy.php rename to src/Controller/OxpsPasswordPolicy.php index 10a5716f..75510c17 100644 --- a/Controller/OxpsPasswordPolicy.php +++ b/src/Controller/OxpsPasswordPolicy.php @@ -1,4 +1,5 @@ _aViewData['blAllowUnblock'] = (bool)$oModule->getModuleSetting('blAllowUnblock'); // Parent render call - return $this->_oxpsPasswordPolicy_render_parent(); + return $this->oxpsPasswordPolicyRenderParent(); } @@ -60,7 +62,7 @@ public function render() * * @return mixed */ - protected function _oxpsPasswordPolicy_render_parent() + protected function oxpsPasswordPolicyRenderParent() { // @codeCoverageIgnoreStart return parent::render(); diff --git a/src/Controller/RegisterController.php b/src/Controller/RegisterController.php new file mode 100644 index 00000000..6b7b16c5 --- /dev/null +++ b/src/Controller/RegisterController.php @@ -0,0 +1,34 @@ +. + * + * @author OXID Professional services + * @link https://www.oxid-esales.com + * @copyright (C) OXID eSales AG 2003-2021 + */ + +namespace OxidProfessionalServices\PasswordPolicy\Controller; + +use OxidProfessionalServices\PasswordPolicy\Core\PasswordPolicyModule; + +/** + * Overridden registration controller. + */ +class RegisterController extends RegisterController_parent +{ + use ControllerWithPasswordPolicy; +} diff --git a/src/Controller/UserController.php b/src/Controller/UserController.php new file mode 100644 index 00000000..f8b0e98d --- /dev/null +++ b/src/Controller/UserController.php @@ -0,0 +1,34 @@ +. + * + * @author OXID Professional services + * @link https://www.oxid-esales.com + * @copyright (C) OXID eSales AG 2003-2021 + */ + +namespace OxidProfessionalServices\PasswordPolicy\Controller; + +use OxidProfessionalServices\PasswordPolicy\Core\PasswordPolicyModule; + +/** + * Class oxpsPasswordPolicyUser + */ +class UserController extends UserController_parent +{ + use ControllerWithPasswordPolicy; +} diff --git a/Core/PasswordPolicyModule.php b/src/Core/PasswordPolicyModule.php similarity index 84% rename from Core/PasswordPolicyModule.php rename to src/Core/PasswordPolicyModule.php index cf7685d1..12d47cd1 100644 --- a/Core/PasswordPolicyModule.php +++ b/src/Core/PasswordPolicyModule.php @@ -1,4 +1,5 @@ _sModuleId; + return $this->moduleId; } /** @@ -114,7 +115,7 @@ public function getModuleSettings($blReturnNames = false) foreach ($aSettings as $sName => $sType) { $aSettings[$sName] = $this->getShopConfVar($sName); - if($sType == 'array' && $aSettings[$sName] === null) { + if ($sType == 'array' && $aSettings[$sName] === null) { $aSettings[$sName] = array(); } settype($aSettings[$sName], $sType); @@ -181,7 +182,8 @@ public function validatePassword($sPassword) $sError = 'OXPS_PASSWORDPOLICY_PASSWORDSTRENGTH_ERROR_REQUIRESLOWER'; } - if (!empty($aSettings['aPasswordRequirements']['special']) and + if ( + !empty($aSettings['aPasswordRequirements']['special']) and !preg_match('([\.,_@\~\(\)\!\#\$%\^\&\*\+=\-\\\/|:;`]+)', $sPassword) ) { $sError = 'OXPS_PASSWORDPOLICY_PASSWORDSTRENGTH_ERROR_REQUIRESSPECIAL'; @@ -245,7 +247,7 @@ public static function onActivate() { // @codeCoverageIgnoreStart // Generated from developer tools, no need to test this - self::_dbEvent( 'install.sql', 'Error activating module: ' ); + self::dbEvent('install.sql', 'Error activating module: '); // @codeCoverageIgnoreEnd } @@ -256,8 +258,8 @@ public static function onDeactivate() { // @codeCoverageIgnoreStart // Generated from developer tools, no need to test this - if ( function_exists( 'module_enabled_count' ) && module_enabled_count( 'oxpswatchlist' ) < 2 ) { - self::_dbEvent( 'uninstall.sql', 'Error deactivating module: ' ); + if (function_exists('module_enabled_count') && module_enabled_count('oxpswatchlist') < 2) { + self::dbEvent('uninstall.sql', 'Error deactivating module: '); } // @codeCoverageIgnoreEnd } @@ -268,35 +270,35 @@ public static function onDeactivate() * @param string $sSqlFile SQL file located in module docs folder (usually install.sql or uninstall.sql). * @param string $sFailureError An error message to show on failure. */ - protected static function _dbEvent( $sSqlFile, $sFailureError = "Operation failed: " ) + protected static function dbEvent($sSqlFile, $sFailureError = "Operation failed: ") { // @codeCoverageIgnoreStart // Generated from developer tools, no need to test this try { - $sSqlDir = dirname( __DIR__ ) . DIRECTORY_SEPARATOR . 'docs' . DIRECTORY_SEPARATOR . $sSqlFile; - if ( preg_match( '/\.tpl$/', $sSqlFile ) ) { // If file extension is .tpl + $sSqlDir = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'docs' . DIRECTORY_SEPARATOR . $sSqlFile; + if (preg_match('/\.tpl$/', $sSqlFile)) { // If file extension is .tpl /** @var Smarty $oSmarty */ - $oSmarty = Registry::get( 'oxUtilsView' )->getSmarty(); - $oSmarty->assign( 'oConfig', Registry::getConfig() ); - $sSql = $oSmarty->fetch( $sSqlDir ); + $oSmarty = Registry::get('oxUtilsView')->getSmarty(); + $oSmarty->assign('oConfig', Registry::getConfig()); + $sSql = $oSmarty->fetch($sSqlDir); } else { - $sSql = file_get_contents( $sSqlDir ); + $sSql = file_get_contents($sSqlDir); } $oDb = DatabaseProvider::getDb(); - $aSql = explode( ';', $sSql ); + $aSql = explode(';', $sSql); - if ( !empty( $aSql ) ) { - foreach ( $aSql as $sQuery ) { - if ( !empty( $sQuery ) || !empty(trim($sQuery)) ) { - $oDb->execute( $sQuery ); + if (!empty($aSql)) { + foreach ($aSql as $sQuery) { + if (!empty($sQuery) || !empty(trim($sQuery))) { + $oDb->execute($sQuery); } } } self::cleanTmp(); - } catch ( Exception $ex ) { - error_log( $sFailureError . $ex->getMessage() ); + } catch (Exception $ex) { + error_log($sFailureError . $ex->getMessage()); } // @codeCoverageIgnoreEnd } @@ -310,11 +312,11 @@ public static function cleanTmp() { // @codeCoverageIgnoreStart // Generated from developer tools, no need to test this - if ( class_exists( 'D' ) ) { + if (class_exists('D')) { try { D::c(); - } catch ( Exception $ex ) { - error_log( 'Cache files deletion failed: ' . $ex->getMessage() ); + } catch (Exception $ex) { + error_log('Cache files deletion failed: ' . $ex->getMessage()); } return true; diff --git a/Model/Attempt.php b/src/Model/Attempt.php similarity index 74% rename from Model/Attempt.php rename to src/Model/Attempt.php index 56d6d01c..e0cb0e26 100644 --- a/Model/Attempt.php +++ b/src/Model/Attempt.php @@ -1,4 +1,5 @@ _oxpsPasswordPolicyAttempt_construct_parent(); + $this->oxpsPasswordPolicyAttemptConstructParent(); // Set defaults $this->setMaxAttemptsAllowed(3); @@ -79,7 +80,7 @@ public function __invoke() */ public function getUser() { - return $this->_oUser; + return $this->user; } /** @@ -91,7 +92,7 @@ public function getUser() public function setUser($oUser) { if ($oUser instanceof oxUser) { - $this->_oUser = $oUser; + $this->user = $oUser; } } @@ -102,18 +103,18 @@ public function setUser($oUser) */ public function getMaxAttemptsAllowed() { - return $this->_iMaxAttemptsAllowed; + return $this->maxAttemptsAllowed; } /** * Set maximum allowed attempts value. * - * @param int $iMaxAttemptsAllowed + * @param int $maxAttemptsAllowed */ - public function setMaxAttemptsAllowed($iMaxAttemptsAllowed) + public function setMaxAttemptsAllowed($maxAttemptsAllowed) { - if ($this->_isPositiveInteger($iMaxAttemptsAllowed)) { - $this->_iMaxAttemptsAllowed = $iMaxAttemptsAllowed; + if ($this->isPositiveInteger($maxAttemptsAllowed)) { + $this->maxAttemptsAllowed = $maxAttemptsAllowed; } } @@ -124,18 +125,18 @@ public function setMaxAttemptsAllowed($iMaxAttemptsAllowed) */ public function getTrackingPeriod() { - return $this->_iTrackingPeriod; + return $this->trackingPeriod; } /** * Set tracking period value. * - * @param int $iTrackingPeriod + * @param int $trackingPeriod */ - public function setTrackingPeriod($iTrackingPeriod) + public function setTrackingPeriod($trackingPeriod) { - if ($this->_isPositiveInteger($iTrackingPeriod)) { - $this->_iTrackingPeriod = $iTrackingPeriod; + if ($this->isPositiveInteger($trackingPeriod)) { + $this->trackingPeriod = $trackingPeriod; } } @@ -147,13 +148,13 @@ public function setTrackingPeriod($iTrackingPeriod) */ public function log() { - $sUserOxid = $this->_getUserOxid(); + $sUserOxid = $this->getUserOxid(); if (!empty($sUserOxid)) { $this->assign(array( 'oxuserid' => $sUserOxid, - 'oxpstime' => $this->_getAttemptTime(), - 'oxpsip' => $this->_getIpAddress(), + 'oxpstime' => $this->getAttemptTime(), + 'oxpsip' => $this->getIpAddress(), )); return (bool)$this->save(); @@ -169,7 +170,7 @@ public function log() */ public function maximumReached() { - $sUserOxid = $this->_getUserOxid(); + $sUserOxid = $this->getUserOxid(); if (!empty($sUserOxid)) { $view = getViewName('oxpspasswordpolicy_attempt'); @@ -177,8 +178,9 @@ public function maximumReached() WHERE `OXUSERID` = ? AND `OXPSTIME` >= ? HAVING COUNT(`OXID`) >= ?"; - $mResults = DatabaseProvider::getDb()->select($sQuery, - [$sUserOxid, $this->_getTimeMargin(), $this->getMaxAttemptsAllowed()] + $mResults = DatabaseProvider::getDb()->select( + $sQuery, + [$sUserOxid, $this->getTimeMargin(), $this->getMaxAttemptsAllowed()] ); return !empty($mResults->fields[0]); @@ -198,21 +200,21 @@ public function clean() // @codeCoverageIgnoreStart // Not covering database queries - $sUserOxid = $this->_getUserOxid(); + $sUserOxid = $this->getUserOxid(); if (!empty($sUserOxid)) { - // Clause to delete only defined user attempts $sUserClause = "`OXUSERID` = " . DatabaseProvider::getDb()->quote($sUserOxid); } else { - // Clause to delete only expired entries (older than tracking period) - $sUserClause = "`OXPSTIME` < " . DatabaseProvider::getDb()->quote($this->_getTimeMargin()); + $sUserClause = "`OXPSTIME` < " . DatabaseProvider::getDb()->quote($this->getTimeMargin()); } $sQuery = "DELETE FROM `%s` WHERE %s"; - return (bool)DatabaseProvider::getDb()->execute(sprintf($sQuery, getViewName('oxpspasswordpolicy_attempt'), $sUserClause)); + return (bool)DatabaseProvider::getDb()->execute( + sprintf($sQuery, getViewName('oxpspasswordpolicy_attempt'), $sUserClause) + ); // @codeCoverageIgnoreEnd } @@ -223,7 +225,7 @@ public function clean() * @param mixed $number * @return bool */ - protected function _isPositiveInteger($number) + protected function isPositiveInteger($number) { return (is_integer($number) and ($number > 0)); } @@ -234,9 +236,9 @@ protected function _isPositiveInteger($number) * * @return string|null */ - protected function _getUserOxid() + protected function getUserOxid() { - return (is_object($this->_oUser) ? $this->_oUser->getId() : null); + return (is_object($this->user) ? $this->user->getId() : null); } /** @@ -245,7 +247,7 @@ protected function _getUserOxid() * * @return string Date-time value. */ - protected function _getTimeMargin() + protected function getTimeMargin() { // @codeCoverageIgnoreStart // Not covering default php methods @@ -262,7 +264,7 @@ protected function _getTimeMargin() * * @return string */ - protected function _getAttemptTime() + protected function getAttemptTime() { // @codeCoverageIgnoreStart // Not covering default php method @@ -276,7 +278,7 @@ protected function _getAttemptTime() * * @return string */ - protected function _getIpAddress() + protected function getIpAddress() { // @codeCoverageIgnoreStart // Not covering default eShop utils @@ -291,7 +293,7 @@ protected function _getIpAddress() * * @return mixed */ - protected function _oxpsPasswordPolicyAttempt_construct_parent() + protected function oxpsPasswordPolicyAttemptConstructParent() { // @codeCoverageIgnoreStart return parent::__construct(); diff --git a/tests/unit/module/Component/UserComponentTest.php b/tests/unit/module/Component/UserComponentTest.php index d246cd97..e13abf5e 100644 --- a/tests/unit/module/Component/UserComponentTest.php +++ b/tests/unit/module/Component/UserComponentTest.php @@ -1,4 +1,5 @@ SUT = $this->getMock( 'OxpsPasswordPolicyUser', array( - '_oxpsPasswordPolicyUser_init_parent', - '_oxpsPasswordPolicyUser_login_parent', - '_oxpsPasswordPolicyUser_createUser_parent', - '_redirectBlockedUser', + 'oxpsPasswordPolicyUserInitParent', + 'oxpsPasswordPolicyUserLoginParent', + 'oxpsPasswordPolicyUserCreateUserParent', + 'redirectBlockedUser', 'getLoginStatus', 'getConfig', ) ); - $this->SUT->expects($this->any())->method('_oxpsPasswordPolicyUser_init_parent') + $this->SUT->expects($this->any())->method('oxpsPasswordPolicyUserInitParent') ->will($this->returnValue(null)); - $this->SUT->expects($this->any())->method('_oxpsPasswordPolicyUser_login_parent') + $this->SUT->expects($this->any())->method('oxpsPasswordPolicyUserLoginParent') ->will($this->returnValue('login_parent')); - $this->SUT->expects($this->any())->method('_oxpsPasswordPolicyUser_createUser_parent') + $this->SUT->expects($this->any())->method('oxpsPasswordPolicyUserCreateUserParent') ->will($this->returnValue('create_user_parent')); - $this->SUT->expects($this->any())->method('_redirectBlockedUser')->will($this->returnValue(null)); + $this->SUT->expects($this->any())->method('redirectBlockedUser')->will($this->returnValue(null)); // Config mock inception $oConfig = $this->getMock('oxConfig', array('getShopConfVar')); @@ -226,7 +227,7 @@ public function testCreateUser_moduleInstanceNotSet_callsParent() public function testCreateUser_noParam_validationFailReturnFalse() { - $this->SUT->expects($this->once())->method('_oxpsPasswordPolicyUser_createUser_parent'); + $this->SUT->expects($this->once())->method('oxpsPasswordPolicyUser_createUser_parent'); $this->SUT->init(); $this->SUT->createUser(); @@ -246,7 +247,7 @@ public function testCreateUser_passwordIsValid_callParent() oxTestModules::addModuleObject("OxpsPasswordPolicyModule", $oModule); - $this->SUT->expects($this->once())->method('_oxpsPasswordPolicyUser_createUser_parent'); + $this->SUT->expects($this->once())->method('oxpsPasswordPolicyUser_createUser_parent'); $this->SUT->init(); $this->SUT->createUser(); diff --git a/tests/unit/module/Controller/AccountPasswordControllerTest.php b/tests/unit/module/Controller/AccountPasswordControllerTest.php index 3e448df7..8beeae9d 100644 --- a/tests/unit/module/Controller/AccountPasswordControllerTest.php +++ b/tests/unit/module/Controller/AccountPasswordControllerTest.php @@ -1,4 +1,5 @@ SUT = $this->getMock('OxpsPasswordPolicyAccountPassword', array( - '_oxpsPasswordPolicyAccountPassword_init_parent', - '_oxpsPasswordPolicyAccountPassword_render_parent', - '_oxpsPasswordPolicyAccountPassword_changePassword_parent' + 'oxpsPasswordPolicyAccountPasswordInitParent', + 'oxpsPasswordPolicyAccountPasswordRenderParent', + 'oxpsPasswordPolicyAccountPasswordChangePasswordParent' )); } @@ -60,7 +61,7 @@ public function testGetPasswordPolicy_initNotRan_returnNull() /** * `getPasswordPolicy` returns `PasswordPolicyModule` object after init (or password policy set) */ - public function testGetPasswordPolicy_initRan_returnPasswordPolicyModuleInstance() + public function testGetPasswordPolicyInitRanReturnPasswordPolicyModuleInstance() { $this->SUT->init(); @@ -71,9 +72,9 @@ public function testGetPasswordPolicy_initRan_returnPasswordPolicyModuleInstance /** * `render` should add Password Policy settings to ViewData array and call parent */ - public function testRender_addPasswordPolicySettingsCallParent() + public function testRenderAddPasswordPolicySettingsCallParent() { - $this->SUT->expects($this->once())->method('_oxpsPasswordPolicyAccountPassword_render_parent'); + $this->SUT->expects($this->once())->method('oxpsPasswordPolicyAccountPasswordRenderParent'); $aConfigKeys = array( 'iMaxAttemptsAllowed', 'iTrackingPeriod', 'blAllowUnblock', @@ -93,9 +94,9 @@ public function testRender_addPasswordPolicySettingsCallParent() /** * `changePassword` should only call parent if no Password Policy module instance set. */ - public function testChangePassword_noModuleInstance_callParent() + public function testChangePasswordNoModuleInstanceCallParent() { - $this->SUT->expects($this->once())->method('_oxpsPasswordPolicyAccountPassword_changePassword_parent'); + $this->SUT->expects($this->once())->method('oxpsPasswordPolicyAccountPasswordChangePasswordParent'); $this->SUT->changePassword(); } @@ -103,7 +104,7 @@ public function testChangePassword_noModuleInstance_callParent() /** * `changePassword` should return false if password is invalid or empty */ - public function testChangePassword_invalidPassword_returnFalse() + public function testChangePasswordInvalidPasswordReturnFalse() { // Password policy module mock $oModule = $this->getMock('OxpsPasswordPolicyModule', array('validatePassword')); @@ -111,7 +112,7 @@ public function testChangePassword_invalidPassword_returnFalse() oxTestModules::addModuleObject("OxpsPasswordPolicyModule", $oModule); - $this->SUT->expects($this->never())->method('_oxpsPasswordPolicyAccountPassword_changePassword_parent'); + $this->SUT->expects($this->never())->method('oxpsPasswordPolicyAccountPasswordChangePasswordParent'); $this->SUT->init(); $this->assertFalse($this->SUT->changePassword()); @@ -120,7 +121,7 @@ public function testChangePassword_invalidPassword_returnFalse() /** * `changePassword` should call parent if password is valid */ - public function testChangePassword_passwordIsValid_callParent() + public function testChangePasswordPasswordIsValidCallParent() { modConfig::getInstance()->setParameter('password_new', 'abcDEFG_123-pass'); @@ -131,7 +132,7 @@ public function testChangePassword_passwordIsValid_callParent() oxTestModules::addModuleObject("OxpsPasswordPolicyModule", $oModule); - $this->SUT->expects($this->once())->method('_oxpsPasswordPolicyAccountPassword_changePassword_parent'); + $this->SUT->expects($this->once())->method('oxpsPasswordPolicyAccountPasswordChangePasswordParent'); $this->SUT->init(); $this->SUT->changePassword(); diff --git a/tests/unit/module/Controller/Admin/OxpsPasswordPolicyAdminTest.php b/tests/unit/module/Controller/Admin/OxpsPasswordPolicyAdminTest.php index 8c638e89..bec47207 100644 --- a/tests/unit/module/Controller/Admin/OxpsPasswordPolicyAdminTest.php +++ b/tests/unit/module/Controller/Admin/OxpsPasswordPolicyAdminTest.php @@ -1,4 +1,5 @@ $aSettings['iMaxPasswordLength']) { $this->assertEquals( 'OXPS_PASSWORDPOLICY_PASSWORDSTRENGTH_ERROR_TOOLONG', - $this->SUT->validatePassword($sValue)); + $this->SUT->validatePassword($sValue) + ); } } } @@ -393,9 +395,11 @@ class oxConfigMock extends oxConfig * @param bool $bPasswordRequiresCapital * @param bool $bPasswordRequiresSpecial */ - public function __mockPasswordRequirements($bPasswordRequiresDigits, $bPasswordRequiresCapital, - $bPasswordRequiresSpecial) - { + public function __mockPasswordRequirements( + $bPasswordRequiresDigits, + $bPasswordRequiresCapital, + $bPasswordRequiresSpecial + ) { $this->_bPasswordRequiresDigits = $bPasswordRequiresDigits; $this->_bPasswordRequiresCapital = $bPasswordRequiresCapital; $this->_bPasswordRequiresSpecial = $bPasswordRequiresSpecial; diff --git a/tests/unit/module/Model/AttemptTest.php b/tests/unit/module/Model/AttemptTest.php index 3e4fa483..f8625c70 100644 --- a/tests/unit/module/Model/AttemptTest.php +++ b/tests/unit/module/Model/AttemptTest.php @@ -1,4 +1,5 @@ setConfig( $oConfigFile ); +$oDb->setConfig($oConfigFile); $oLegacyDb = $oDb->getDb(); -\OxidEsales\Eshop\Core\Registry::set( 'OxDb', $oLegacyDb ); +\OxidEsales\Eshop\Core\Registry::set('OxDb', $oLegacyDb); oxConfig::getInstance(); @@ -80,8 +81,9 @@ public function UNITSetTime($sTime) public function getTime() { - if (!is_null($this->_sTime)) + if (!is_null($this->_sTime)) { return $this->_sTime; + } return parent::getTime(); } diff --git a/tests/unit/test_utils.php b/tests/unit/test_utils.php index c9fd4f33..f27d88c5 100644 --- a/tests/unit/test_utils.php +++ b/tests/unit/test_utils.php @@ -1,4 +1,5 @@ getConfigParam( "dbUser" ) - . " -p" . $oConfig->getConfigParam( "dbPwd" ) - . " " . $oConfig->getConfigParam( "dbName" ) + $sCall = "mysql -u" . $oConfig->getConfigParam("dbUser") + . " -p" . $oConfig->getConfigParam("dbPwd") + . " " . $oConfig->getConfigParam("dbName") . " < " . getTestsBasePath() . "/unit/testdata/" . $sFileName; - exec( $sCall ); + exec($sCall); } /** @@ -63,70 +64,73 @@ function importTestdataFile( $sFileName ) * found it usefull while testing getInstance method, when I needed to know * that my object is really really created, and not taken from cache. */ -function oxClassCacheKey( $reset = false, $sProvide = null ) +function oxClassCacheKey($reset = false, $sProvide = null) { static $key = null; - if ( $key === null || $reset ) { - if ( $sProvide ) + if ($key === null || $reset) { + if ($sProvide) { $key = $sProvide; - else { + } else { $myConfig = modConfig::getInstance(); - if ( is_array( $myConfig->getConfigParam( 'aModules' ) ) ) - $key = md5( 'cc|' . implode( '|', $myConfig->getConfigParam( 'aModules' ) ) ); - else - $key = md5( 'cc|' ); + if (is_array($myConfig->getConfigParam('aModules'))) { + $key = md5('cc|' . implode('|', $myConfig->getConfigParam('aModules'))); + } else { + $key = md5('cc|'); + } } } return $key; } -function oxAddClassModule( $sModuleClass, $sClass ) +function oxAddClassModule($sModuleClass, $sClass) { //$myConfig = modConfig::getInstance(); //$aModules = $myConfig->getConfigParam( 'aModules' ); $oFactory = new oxUtilsObject(); - $aModules = $oFactory->getModuleVar( "aModules" ); + $aModules = $oFactory->getModuleVar("aModules"); //unsetting _possible_ registry instance - \OxidEsales\Eshop\Core\Registry::set( $sClass, null ); + \OxidEsales\Eshop\Core\Registry::set($sClass, null); - if ( $aModules[strtolower( $sClass )] ) - $sModuleClass = $aModules[strtolower( $sClass )] . '&' . $sModuleClass; - $aModules[strtolower( $sClass )] = $sModuleClass; + if ($aModules[strtolower($sClass)]) { + $sModuleClass = $aModules[strtolower($sClass)] . '&' . $sModuleClass; + } + $aModules[strtolower($sClass)] = $sModuleClass; //$myConfig->setConfigParam( 'aModules', $aModules ); - $oFactory->setModuleVar( "aModules", $aModules ); + $oFactory->setModuleVar("aModules", $aModules); - oxClassCacheKey( true ); + oxClassCacheKey(true); } -function oxRemClassModule( $sModuleClass, $sClass = '' ) +function oxRemClassModule($sModuleClass, $sClass = '') { //$myConfig = modConfig::getInstance(); //$aModules = $myConfig->getConfigParam( 'aModules' ); //unsetting _possible_ registry instance - \OxidEsales\Eshop\Core\Registry::set( $sClass, null ); + \OxidEsales\Eshop\Core\Registry::set($sClass, null); $oFactory = new oxUtilsObject(); - $aModules = $oFactory->getModuleVar( "aModules" ); + $aModules = $oFactory->getModuleVar("aModules"); - if ( !$aModules ) + if (!$aModules) { $aModules = array(); + } - if ( $sClass ) { + if ($sClass) { // force for now if ($aModules[$sClass] == $sModuleClass) - unset( $aModules[$sClass] ); + unset($aModules[$sClass]); } else { - while ( ( $sKey = array_search( $sModuleClass, $aModules ) ) !== false ) { - unset( $aModules[$sKey] ); + while (( $sKey = array_search($sModuleClass, $aModules) ) !== false) { + unset($aModules[$sKey]); } } //$myConfig->setConfigParam( 'aModules', $aModules ); - $oFactory->setModuleVar( "aModules", $aModules ); + $oFactory->setModuleVar("aModules", $aModules); - oxClassCacheKey( true ); + oxClassCacheKey(true); } class oxTestModules @@ -134,11 +138,13 @@ class oxTestModules private static $_addedmods = array(); - private static function _getNextName( $sOrig ) + private static function _getNextName($sOrig) { $base = $sOrig . '__oxTestModule_'; $cnt = 0; - while ( class_exists( $base . $cnt, false ) ) ++$cnt; + while (class_exists($base . $cnt, false)) { + ++$cnt; + } return $base . $cnt; } @@ -155,17 +161,17 @@ private static function _getNextName( $sOrig ) * @access public * @return void */ - public static function addVariable( $class, $varName, $access = 'public', $default = 'null' ) + public static function addVariable($class, $varName, $access = 'public', $default = 'null') { - $class = strtolower( $class ); - $name = self::_getNextName( $class ); - if ( $cnt = count( self::$_addedmods[$class] ) ) { + $class = strtolower($class); + $name = self::_getNextName($class); + if ($cnt = count(self::$_addedmods[$class])) { $last = self::$_addedmods[$class][$cnt - 1]; } else { $last = $class; } - eval ( "class $name extends $last { $access \$$varName = $default;}" ); - oxAddClassModule( $name, $class ); + eval("class $name extends $last { $access \$$varName = $default;}"); + oxAddClassModule($name, $class); self::$_addedmods[$class][] = $name; } @@ -180,86 +186,85 @@ public static function addVariable( $class, $varName, $access = 'public', $defau * @access public * @return string */ - public static function addFunction( $class, $fncName, $func ) + public static function addFunction($class, $fncName, $func) { - $class = strtolower( $class ); - $name = self::_getNextName( $class ); + $class = strtolower($class); + $name = self::_getNextName($class); - if ( $cnt = count( self::$_addedmods[$class] ) ) { + if ($cnt = count(self::$_addedmods[$class])) { $last = self::$_addedmods[$class][$cnt - 1]; } else { $last = $class; } $sCode = ''; - if ( preg_match( '/^{.*}$/ms', $func ) ) { - $sCode = "\$aA = func_get_args(); " . trim( $func, '{}' ); + if (preg_match('/^{.*}$/ms', $func)) { + $sCode = "\$aA = func_get_args(); " . trim($func, '{}'); } else { - if ( preg_match( '/^[a-z0-9_-]*$/i', trim( $func ) ) ) { + if (preg_match('/^[a-z0-9_-]*$/i', trim($func))) { $func = "'$func'"; } $sCode = " \$arg = func_get_args(); return call_user_func_array($func, \$arg);"; } - $iErrorReportinc = error_reporting( E_ALL ^ E_NOTICE ); + $iErrorReportinc = error_reporting(E_ALL ^ E_NOTICE); $aFncParams = array(); - if ( strpos( $fncName, '(' ) !== false ) { + if (strpos($fncName, '(') !== false) { $aMatches = null; - preg_match( "@(.*?)\((.*?)\)@", $fncName, $aMatches ); + preg_match("@(.*?)\((.*?)\)@", $fncName, $aMatches); - $fncName = trim( $aMatches[1] ); - if ( trim( $aMatches[2] ) ) { - $aFncParams = explode( ',', $aMatches[2] ); + $fncName = trim($aMatches[1]); + if (trim($aMatches[2])) { + $aFncParams = explode(',', $aMatches[2]); } else { $aFncParams = array(); } } - if ( method_exists( $last, $fncName ) ) { - $oReflection = new ReflectionClass( $last ); - $aMethodParams = $oReflection->getMethod( $fncName )->getParameters(); + if (method_exists($last, $fncName)) { + $oReflection = new ReflectionClass($last); + $aMethodParams = $oReflection->getMethod($fncName)->getParameters(); $fncName .= '('; $blFirst = true; - foreach ( $aMethodParams AS $iKey => $oParam ) { - - if ( !$blFirst ) { + foreach ($aMethodParams as $iKey => $oParam) { + if (!$blFirst) { $fncName .= ', '; } else { $blFirst = false; } - if ( isset( $aFncParams[$iKey] ) ) { + if (isset($aFncParams[$iKey])) { $fncName .= $aFncParams[$iKey]; - if ( strpos( $aFncParams[$iKey], '=' ) === false && $oParam->isDefaultValueAvailable() ) { - $fncName .= ' = ' . var_export( $oParam->getDefaultValue(), true ); + if (strpos($aFncParams[$iKey], '=') === false && $oParam->isDefaultValueAvailable()) { + $fncName .= ' = ' . var_export($oParam->getDefaultValue(), true); } continue; } - if ( $oParam->getClass() ) { + if ($oParam->getClass()) { $fncName .= $oParam->getClass()->getName() . ' '; } $fncName .= '$' . $oParam->getName(); - if ( $oParam->isDefaultValueAvailable() ) { - $fncName .= ' = ' . var_export( $oParam->getDefaultValue(), true ); + if ($oParam->isDefaultValueAvailable()) { + $fncName .= ' = ' . var_export($oParam->getDefaultValue(), true); } } $fncName .= ')'; } else { - if ( empty( $aFncParams ) ) { + if (empty($aFncParams)) { $fncName .= '($p1=null, $p2=null, $p3=null, $p4=null, $p5=null, $p6=null, $p7=null, $p8=null, $p9=null, $p10=null)'; } else { - $fncName .= '(' . implode( ', ', $aFncParams ) . ')'; + $fncName .= '(' . implode(', ', $aFncParams) . ')'; } } - eval ( "class $name extends $last { function $fncName { $sCode }}" ); - oxAddClassModule( $name, $class ); + eval("class $name extends $last { function $fncName { $sCode }}"); + oxAddClassModule($name, $class); - error_reporting( $iErrorReportinc ); + error_reporting($iErrorReportinc); self::$_addedmods[$class][] = $name; @@ -282,10 +287,10 @@ public static function addFunction( $class, $fncName, $func ) * * @return null */ - public static function addModuleObject( $sClassName, $oObject ) + public static function addModuleObject($sClassName, $oObject) { - \OxidEsales\Eshop\Core\Registry::set( $sClassName, null ); - oxUtilsObject::setClassInstance( $sClassName, $oObject ); + \OxidEsales\Eshop\Core\Registry::set($sClassName, null); + oxUtilsObject::setClassInstance($sClassName, $oObject); /* $sClassName = strtolower($sClassName); if (!self::$_oOrigOxUtilsObj) { @@ -325,9 +330,9 @@ public static function addModuleObject( $sClassName, $oObject ) * @access public * @return string */ - public static function publicize( $class, $fnc ) + public static function publicize($class, $fnc) { - return self::addFunction( $class, preg_replace( '/^_/', 'p_', $fnc ), "array(\$this, '$fnc')" ); + return self::addFunction($class, preg_replace('/^_/', 'p_', $fnc), "array(\$this, '$fnc')"); } /** @@ -341,9 +346,9 @@ public static function cleanUp() { self::$_aModuleMap = array(); self::$_oOrigOxUtilsObj = null; - foreach ( self::$_addedmods as $class => $arr ) { + foreach (self::$_addedmods as $class => $arr) { // foreach ($arr as $mod) { - oxRemClassModule( 'allmods', $class ); + oxRemClassModule('allmods', $class); // } } self::$_addedmods = array(); @@ -354,8 +359,8 @@ public static function cleanUp() */ public static function cleanAllModules() { - modConfig::getInstance()->setConfigParam( 'aModules', array() ); - oxClassCacheKey( true, "empty" ); + modConfig::getInstance()->setConfigParam('aModules', array()); + oxClassCacheKey(true, "empty"); } } @@ -372,7 +377,7 @@ class oxTestsStaticCleaner * * @return string */ - protected static function _getChildClass( $sClass ) + protected static function _getChildClass($sClass) { return __CLASS__ . '_' . $sClass; } @@ -385,14 +390,14 @@ protected static function _getChildClass( $sClass ) * * @return null */ - public static function clean( $sClass, $sProperty ) + public static function clean($sClass, $sProperty) { - $sNewCl = self::_getChildClass( $sClass ); - if ( !class_exists( $sNewCl ) ) { - eval ( "class $sNewCl extends $sClass { public function __construct(){} public function __cleaner(\$sProperty) { $sClass::\${\$sProperty}=null; }}" ); + $sNewCl = self::_getChildClass($sClass); + if (!class_exists($sNewCl)) { + eval("class $sNewCl extends $sClass { public function __construct(){} public function __cleaner(\$sProperty) { $sClass::\${\$sProperty}=null; }}"); } $o = new $sNewCl(); - $o->__cleaner( $sProperty ); + $o->__cleaner($sProperty); } } @@ -441,7 +446,7 @@ public function getRealInstance() return $this->_oRealInstance; } - public function modAttach( $oObj = null ) + public function modAttach($oObj = null) { $this->cleanup(); } @@ -452,79 +457,83 @@ public function cleanup() $this->_checkover = array(); $this->_vars = array(); $this->_params = array(); - } public static function globalCleanup() { // cleaning up core info $oConfig = new oxsupercfg(); - $oConfig->setConfig( null ); - $oConfig->setSession( null ); - $oConfig->setUser( null ); - $oConfig->setAdminMode( null ); + $oConfig->setConfig(null); + $oConfig->setSession(null); + $oConfig->setUser(null); + $oConfig->setAdminMode(null); - if ( method_exists( $oConfig, "setRights" ) ) { - $oConfig->setRights( null ); + if (method_exists($oConfig, "setRights")) { + $oConfig->setRights(null); } oxTestModules::cleanAllModules(); } - public function addClassFunction( $sFunction, $callback, $blTakeOver = true ) + public function addClassFunction($sFunction, $callback, $blTakeOver = true) { - $sFunction = strtolower( $sFunction ); - if ( $blTakeOver ) + $sFunction = strtolower($sFunction); + if ($blTakeOver) { $this->_takeover[$sFunction] = $callback; - else + } else { $this->_checkover[$sFunction] = $callback; + } } - public function remClassFunction( $sFunction ) + public function remClassFunction($sFunction) { - $sFunction = strtolower( $sFunction ); - if ( isset( $this->_takeover[$sFunction] ) ) - unset( $this->_takeover[$sFunction] ); - if ( isset( $this->_checkover[$sFunction] ) ) - unset( $this->_checkover[$sFunction] ); + $sFunction = strtolower($sFunction); + if (isset($this->_takeover[$sFunction])) { + unset($this->_takeover[$sFunction]); + } + if (isset($this->_checkover[$sFunction])) { + unset($this->_checkover[$sFunction]); + } } - public function addClassVar( $name, $value = null ) + public function addClassVar($name, $value = null) { - $this->_vars[$name] = ( isset( $value ) ) ? $value : $this->_oRealInstance->$name; + $this->_vars[$name] = ( isset($value) ) ? $value : $this->_oRealInstance->$name; } - public function remClassVar( $name ) + public function remClassVar($name) { - if ( array_key_exists( $name, $this->_vars ) ) - unset( $this->_vars[$name] ); + if (array_key_exists($name, $this->_vars)) { + unset($this->_vars[$name]); + } } - public function __call( $func, $var ) + public function __call($func, $var) { - $funca = strtolower( $func ); - if ( isset( $this->_takeover[$funca] ) ) { - return call_user_func_array( $this->_takeover[$funca], $var ); + $funca = strtolower($func); + if (isset($this->_takeover[$funca])) { + return call_user_func_array($this->_takeover[$funca], $var); } else { - if ( isset( $this->_checkover[$funca] ) ) { - call_user_func_array( $this->_checkover[$funca], $var ); + if (isset($this->_checkover[$funca])) { + call_user_func_array($this->_checkover[$funca], $var); } - return call_user_func_array( array($this->_oRealInstance, $func), $var ); + return call_user_func_array(array($this->_oRealInstance, $func), $var); } } - public function __get( $nm ) + public function __get($nm) { // maybe should copy var line in __set function ??? // if it would help to clone object properties... - if ( array_key_exists( $nm, $this->_vars ) ) + if (array_key_exists($nm, $this->_vars)) { return $this->_vars[$nm]; + } - return $this->_oRealInstance->getConfigParam( $nm ); + return $this->_oRealInstance->getConfigParam($nm); } - public function __set( $nm, $val ) + public function __set($nm, $val) { // this is commented out for the reason: // all tests are INDEPENDANT, so no real changes should be made to the real @@ -537,23 +546,23 @@ public function __set( $nm, $val ) // $this->_oRealInstance->$nm = &$val; } - public function __isset( $nm ) + public function __isset($nm) { - if ( array_key_exists( $nm, $this->_vars ) ) { - return isset( $this->_vars[$nm] ); + if (array_key_exists($nm, $this->_vars)) { + return isset($this->_vars[$nm]); } - return isset( $this->_oRealInstance->$nm ); + return isset($this->_oRealInstance->$nm); } - public function __unset( $nm ) + public function __unset($nm) { - if ( array_key_exists( $nm, $this->_vars ) ) { + if (array_key_exists($nm, $this->_vars)) { $this->_vars[$nm] = null; return; } - unset( $this->_oRealInstance->$nm ); + unset($this->_oRealInstance->$nm); } } @@ -568,12 +577,12 @@ class modConfig extends modOXID protected static $_inst = null; protected $_aConfigparams = array(); - function modAttach( $oObj = null ) + function modAttach($oObj = null) { - parent::modAttach( $oObj ); + parent::modAttach($oObj); self::$unitMOD = null; $this->_oRealInstance = oxConfig::getInstance(); - if ( !$oObj ) { + if (!$oObj) { $oObj = $this; } self::$unitMOD = $oObj; @@ -584,10 +593,12 @@ function modAttach( $oObj = null ) */ static function getInstance() { - if ( !self::$_inst ) + if (!self::$_inst) { self::$_inst = new modConfig(); - if ( !self::$unitMOD ) + } + if (!self::$unitMOD) { self::$_inst->modAttach(); + } return self::$_inst; } @@ -602,72 +613,74 @@ public function cleanup() parent::cleanup(); - if ( oxConfig::getInstance() === $this ) { - throw new Exception( "clean config failed" ); + if (oxConfig::getInstance() === $this) { + throw new Exception("clean config failed"); } } - public function getModConfigParam( $paramName ) + public function getModConfigParam($paramName) { $oInst = self::getInstance(); - if ( array_key_exists( $paramName, $oInst->_aConfigparams ) ) { + if (array_key_exists($paramName, $oInst->_aConfigparams)) { return $oInst->_aConfigparams[$paramName]; } } - public function getConfigParam( $paramName ) + public function getConfigParam($paramName) { $oInst = self::getInstance(); - if ( ( $sValue = $this->getModConfigParam( $paramName ) ) !== null ) { + if (( $sValue = $this->getModConfigParam($paramName) ) !== null) { return $sValue; } else { - if ( !$oInst->_oRealInstance ) { + if (!$oInst->_oRealInstance) { $_i = oxConfig::getInstance(); - if ( $_i instanceof oxConfig ) { - return $_i->getConfigParam( $paramName ); + if ($_i instanceof oxConfig) { + return $_i->getConfigParam($paramName); } - throw new Exception( "real instance is empty!" ); + throw new Exception("real instance is empty!"); } - return $oInst->_oRealInstance->getConfigParam( $paramName ); + return $oInst->_oRealInstance->getConfigParam($paramName); } } public function isDemoShop() { $oInst = self::getInstance(); - if ( isset( $oInst->_aConfigparams['blDemoShop'] ) ) + if (isset($oInst->_aConfigparams['blDemoShop'])) { return $oInst->_aConfigparams['blDemoShop']; - else + } else { return $oInst->_oRealInstance->isDemoShop(); + } } public function isUtf() { $oInst = self::getInstance(); - if ( isset( $oInst->_aConfigparams['iUtfMode'] ) ) + if (isset($oInst->_aConfigparams['iUtfMode'])) { return $oInst->_aConfigparams['iUtfMode']; - else + } else { return $oInst->_oRealInstance->isUtf(); + } } - public function setConfigParam( $paramName, $paramValue ) + public function setConfigParam($paramName, $paramValue) { self::getInstance()->_aConfigparams[$paramName] = $paramValue; } // needed 4 oxConfig - static function getParameter( $paramName, $blRaw = false ) + static function getParameter($paramName, $blRaw = false) { // should throw exception if original functionality is needed. - if ( array_key_exists( $paramName, self::getInstance()->_params ) ) { + if (array_key_exists($paramName, self::getInstance()->_params)) { return self::getInstance()->_params[$paramName]; } else { - return modSession::getInstance()->getVar( $paramName ); + return modSession::getInstance()->getVar($paramName); } } - static function setParameter( $paramName, $paramValue ) + static function setParameter($paramName, $paramValue) { // should throw exception if original functionality is needed. self::getInstance()->_params[$paramName] = $paramValue; @@ -679,7 +692,7 @@ static function setParameter( $paramName, $paramValue ) */ public function getSerial() { - return $this->__call( 'getSerial', array() ); + return $this->__call('getSerial', array()); } } @@ -700,11 +713,11 @@ class modSession extends modOXID */ protected $_aSessionVars = array(); - function modAttach( $oObj = null ) + function modAttach($oObj = null) { - parent::modAttach( $oObj ); + parent::modAttach($oObj); $this->_oRealInstance = oxSession::getInstance(); - if ( !$oObj ) { + if (!$oObj) { $oObj = $this; } self::$unitMOD = $oObj; @@ -713,18 +726,20 @@ function modAttach( $oObj = null ) static function getInstance() { - if ( !self::$_inst ) + if (!self::$_inst) { self::$_inst = new modSession(); - if ( !self::$unitMOD ) + } + if (!self::$unitMOD) { self::$_inst->modAttach(); + } return self::$_inst; } public function cleanup() { - if ( $this->_oRealInstance ) { - $this->_oRealInstance->setId( $this->_id ); + if ($this->_oRealInstance) { + $this->_oRealInstance->setId($this->_id); } self::$unitMOD = null; self::$unitCustMOD = null; @@ -738,7 +753,7 @@ public function cleanup() * @param string $sVar * @param string $sVal */ - public function setVar( $sVar, $sVal ) + public function setVar($sVar, $sVal) { $this->_aSessionVars[$sVar] = $sVal; } @@ -750,10 +765,11 @@ public function setVar( $sVar, $sVal ) * * @return string */ - public function getVar( $sVar ) + public function getVar($sVar) { - if ( isset( $this->_aSessionVars[$sVar] ) ) + if (isset($this->_aSessionVars[$sVar])) { return $this->_aSessionVars[$sVar]; + } return $_SESSION[$sVar]; } @@ -765,12 +781,13 @@ public function getVar( $sVar ) * * @return mixed */ - public function __get( $nm ) + public function __get($nm) { // maybe should copy var line in __set function ??? // if it would help to clone object properties... - if ( array_key_exists( $nm, $this->_vars ) ) + if (array_key_exists($nm, $this->_vars)) { return $this->_vars[$nm]; + } return $this->_oRealInstance->$nm; } @@ -785,30 +802,32 @@ class modDB extends modOXID public static $unitMOD = null; protected static $_inst = null; - function modAttach( $oObj = null ) + function modAttach($oObj = null) { parent::modAttach(); $this->_oRealInstance = oxDb::getDb(); - if ( !$oObj ) { + if (!$oObj) { $oObj = $this; } self::$unitMOD = $oObj; - modConfig::getInstance()->addClassFunction( 'getDB', create_function( '', 'return modDB::$unitMOD;' ) ); + modConfig::getInstance()->addClassFunction('getDB', create_function('', 'return modDB::$unitMOD;')); } static function getInstance() { - if ( !self::$_inst ) + if (!self::$_inst) { self::$_inst = new modDB(); - if ( !self::$unitMOD ) + } + if (!self::$unitMOD) { self::$_inst->modAttach(); + } return self::$_inst; } public function cleanup() { - modConfig::getInstance()->remClassFunction( 'getDB' ); + modConfig::getInstance()->remClassFunction('getDB'); self::$unitMOD = null; parent::cleanup(); } @@ -826,18 +845,20 @@ class modResource function RecordCount() { - if ( $this->recordCount ) + if ($this->recordCount) { $this->EOF = false; - else + } else { $this->EOF = true; + } return $this->recordCount; } function MoveNext() { - if ( ( --$this->recordCount ) == 0 ) + if (( --$this->recordCount ) == 0) { $this->EOF = true; + } } } @@ -853,15 +874,15 @@ class modInstances protected static $_aInst = array(); - public static function addMod( $sModId, $oObject ) + public static function addMod($sModId, $oObject) { - self::$_aInst[strtolower( $sModId ) . oxClassCacheKey()] = $oObject; + self::$_aInst[strtolower($sModId) . oxClassCacheKey()] = $oObject; } - public static function getMod( $sModId ) + public static function getMod($sModId) { //print_r(array_keys(self::$_aInst)); - return self::$_aInst[strtolower( $sModId ) . oxClassCacheKey()]; + return self::$_aInst[strtolower($sModId) . oxClassCacheKey()]; } public static function cleanup() @@ -875,7 +896,7 @@ public static function cleanup() // ############### CodeCoverage Executible Lines Generator ############### // ######################################################################## -if ( !function_exists( 'getFileArr' ) ) { +if (!function_exists('getFileArr')) { function getFileArr() { $sBasePath = oxPATH; @@ -926,27 +947,27 @@ function getFileArr() '/core/smarty/plugins/function.oxcontent.php', '/core/smarty/plugins/block.oxhasrights.php', ); - $arr = findphp( $sBasePath, $aDirBlackList, $aFileBlackList, $aFileWhiteList ); - - if ( $_ENV['PHP_FILE'] ) { - $sTestOnlyFile = basename( $_ENV['PHP_FILE'] ); - $sTestOnlyFile = preg_replace( '/Test.php$/i', '', $sTestOnlyFile ); - $sTestOnlyFile = preg_replace( '/.php$/i', '', $sTestOnlyFile ); - foreach ( $arr as &$sSerchFile ) { - if ( stristr( $sSerchFile, $sTestOnlyFile ) ) { + $arr = findphp($sBasePath, $aDirBlackList, $aFileBlackList, $aFileWhiteList); + + if ($_ENV['PHP_FILE']) { + $sTestOnlyFile = basename($_ENV['PHP_FILE']); + $sTestOnlyFile = preg_replace('/Test.php$/i', '', $sTestOnlyFile); + $sTestOnlyFile = preg_replace('/.php$/i', '', $sTestOnlyFile); + foreach ($arr as &$sSerchFile) { + if (stristr($sSerchFile, $sTestOnlyFile)) { $sTestOnlyFile = $sSerchFile; break; } } - return array($sTestOnlyFile => stripCodeLines( $arr[array_search( $sTestOnlyFile, $arr )], $sCCarrayDir )); + return array($sTestOnlyFile => stripCodeLines($arr[array_search($sTestOnlyFile, $arr)], $sCCarrayDir)); } $ret = array(); - foreach ( $arr as $file ) { + foreach ($arr as $file) { try { - $ret[$file] = stripCodeLines( $file, $sCCarrayDir ); - } catch ( Exception $e ) { + $ret[$file] = stripCodeLines($file, $sCCarrayDir); + } catch (Exception $e) { // do not add file here; echo '', $e->getMessage(), "\n"; } @@ -956,44 +977,44 @@ function getFileArr() } } -if ( !function_exists( 'replaceDirSeperator' ) ) { - function replaceDirSeperator( $sDir ) +if (!function_exists('replaceDirSeperator')) { + function replaceDirSeperator($sDir) { - if ( DIRECTORY_SEPARATOR == '\\' ) { - return str_replace( '/', '\\', $sDir ); + if (DIRECTORY_SEPARATOR == '\\') { + return str_replace('/', '\\', $sDir); } return $sDir; } } -if ( !function_exists( 'preparePathArray' ) ) { - function preparePathArray( &$aPaths, $sBasePath ) +if (!function_exists('preparePathArray')) { + function preparePathArray(&$aPaths, $sBasePath) { - foreach ( array_keys( $aPaths ) as $key ) { + foreach (array_keys($aPaths) as $key) { $aPaths[$key] = $sBasePath . $aPaths[$key]; } - $aPaths = array_map( 'replaceDirSeperator', $aPaths ); + $aPaths = array_map('replaceDirSeperator', $aPaths); } } -if ( !function_exists( 'findphp' ) ) { - function findphp( $baseDir, $aDirBlackList = array(), $aFileBlackList = array(), $aFileWhiteList = array() ) +if (!function_exists('findphp')) { + function findphp($baseDir, $aDirBlackList = array(), $aFileBlackList = array(), $aFileWhiteList = array()) { - $baseDir = preg_replace( '#/$#', '', $baseDir ); - $baseDir = replaceDirSeperator( $baseDir ); + $baseDir = preg_replace('#/$#', '', $baseDir); + $baseDir = replaceDirSeperator($baseDir); $dirs = array($baseDir); - preparePathArray( $aDirBlackList, $baseDir ); - preparePathArray( $aFileBlackList, $baseDir ); - preparePathArray( $aFileWhiteList, $baseDir ); + preparePathArray($aDirBlackList, $baseDir); + preparePathArray($aFileBlackList, $baseDir); + preparePathArray($aFileWhiteList, $baseDir); //get directorys (do not go to blacklist) - while ( list ( , $dir ) = each( $dirs ) ) { - foreach ( glob( $dir . DIRECTORY_SEPARATOR . '*', GLOB_ONLYDIR ) as $sdir ) { - if ( array_search( $sdir, $aDirBlackList ) === false ) { + while (list ( , $dir ) = each($dirs)) { + foreach (glob($dir . DIRECTORY_SEPARATOR . '*', GLOB_ONLYDIR) as $sdir) { + if (array_search($sdir, $aDirBlackList) === false) { $dirs[] = $sdir; } } @@ -1001,19 +1022,19 @@ function findphp( $baseDir, $aDirBlackList = array(), $aFileBlackList = array(), // get PHP files form directorys $aFiles = array(); - foreach ( $dirs as $dir ) { - $aFiles = array_merge( $aFiles, glob( $dir . DIRECTORY_SEPARATOR . "*.php", GLOB_NOSORT ) ); + foreach ($dirs as $dir) { + $aFiles = array_merge($aFiles, glob($dir . DIRECTORY_SEPARATOR . "*.php", GLOB_NOSORT)); } //remove files existing in file blacklist - foreach ( $aFileBlackList as $sFile ) { - $iNR = array_search( $sFile, $aFiles ); - if ( $iNR !== false ) { - unset ( $aFiles[$iNR] ); + foreach ($aFileBlackList as $sFile) { + $iNR = array_search($sFile, $aFiles); + if ($iNR !== false) { + unset($aFiles[$iNR]); } } // add files from white list - foreach ( $aFileWhiteList as $sFile ) { + foreach ($aFileWhiteList as $sFile) { $aFiles[] = $sFile; } @@ -1021,76 +1042,77 @@ function findphp( $baseDir, $aDirBlackList = array(), $aFileBlackList = array(), } } -if ( !function_exists( 'preg_stripper' ) ) { - function preg_stripper( $matches ) +if (!function_exists('preg_stripper')) { + function preg_stripper($matches) { - return preg_replace( '/.*/', '', $matches[0] ); + return preg_replace('/.*/', '', $matches[0]); } } -if ( !function_exists( 'stripCodeLines' ) ) { - function stripCodeLines( $sFile, $sCCarrayDir ) +if (!function_exists('stripCodeLines')) { + function stripCodeLines($sFile, $sCCarrayDir) { - if ( !file_exists( $sFile ) ) { - throw new Exception( "\n" . 'File "' . $sFile . '" does not exists, skipping' ); + if (!file_exists($sFile)) { + throw new Exception("\n" . 'File "' . $sFile . '" does not exists, skipping'); } - $sFileContentMD5 = md5_file( $sFile ); - $sCCFileName = $sCCarrayDir . md5( $sFile ) . "." . $sFileContentMD5; + $sFileContentMD5 = md5_file($sFile); + $sCCFileName = $sCCarrayDir . md5($sFile) . "." . $sFileContentMD5; // delete unneeded files - $aArray = glob( $sCCarrayDir . md5( $sFile ) . ".*" ); + $aArray = glob($sCCarrayDir . md5($sFile) . ".*"); $blFound = false; - if ( count( $aArray ) ) { - while ( $aArray ) { - $sF = array_pop( $aArray ); - if ( !$blFound && $sF === $sCCFileName ) { + if (count($aArray)) { + while ($aArray) { + $sF = array_pop($aArray); + if (!$blFound && $sF === $sCCFileName) { $blFound = true; } else { - unlink( $sF ); + unlink($sF); } } } - if ( !$blFound ) { - $aFile = file_get_contents( $sFile ); + if (!$blFound) { + $aFile = file_get_contents($sFile); - $aFile = str_replace( ' ', '', $aFile ); - $aFile = str_replace( "\t", '', $aFile ); - $aFile = str_replace( "\r", '', $aFile ); + $aFile = str_replace(' ', '', $aFile); + $aFile = str_replace("\t", '', $aFile); + $aFile = str_replace("\r", '', $aFile); - $aFile = preg_replace( '#//.*#', '', $aFile ); - $aFile = preg_replace_callback( '#/\*.*?\*/#sm', 'preg_stripper', $aFile ); + $aFile = preg_replace('#//.*#', '', $aFile); + $aFile = preg_replace_callback('#/\*.*?\*/#sm', 'preg_stripper', $aFile); // for viariables - $aFile = preg_replace( '#(public|static|protected|private|var|\{|\}).*;#', '', $aFile ); + $aFile = preg_replace('#(public|static|protected|private|var|\{|\}).*;#', '', $aFile); //for functions - $aFile = preg_replace( '#(public|static|protected|private|var|\{|\})#', '', $aFile ); + $aFile = preg_replace('#(public|static|protected|private|var|\{|\})#', '', $aFile); - $aFile = preg_replace( '#^class.*?$#m', '', $aFile ); - $aFile = preg_replace_callback( '/\?>.*?<\?php/sm', 'preg_stripper', $aFile ); - $aFile = preg_replace_callback( '/\?>.*?<\?/sm', 'preg_stripper', $aFile ); - $aFile = preg_replace_callback( '/\.*?<\?php/sm', 'preg_stripper', $aFile ); - $aFile = preg_replace_callback( '/\.*?<\?/sm', 'preg_stripper', $aFile ); + $aFile = preg_replace('#^class.*?$#m', '', $aFile); + $aFile = preg_replace_callback('/\?>.*?<\?php/sm', 'preg_stripper', $aFile); + $aFile = preg_replace_callback('/\?>.*?<\?/sm', 'preg_stripper', $aFile); + $aFile = preg_replace_callback('/\.*?<\?php/sm', 'preg_stripper', $aFile); + $aFile = preg_replace_callback('/\.*?<\?/sm', 'preg_stripper', $aFile); - $aFile = preg_replace_callback( '/\?>.*/sm', 'preg_stripper', $aFile ); + $aFile = preg_replace_callback('/\?>.*/sm', 'preg_stripper', $aFile); - $aFile = preg_replace( '#^\$[a-zA-Z0-9_]+;$#m', '', $aFile ); + $aFile = preg_replace('#^\$[a-zA-Z0-9_]+;$#m', '', $aFile); - $aFile = preg_replace( '#^function[a-zA-Z0-9_]+\(.*?\)\{?$#m', '', $aFile ); - $aFile = preg_replace( '#.+#', '1', $aFile ); + $aFile = preg_replace('#^function[a-zA-Z0-9_]+\(.*?\)\{?$#m', '', $aFile); + $aFile = preg_replace('#.+#', '1', $aFile); - $aFile = preg_replace( '#^$#m', '0', $aFile ); - $aFile = str_replace( "\n", '', $aFile ); + $aFile = preg_replace('#^$#m', '0', $aFile); + $aFile = str_replace("\n", '', $aFile); $aCC = array(); - for ( $i = 0; $i < strlen( $aFile ); $i++ ) { - if ( $aFile[$i] === '1' ) + for ($i = 0; $i < strlen($aFile); $i++) { + if ($aFile[$i] === '1') { $aCC[$i + 1] = -1; + } } - file_put_contents( $sCCFileName, serialize( $aCC ) ); + file_put_contents($sCCFileName, serialize($aCC)); return $aCC; } else { - return unserialize( file_get_contents( $sCCFileName ) ); + return unserialize(file_get_contents($sCCFileName)); } } } @@ -1108,7 +1130,7 @@ class oxTestModuleLoader * * @param boolean $blOriginal */ - public static function useOriginalChain( $blOriginal ) + public static function useOriginalChain($blOriginal) { self::$_blOriginal = $blOriginal; } @@ -1118,32 +1140,31 @@ public static function useOriginalChain( $blOriginal ) */ public static function initFromMetadata() { - $sPath = getenv( 'oxMETADATA' ); + $sPath = getenv('oxMETADATA'); // if metadata exists - if ( file_exists( $sPath ) ) { - + if (file_exists($sPath)) { include $sPath; // including all filles from ["files"] - if ( isset( $aModule["files"] ) && count( $aModule["files"] ) ) { - foreach ( $aModule["files"] as $sFilePath ) { - require_once oxConfig::getInstance()->getConfigParam( "sShopDir" ) . "/modules/" . $sFilePath; + if (isset($aModule["files"]) && count($aModule["files"])) { + foreach ($aModule["files"] as $sFilePath) { + require_once oxConfig::getInstance()->getConfigParam("sShopDir") . "/modules/" . $sFilePath; } } // adding and extending the module files - if ( isset( $aModule["extend"] ) && count( $aModule["extend"] ) ) { - foreach ( $aModule["extend"] as $sParent => $sPathToModule ) { - $sClassName = basename( $sPathToModule ); + if (isset($aModule["extend"]) && count($aModule["extend"])) { + foreach ($aModule["extend"] as $sParent => $sPathToModule) { + $sClassName = basename($sPathToModule); $sFakeParent = $sClassName . "_parent"; - if ( !class_exists( $sFakeParent ) ) { - eval( "class $sFakeParent extends $sParent {}" ); + if (!class_exists($sFakeParent)) { + eval("class $sFakeParent extends $sParent {}"); } - require_once oxConfig::getInstance()->getConfigParam( "sShopDir" ) . "/modules/" . $sPathToModule . ".php"; + require_once oxConfig::getInstance()->getConfigParam("sShopDir") . "/modules/" . $sPathToModule . ".php"; } - self::_appendToChain( $aModule["extend"] ); + self::_appendToChain($aModule["extend"]); } } } @@ -1157,9 +1178,9 @@ public static function initFromMetadata() public static function loadModule() { // if theres a chain already saved and is not empty - if ( count( self::$_aChain ) ) { - \OxidEsales\Eshop\Core\Registry::getConfig()->setConfigParam( "aModules", self::$_aChain ); - \OxidEsales\Eshop\Core\Registry::get( "oxUtilsObject" )->setModuleVar( "aDisabledModules", array() ); + if (count(self::$_aChain)) { + \OxidEsales\Eshop\Core\Registry::getConfig()->setConfigParam("aModules", self::$_aChain); + \OxidEsales\Eshop\Core\Registry::get("oxUtilsObject")->setModuleVar("aDisabledModules", array()); } } @@ -1168,23 +1189,23 @@ public static function loadModule() * * @param array $aChain array with the module chain */ - public static function append( array $aChain ) + public static function append(array $aChain) { - self::_appendToChain( $aChain ); + self::_appendToChain($aChain); } - public static function _appendToChain( $aExtend ) + public static function _appendToChain($aExtend) { // if the chain is still empty and "original" chain is needed - if ( self::$_blOriginal && !count( self::$_aChain ) ) { - self::$_aChain = (array) modConfig::getInstance()->getConfigParam( "aModules" ); + if (self::$_blOriginal && !count(self::$_aChain)) { + self::$_aChain = (array) modConfig::getInstance()->getConfigParam("aModules"); } // addping the "extend" chain to the main chain - foreach ( $aExtend as $sParent => $sExtends ) { - if ( isset( self::$_aChain[$sParent] ) ) { - $sExtends = trim( self::$_aChain[$sParent], "& " ) . "&" - . trim( $sExtends, "& " ); + foreach ($aExtend as $sParent => $sExtends) { + if (isset(self::$_aChain[$sParent])) { + $sExtends = trim(self::$_aChain[$sParent], "& ") . "&" + . trim($sExtends, "& "); } self::$_aChain[$sParent] = $sExtends; } diff --git a/translations/de/passwordpolicy_lang.php b/translations/de/passwordpolicy_lang.php index 9b83ae1b..d9843cbf 100644 --- a/translations/de/passwordpolicy_lang.php +++ b/translations/de/passwordpolicy_lang.php @@ -1,4 +1,5 @@ Date: Fri, 12 Feb 2021 17:47:19 +0100 Subject: [PATCH 3/5] prepare tests --- composer.json | 8 +- tests/phpunit.xml | 25 + .../Component/UserComponentTest.php | 0 .../AccountPasswordControllerTest.php | 0 .../Admin/OxpsPasswordPolicyAdminTest.php | 0 .../ForgotPasswordControllerTest.php | 0 .../Controller/OxpsPasswordPolicyTest.php | 0 .../Controller/RegisterControllerTest.php | 0 .../Core/PasswordPolicyModuleTest.php | 0 tests/unit/{module => }/Model/AttemptTest.php | 0 tests/unit/test_config.inc.php | 123 -- tests/unit/test_utils.php | 1213 ----------------- tests/unit/testdata/.gitkeep | 0 13 files changed, 31 insertions(+), 1338 deletions(-) create mode 100644 tests/phpunit.xml rename tests/unit/{module => }/Component/UserComponentTest.php (100%) rename tests/unit/{module => }/Controller/AccountPasswordControllerTest.php (100%) rename tests/unit/{module => }/Controller/Admin/OxpsPasswordPolicyAdminTest.php (100%) rename tests/unit/{module => }/Controller/ForgotPasswordControllerTest.php (100%) rename tests/unit/{module => }/Controller/OxpsPasswordPolicyTest.php (100%) rename tests/unit/{module => }/Controller/RegisterControllerTest.php (100%) rename tests/unit/{module => }/Core/PasswordPolicyModuleTest.php (100%) rename tests/unit/{module => }/Model/AttemptTest.php (100%) delete mode 100644 tests/unit/test_config.inc.php delete mode 100644 tests/unit/test_utils.php delete mode 100644 tests/unit/testdata/.gitkeep diff --git a/composer.json b/composer.json index 7f1595ac..e9264f60 100644 --- a/composer.json +++ b/composer.json @@ -7,6 +7,9 @@ "require": { "oxid-esales/oxideshop-ce": "^v6.3" }, + "require-dev": { + + } "extra": { "oxideshop": { "target-directory": "oxps/passwordpolicy" @@ -14,7 +17,8 @@ }, "autoload": { "psr-4": { - "OxidProfessionalServices\\PasswordPolicy\\": "src" + "OxidProfessionalServices\\PasswordPolicy\\": "src", + "OxidProfessionalServices\\PasswordPolicy\\Tests": "tests" } } -} +}, diff --git a/tests/phpunit.xml b/tests/phpunit.xml new file mode 100644 index 00000000..e364e716 --- /dev/null +++ b/tests/phpunit.xml @@ -0,0 +1,25 @@ + + + + ../src/Core + ../src/Controller + ../src/Component + ../src/Model + + + diff --git a/tests/unit/module/Component/UserComponentTest.php b/tests/unit/Component/UserComponentTest.php similarity index 100% rename from tests/unit/module/Component/UserComponentTest.php rename to tests/unit/Component/UserComponentTest.php diff --git a/tests/unit/module/Controller/AccountPasswordControllerTest.php b/tests/unit/Controller/AccountPasswordControllerTest.php similarity index 100% rename from tests/unit/module/Controller/AccountPasswordControllerTest.php rename to tests/unit/Controller/AccountPasswordControllerTest.php diff --git a/tests/unit/module/Controller/Admin/OxpsPasswordPolicyAdminTest.php b/tests/unit/Controller/Admin/OxpsPasswordPolicyAdminTest.php similarity index 100% rename from tests/unit/module/Controller/Admin/OxpsPasswordPolicyAdminTest.php rename to tests/unit/Controller/Admin/OxpsPasswordPolicyAdminTest.php diff --git a/tests/unit/module/Controller/ForgotPasswordControllerTest.php b/tests/unit/Controller/ForgotPasswordControllerTest.php similarity index 100% rename from tests/unit/module/Controller/ForgotPasswordControllerTest.php rename to tests/unit/Controller/ForgotPasswordControllerTest.php diff --git a/tests/unit/module/Controller/OxpsPasswordPolicyTest.php b/tests/unit/Controller/OxpsPasswordPolicyTest.php similarity index 100% rename from tests/unit/module/Controller/OxpsPasswordPolicyTest.php rename to tests/unit/Controller/OxpsPasswordPolicyTest.php diff --git a/tests/unit/module/Controller/RegisterControllerTest.php b/tests/unit/Controller/RegisterControllerTest.php similarity index 100% rename from tests/unit/module/Controller/RegisterControllerTest.php rename to tests/unit/Controller/RegisterControllerTest.php diff --git a/tests/unit/module/Core/PasswordPolicyModuleTest.php b/tests/unit/Core/PasswordPolicyModuleTest.php similarity index 100% rename from tests/unit/module/Core/PasswordPolicyModuleTest.php rename to tests/unit/Core/PasswordPolicyModuleTest.php diff --git a/tests/unit/module/Model/AttemptTest.php b/tests/unit/Model/AttemptTest.php similarity index 100% rename from tests/unit/module/Model/AttemptTest.php rename to tests/unit/Model/AttemptTest.php diff --git a/tests/unit/test_config.inc.php b/tests/unit/test_config.inc.php deleted file mode 100644 index 9f5052c5..00000000 --- a/tests/unit/test_config.inc.php +++ /dev/null @@ -1,123 +0,0 @@ -setConfig($oConfigFile); -$oLegacyDb = $oDb->getDb(); -\OxidEsales\Eshop\Core\Registry::set('OxDb', $oLegacyDb); - -oxConfig::getInstance(); - -/** - * Useful for defining custom time - */ -class modOxUtilsDate extends oxUtilsDate -{ - protected $_sTime = null; - - public function UNITSetTime($sTime) - { - $this->_sTime = $sTime; - } - - public function getTime() - { - if (!is_null($this->_sTime)) { - return $this->_sTime; - } - - return parent::getTime(); - } -} - -// Utility class -require_once getShopBasePath() . 'core/oxutils.php'; - -// Database managing class. -require_once getShopBasePath() . 'core/adodblite/adodb.inc.php'; - -// Session managing class. -require_once getShopBasePath() . 'core/oxsession.php'; - -// Database session managing class. -// included in session file if needed - require_once( getShopBasePath() . 'core/adodb/session/adodb-session.php'); - -// DB managing class. -//require_once( getShopBasePath() . 'core/adodb/drivers/adodb-mysql.inc.php'); -require_once getShopBasePath() . 'core/oxconfig.php'; - -function initDbDump() -{ - static $done = false; - if ($done) { - throw new Exception("init already done"); - } - if (file_exists('unit/dbMaintenance.php')) { - include_once 'unit/dbMaintenance.php'; - } else { - include_once 'dbMaintenance.php'; - } - $dbM = new dbMaintenance(); - $dbM->dumpDB(); - $done = true; -} -initDbDump(); diff --git a/tests/unit/test_utils.php b/tests/unit/test_utils.php deleted file mode 100644 index f27d88c5..00000000 --- a/tests/unit/test_utils.php +++ /dev/null @@ -1,1213 +0,0 @@ -getConfigParam("dbUser") - . " -p" . $oConfig->getConfigParam("dbPwd") - . " " . $oConfig->getConfigParam("dbName") - . " < " . getTestsBasePath() . "/unit/testdata/" . $sFileName; - exec($sCall); -} - -/** - * adds new module to specified class - * Usable if you want to check how many calls of class AA method BB - * done while testing class XX. - * Or can be used to disable some AA method like BB (e.g. die), - * which gets called while testing XX. - * Since there are no modules in testing data, this function does not - * check module parent module - * - * e.g. - * - we need to disable oxUtils::showMessageAndDie - * class modUtils extends oxutils { - * function showMessageAndDie (){} - * }; - * - and then in your test function - * oxAddClassModule('modUtils', 'oxutils'); - * - and after doing some ... - * oxRemClassModule('modUtils'); - * - * - now one can provide his/her own oxClassCacheKey - * found it usefull while testing getInstance method, when I needed to know - * that my object is really really created, and not taken from cache. - */ -function oxClassCacheKey($reset = false, $sProvide = null) -{ - static $key = null; - if ($key === null || $reset) { - if ($sProvide) { - $key = $sProvide; - } else { - $myConfig = modConfig::getInstance(); - if (is_array($myConfig->getConfigParam('aModules'))) { - $key = md5('cc|' . implode('|', $myConfig->getConfigParam('aModules'))); - } else { - $key = md5('cc|'); - } - } - } - - return $key; -} - -function oxAddClassModule($sModuleClass, $sClass) -{ - //$myConfig = modConfig::getInstance(); - //$aModules = $myConfig->getConfigParam( 'aModules' ); - $oFactory = new oxUtilsObject(); - $aModules = $oFactory->getModuleVar("aModules"); - - //unsetting _possible_ registry instance - \OxidEsales\Eshop\Core\Registry::set($sClass, null); - - if ($aModules[strtolower($sClass)]) { - $sModuleClass = $aModules[strtolower($sClass)] . '&' . $sModuleClass; - } - $aModules[strtolower($sClass)] = $sModuleClass; - - //$myConfig->setConfigParam( 'aModules', $aModules ); - $oFactory->setModuleVar("aModules", $aModules); - - oxClassCacheKey(true); -} - -function oxRemClassModule($sModuleClass, $sClass = '') -{ - //$myConfig = modConfig::getInstance(); - //$aModules = $myConfig->getConfigParam( 'aModules' ); - - //unsetting _possible_ registry instance - \OxidEsales\Eshop\Core\Registry::set($sClass, null); - - $oFactory = new oxUtilsObject(); - $aModules = $oFactory->getModuleVar("aModules"); - - if (!$aModules) { - $aModules = array(); - } - - if ($sClass) { -// force for now if ($aModules[$sClass] == $sModuleClass) - unset($aModules[$sClass]); - } else { - while (( $sKey = array_search($sModuleClass, $aModules) ) !== false) { - unset($aModules[$sKey]); - } - } - //$myConfig->setConfigParam( 'aModules', $aModules ); - $oFactory->setModuleVar("aModules", $aModules); - - oxClassCacheKey(true); -} - -class oxTestModules -{ - - private static $_addedmods = array(); - - private static function _getNextName($sOrig) - { - $base = $sOrig . '__oxTestModule_'; - $cnt = 0; - while (class_exists($base . $cnt, false)) { - ++$cnt; - } - - return $base . $cnt; - } - - /** - * addVar adds module and creates function in it - * - * @param string $class target class - * @param string $varName target variabe - * @param string $access public | private | public static, whatever - * @param string $default default value - * - * @static - * @access public - * @return void - */ - public static function addVariable($class, $varName, $access = 'public', $default = 'null') - { - $class = strtolower($class); - $name = self::_getNextName($class); - if ($cnt = count(self::$_addedmods[$class])) { - $last = self::$_addedmods[$class][$cnt - 1]; - } else { - $last = $class; - } - eval("class $name extends $last { $access \$$varName = $default;}"); - oxAddClassModule($name, $class); - self::$_addedmods[$class][] = $name; - } - - /** - * addFunction adds module and creates function in it - * - * @param mixed $class target class - * @param mixed $fncName target function - * @param mixed $func function - if it is '{...}' then it is function code ($aA is arguments array), else it is taken as param to call_user_func_array - * - * @static - * @access public - * @return string - */ - public static function addFunction($class, $fncName, $func) - { - $class = strtolower($class); - $name = self::_getNextName($class); - - if ($cnt = count(self::$_addedmods[$class])) { - $last = self::$_addedmods[$class][$cnt - 1]; - } else { - $last = $class; - } - $sCode = ''; - if (preg_match('/^{.*}$/ms', $func)) { - $sCode = "\$aA = func_get_args(); " . trim($func, '{}'); - } else { - if (preg_match('/^[a-z0-9_-]*$/i', trim($func))) { - $func = "'$func'"; - } - $sCode = " \$arg = func_get_args(); return call_user_func_array($func, \$arg);"; - } - - $iErrorReportinc = error_reporting(E_ALL ^ E_NOTICE); - - $aFncParams = array(); - if (strpos($fncName, '(') !== false) { - $aMatches = null; - preg_match("@(.*?)\((.*?)\)@", $fncName, $aMatches); - - $fncName = trim($aMatches[1]); - if (trim($aMatches[2])) { - $aFncParams = explode(',', $aMatches[2]); - } else { - $aFncParams = array(); - } - } - - if (method_exists($last, $fncName)) { - $oReflection = new ReflectionClass($last); - $aMethodParams = $oReflection->getMethod($fncName)->getParameters(); - - $fncName .= '('; - $blFirst = true; - foreach ($aMethodParams as $iKey => $oParam) { - if (!$blFirst) { - $fncName .= ', '; - } else { - $blFirst = false; - } - - if (isset($aFncParams[$iKey])) { - $fncName .= $aFncParams[$iKey]; - - if (strpos($aFncParams[$iKey], '=') === false && $oParam->isDefaultValueAvailable()) { - $fncName .= ' = ' . var_export($oParam->getDefaultValue(), true); - } - - continue; - } - - if ($oParam->getClass()) { - $fncName .= $oParam->getClass()->getName() . ' '; - } - $fncName .= '$' . $oParam->getName(); - if ($oParam->isDefaultValueAvailable()) { - $fncName .= ' = ' . var_export($oParam->getDefaultValue(), true); - } - } - $fncName .= ')'; - } else { - if (empty($aFncParams)) { - $fncName .= '($p1=null, $p2=null, $p3=null, $p4=null, $p5=null, $p6=null, $p7=null, $p8=null, $p9=null, $p10=null)'; - } else { - $fncName .= '(' . implode(', ', $aFncParams) . ')'; - } - } - - eval("class $name extends $last { function $fncName { $sCode }}"); - oxAddClassModule($name, $class); - - error_reporting($iErrorReportinc); - - self::$_addedmods[$class][] = $name; - - return $name; - } - - /** - * internal class->object map - * - * @var array - */ - protected static $_aModuleMap = array(); - protected static $_oOrigOxUtilsObj = null; - - /** - * add object to be returned from oxNew for a class - * - * @param string $sClassName - * @param object $oObject - * - * @return null - */ - public static function addModuleObject($sClassName, $oObject) - { - \OxidEsales\Eshop\Core\Registry::set($sClassName, null); - oxUtilsObject::setClassInstance($sClassName, $oObject); - /* - $sClassName = strtolower($sClassName); - if (!self::$_oOrigOxUtilsObj) { - self::$_oOrigOxUtilsObj = oxUtilsObject::getInstance(); - self::addFunction('oxUtilsObject', 'oxNew($class)', '{return oxTestModules::getModuleObject($class);}'); - } - self::$_aModuleMap[$sClassName] = $oObject; - */ - } - - /** - * rewrittern oxNew logic to return object from the map - * - * @param string $sClassName - * - * @return object - */ - /*public static function getModuleObject($sClassName) - { - $sClassName = strtolower($sClassName); - if (isset(self::$_aModuleMap[$sClassName])) { - return self::$_aModuleMap[$sClassName]; - } - if (!self::$_oOrigOxUtilsObj) { - throw new Exception("TEST ERROR: original oxUtilsObject is badly initialized"); - } - return self::$_oOrigOxUtilsObj->oxNew($sClassName); - }*/ - - /** - * publicize method = creates a wrapper for it named p_XXX instead of _XXX - * - * @param mixed $class - * @param mixed $fnc - * - * @static - * @access public - * @return string - */ - public static function publicize($class, $fnc) - { - return self::addFunction($class, preg_replace('/^_/', 'p_', $fnc), "array(\$this, '$fnc')"); - } - - /** - * clean Ups loaded modules - * - * @static - * @access public - * @return void - */ - public static function cleanUp() - { - self::$_aModuleMap = array(); - self::$_oOrigOxUtilsObj = null; - foreach (self::$_addedmods as $class => $arr) { -// foreach ($arr as $mod) { - oxRemClassModule('allmods', $class); - // } - } - self::$_addedmods = array(); - } - - /** - * cleans every module attached - */ - public static function cleanAllModules() - { - modConfig::getInstance()->setConfigParam('aModules', array()); - oxClassCacheKey(true, "empty"); - } -} - -/** - * creates static cleaner subclasses and nulls parent class protected static property - */ -class oxTestsStaticCleaner -{ - - /** - * get class name - * - * @param string $sClass - * - * @return string - */ - protected static function _getChildClass($sClass) - { - return __CLASS__ . '_' . $sClass; - } - - /** - * create cleaner and execute it - * - * @param string $sClass - * @param string $sProperty - * - * @return null - */ - public static function clean($sClass, $sProperty) - { - $sNewCl = self::_getChildClass($sClass); - if (!class_exists($sNewCl)) { - eval("class $sNewCl extends $sClass { public function __construct(){} public function __cleaner(\$sProperty) { $sClass::\${\$sProperty}=null; }}"); - } - $o = new $sNewCl(); - $o->__cleaner($sProperty); - } -} - -/** - * adds or replaces oxConfig functionality. - * [because you just can not use module emulation functionality with oxConfig] - * usage: - * to initialize just create a new instance of the class. - * to replace OR attach some oxConfig function use addClassFunction method: - * to end with mod, use remClassFunction or just cleanup. - * - * e.g. - * - * Executor - * $a = modConfig::getInstance(); - * $a->addClassFunction('getDB', array($this, 'getMyDb')); - * - * OR - * - * Observer - * $a = modConfig::getInstance(); - * $a->addClassFunction('getDB', array($this, 'countGetDbCalls'), false); - * - * - * this class is also usable to override some oxConfig variable by using - * addClassVar function (if second parameter is null [default], the initial value of - * overriden variable is the orginal oxConfig's value) - * - * Also, since all tests are INDEPENDANT, no real changes are made to the real instance. - * NOTE: after cleanup, all oxConfig variable changes while modConfig was active are LOST. - * - */ - - -abstract class modOXID -{ - - protected $_takeover = array(); - protected $_checkover = array(); - protected $_vars = array(); - protected $_params = array(); - protected $_oRealInstance = null; - - public function getRealInstance() - { - return $this->_oRealInstance; - } - - public function modAttach($oObj = null) - { - $this->cleanup(); - } - - public function cleanup() - { - $this->_takeover = array(); - $this->_checkover = array(); - $this->_vars = array(); - $this->_params = array(); - } - - public static function globalCleanup() - { - // cleaning up core info - $oConfig = new oxsupercfg(); - $oConfig->setConfig(null); - $oConfig->setSession(null); - $oConfig->setUser(null); - $oConfig->setAdminMode(null); - - if (method_exists($oConfig, "setRights")) { - $oConfig->setRights(null); - } - - oxTestModules::cleanAllModules(); - } - - public function addClassFunction($sFunction, $callback, $blTakeOver = true) - { - $sFunction = strtolower($sFunction); - if ($blTakeOver) { - $this->_takeover[$sFunction] = $callback; - } else { - $this->_checkover[$sFunction] = $callback; - } - } - - public function remClassFunction($sFunction) - { - $sFunction = strtolower($sFunction); - if (isset($this->_takeover[$sFunction])) { - unset($this->_takeover[$sFunction]); - } - if (isset($this->_checkover[$sFunction])) { - unset($this->_checkover[$sFunction]); - } - } - - public function addClassVar($name, $value = null) - { - $this->_vars[$name] = ( isset($value) ) ? $value : $this->_oRealInstance->$name; - } - - public function remClassVar($name) - { - if (array_key_exists($name, $this->_vars)) { - unset($this->_vars[$name]); - } - } - - public function __call($func, $var) - { - $funca = strtolower($func); - if (isset($this->_takeover[$funca])) { - return call_user_func_array($this->_takeover[$funca], $var); - } else { - if (isset($this->_checkover[$funca])) { - call_user_func_array($this->_checkover[$funca], $var); - } - - return call_user_func_array(array($this->_oRealInstance, $func), $var); - } - } - - public function __get($nm) - { - // maybe should copy var line in __set function ??? - // if it would help to clone object properties... - if (array_key_exists($nm, $this->_vars)) { - return $this->_vars[$nm]; - } - - return $this->_oRealInstance->getConfigParam($nm); - } - - public function __set($nm, $val) - { - // this is commented out for the reason: - // all tests are INDEPENDANT, so no real changes should be made to the real - // instance. - // NOTE: after cleanup, all changes to oxConfig while modConfig was active are LOST. - // if (array_key_exists($nm, $this->_vars)) { - $this->_vars[$nm] = $val; - // return; - // } - // $this->_oRealInstance->$nm = &$val; - } - - public function __isset($nm) - { - if (array_key_exists($nm, $this->_vars)) { - return isset($this->_vars[$nm]); - } - - return isset($this->_oRealInstance->$nm); - } - - public function __unset($nm) - { - if (array_key_exists($nm, $this->_vars)) { - $this->_vars[$nm] = null; - - return; - } - unset($this->_oRealInstance->$nm); - } -} - -//----------------- - -class modConfig extends modOXID -{ - - // needed 4 modOXID - public static $unitMOD = null; - public static $unitCustMOD = null; - protected static $_inst = null; - protected $_aConfigparams = array(); - - function modAttach($oObj = null) - { - parent::modAttach($oObj); - self::$unitMOD = null; - $this->_oRealInstance = oxConfig::getInstance(); - if (!$oObj) { - $oObj = $this; - } - self::$unitMOD = $oObj; - } - - /** - * @return modconfig - */ - static function getInstance() - { - if (!self::$_inst) { - self::$_inst = new modConfig(); - } - if (!self::$unitMOD) { - self::$_inst->modAttach(); - } - - return self::$_inst; - } - - public function cleanup() - { - self::$unitMOD = null; - self::$unitCustMOD = null; - - // cleaning config parameters - $this->_aConfigparams = array(); - - parent::cleanup(); - - if (oxConfig::getInstance() === $this) { - throw new Exception("clean config failed"); - } - } - - public function getModConfigParam($paramName) - { - $oInst = self::getInstance(); - if (array_key_exists($paramName, $oInst->_aConfigparams)) { - return $oInst->_aConfigparams[$paramName]; - } - } - - public function getConfigParam($paramName) - { - $oInst = self::getInstance(); - if (( $sValue = $this->getModConfigParam($paramName) ) !== null) { - return $sValue; - } else { - if (!$oInst->_oRealInstance) { - $_i = oxConfig::getInstance(); - if ($_i instanceof oxConfig) { - return $_i->getConfigParam($paramName); - } - throw new Exception("real instance is empty!"); - } - - return $oInst->_oRealInstance->getConfigParam($paramName); - } - } - - public function isDemoShop() - { - $oInst = self::getInstance(); - if (isset($oInst->_aConfigparams['blDemoShop'])) { - return $oInst->_aConfigparams['blDemoShop']; - } else { - return $oInst->_oRealInstance->isDemoShop(); - } - } - - public function isUtf() - { - $oInst = self::getInstance(); - if (isset($oInst->_aConfigparams['iUtfMode'])) { - return $oInst->_aConfigparams['iUtfMode']; - } else { - return $oInst->_oRealInstance->isUtf(); - } - } - - public function setConfigParam($paramName, $paramValue) - { - self::getInstance()->_aConfigparams[$paramName] = $paramValue; - } - - // needed 4 oxConfig - static function getParameter($paramName, $blRaw = false) - { - // should throw exception if original functionality is needed. - if (array_key_exists($paramName, self::getInstance()->_params)) { - return self::getInstance()->_params[$paramName]; - } else { - return modSession::getInstance()->getVar($paramName); - } - } - - static function setParameter($paramName, $paramValue) - { - // should throw exception if original functionality is needed. - self::getInstance()->_params[$paramName] = $paramValue; - } - - /** - * needed for Erp test where it checks it with method_exists - * - */ - public function getSerial() - { - return $this->__call('getSerial', array()); - } -} - -//----------------- - -class modSession extends modOXID -{ - - public static $unitMOD = null; - public static $unitCustMOD = null; - protected static $_inst = null; - protected $_id = null; - - /** - * Keeps test session vars - * - * @var array - */ - protected $_aSessionVars = array(); - - function modAttach($oObj = null) - { - parent::modAttach($oObj); - $this->_oRealInstance = oxSession::getInstance(); - if (!$oObj) { - $oObj = $this; - } - self::$unitMOD = $oObj; - $this->_id = $this->_oRealInstance->getId(); - } - - static function getInstance() - { - if (!self::$_inst) { - self::$_inst = new modSession(); - } - if (!self::$unitMOD) { - self::$_inst->modAttach(); - } - - return self::$_inst; - } - - public function cleanup() - { - if ($this->_oRealInstance) { - $this->_oRealInstance->setId($this->_id); - } - self::$unitMOD = null; - self::$unitCustMOD = null; - parent::cleanup(); - $this->_aSessionVars = array(); - } - - /** - * Set session var for testing - * - * @param string $sVar - * @param string $sVal - */ - public function setVar($sVar, $sVal) - { - $this->_aSessionVars[$sVar] = $sVal; - } - - /** - * Gets session var for testing - * - * @param string $sVar - * - * @return string - */ - public function getVar($sVar) - { - if (isset($this->_aSessionVars[$sVar])) { - return $this->_aSessionVars[$sVar]; - } - - return $_SESSION[$sVar]; - } - - /** - * Session properties getter - * - * @param string $nm name of parameter - * - * @return mixed - */ - public function __get($nm) - { - // maybe should copy var line in __set function ??? - // if it would help to clone object properties... - if (array_key_exists($nm, $this->_vars)) { - return $this->_vars[$nm]; - } - - return $this->_oRealInstance->$nm; - } -} - -//----------------- - -class modDB extends modOXID -{ - - // needed 4 modOXID - public static $unitMOD = null; - protected static $_inst = null; - - function modAttach($oObj = null) - { - parent::modAttach(); - $this->_oRealInstance = oxDb::getDb(); - if (!$oObj) { - $oObj = $this; - } - self::$unitMOD = $oObj; - modConfig::getInstance()->addClassFunction('getDB', create_function('', 'return modDB::$unitMOD;')); - } - - static function getInstance() - { - if (!self::$_inst) { - self::$_inst = new modDB(); - } - if (!self::$unitMOD) { - self::$_inst->modAttach(); - } - - return self::$_inst; - } - - public function cleanup() - { - modConfig::getInstance()->remClassFunction('getDB'); - self::$unitMOD = null; - parent::cleanup(); - } -} - -//----------------- - -// usefull for extending getDB()->Execute method -class modResource -{ - - public $recordCount = 0; - public $eof = true; - public $fields = array(); - - function RecordCount() - { - if ($this->recordCount) { - $this->EOF = false; - } else { - $this->EOF = true; - } - - return $this->recordCount; - } - - function MoveNext() - { - if (( --$this->recordCount ) == 0) { - $this->EOF = true; - } - } -} - -// Stores added objects instances in array -// On cleanup clears all stored instances -// Add modInstances->getInstance()->cleanup() when testing in tearDown() -// to force recreate added objects - -//----------------- - -class modInstances -{ - - protected static $_aInst = array(); - - public static function addMod($sModId, $oObject) - { - self::$_aInst[strtolower($sModId) . oxClassCacheKey()] = $oObject; - } - - public static function getMod($sModId) - { - //print_r(array_keys(self::$_aInst)); - return self::$_aInst[strtolower($sModId) . oxClassCacheKey()]; - } - - public static function cleanup() - { - self::$_aInst = array(); - } -} - - -// ######################################################################## -// ############### CodeCoverage Executible Lines Generator ############### -// ######################################################################## - -if (!function_exists('getFileArr')) { - function getFileArr() - { - $sBasePath = oxPATH; - $sCCarrayDir = oxCCTempDir; - - $aDirBlackList = array( - '/admin/dtaus', - '/admin/reports/jpgraph', - '/admin/wysiwigpro', - '/core/adodb', - '/core/openid', - '/core/adodblite', - '/core/emailvalidation', - '/core/ERP', - '/core/tcpdf', - '/core/nusoap', - '/core/phpmailer', - '/core/smarty', - '/force_version', - '/out', - '/out_ee', - '/out_pe', - '/tmp', - '/core/objects', // TODO: remove after gen import was refactored - ); - $aFileBlackList = array( - '/_cc.php', - '/_version_define.php', - '/core/oxerpbase.php', // TODO: remove after gen import was refactored - '/core/oxerpcsv.php', // TODO: remove after gen import was refactored - '/core/oxerpinterface.php', // TODO: remove after gen import was refactored - '/core/oxopenidhttpfetcher.php', //third party lib - '/core/oxopenidgenericconsumer.php', //third party lib - ); - $aFileWhiteList = array( - '/core/smarty/plugins/emos.php', - '/core/smarty/plugins/oxemosadapter.php', - '/core/smarty/plugins/modifier.oxmultilangassign.php', - '/core/smarty/plugins/modifier.oxnumberformat.php', - '/core/smarty/plugins/modifier.oxformdate.php', - '/core/smarty/plugins/insert.oxid_cmplogin.php', - '/core/smarty/plugins/insert.oxid_cssmanager.php', - '/core/smarty/plugins/insert.oxid_newbasketitem.php', - '/core/smarty/plugins/insert.oxid_nocache.php', - '/core/smarty/plugins/insert.oxid_tracker.php', - '/core/smarty/plugins/function.oxmultilang.php', - '/core/smarty/plugins/function.oxid_include_dynamic.php', - '/core/smarty/plugins/function.oxcontent.php', - '/core/smarty/plugins/block.oxhasrights.php', - ); - $arr = findphp($sBasePath, $aDirBlackList, $aFileBlackList, $aFileWhiteList); - - if ($_ENV['PHP_FILE']) { - $sTestOnlyFile = basename($_ENV['PHP_FILE']); - $sTestOnlyFile = preg_replace('/Test.php$/i', '', $sTestOnlyFile); - $sTestOnlyFile = preg_replace('/.php$/i', '', $sTestOnlyFile); - foreach ($arr as &$sSerchFile) { - if (stristr($sSerchFile, $sTestOnlyFile)) { - $sTestOnlyFile = $sSerchFile; - break; - } - } - - return array($sTestOnlyFile => stripCodeLines($arr[array_search($sTestOnlyFile, $arr)], $sCCarrayDir)); - } - - $ret = array(); - foreach ($arr as $file) { - try { - $ret[$file] = stripCodeLines($file, $sCCarrayDir); - } catch (Exception $e) { - // do not add file here; - echo '', $e->getMessage(), "\n"; - } - } - - return $ret; - } -} - -if (!function_exists('replaceDirSeperator')) { - function replaceDirSeperator($sDir) - { - if (DIRECTORY_SEPARATOR == '\\') { - return str_replace('/', '\\', $sDir); - } - - return $sDir; - } -} - -if (!function_exists('preparePathArray')) { - function preparePathArray(&$aPaths, $sBasePath) - { - foreach (array_keys($aPaths) as $key) { - $aPaths[$key] = $sBasePath . $aPaths[$key]; - } - $aPaths = array_map('replaceDirSeperator', $aPaths); - } -} - -if (!function_exists('findphp')) { - function findphp($baseDir, $aDirBlackList = array(), $aFileBlackList = array(), $aFileWhiteList = array()) - { - $baseDir = preg_replace('#/$#', '', $baseDir); - $baseDir = replaceDirSeperator($baseDir); - - $dirs = array($baseDir); - - preparePathArray($aDirBlackList, $baseDir); - preparePathArray($aFileBlackList, $baseDir); - preparePathArray($aFileWhiteList, $baseDir); - - - //get directorys (do not go to blacklist) - while (list ( , $dir ) = each($dirs)) { - foreach (glob($dir . DIRECTORY_SEPARATOR . '*', GLOB_ONLYDIR) as $sdir) { - if (array_search($sdir, $aDirBlackList) === false) { - $dirs[] = $sdir; - } - } - } - - // get PHP files form directorys - $aFiles = array(); - foreach ($dirs as $dir) { - $aFiles = array_merge($aFiles, glob($dir . DIRECTORY_SEPARATOR . "*.php", GLOB_NOSORT)); - } - - //remove files existing in file blacklist - foreach ($aFileBlackList as $sFile) { - $iNR = array_search($sFile, $aFiles); - if ($iNR !== false) { - unset($aFiles[$iNR]); - } - } - // add files from white list - foreach ($aFileWhiteList as $sFile) { - $aFiles[] = $sFile; - } - - return $aFiles; - } -} - -if (!function_exists('preg_stripper')) { - function preg_stripper($matches) - { - return preg_replace('/.*/', '', $matches[0]); - } -} - -if (!function_exists('stripCodeLines')) { - function stripCodeLines($sFile, $sCCarrayDir) - { - if (!file_exists($sFile)) { - throw new Exception("\n" . 'File "' . $sFile . '" does not exists, skipping'); - } - - - $sFileContentMD5 = md5_file($sFile); - $sCCFileName = $sCCarrayDir . md5($sFile) . "." . $sFileContentMD5; - // delete unneeded files - $aArray = glob($sCCarrayDir . md5($sFile) . ".*"); - $blFound = false; - if (count($aArray)) { - while ($aArray) { - $sF = array_pop($aArray); - if (!$blFound && $sF === $sCCFileName) { - $blFound = true; - } else { - unlink($sF); - } - } - } - if (!$blFound) { - $aFile = file_get_contents($sFile); - - $aFile = str_replace(' ', '', $aFile); - $aFile = str_replace("\t", '', $aFile); - $aFile = str_replace("\r", '', $aFile); - - $aFile = preg_replace('#//.*#', '', $aFile); - $aFile = preg_replace_callback('#/\*.*?\*/#sm', 'preg_stripper', $aFile); - - // for viariables - $aFile = preg_replace('#(public|static|protected|private|var|\{|\}).*;#', '', $aFile); - //for functions - $aFile = preg_replace('#(public|static|protected|private|var|\{|\})#', '', $aFile); - - $aFile = preg_replace('#^class.*?$#m', '', $aFile); - $aFile = preg_replace_callback('/\?>.*?<\?php/sm', 'preg_stripper', $aFile); - $aFile = preg_replace_callback('/\?>.*?<\?/sm', 'preg_stripper', $aFile); - $aFile = preg_replace_callback('/\.*?<\?php/sm', 'preg_stripper', $aFile); - $aFile = preg_replace_callback('/\.*?<\?/sm', 'preg_stripper', $aFile); - - $aFile = preg_replace_callback('/\?>.*/sm', 'preg_stripper', $aFile); - - $aFile = preg_replace('#^\$[a-zA-Z0-9_]+;$#m', '', $aFile); - - $aFile = preg_replace('#^function[a-zA-Z0-9_]+\(.*?\)\{?$#m', '', $aFile); - $aFile = preg_replace('#.+#', '1', $aFile); - - $aFile = preg_replace('#^$#m', '0', $aFile); - $aFile = str_replace("\n", '', $aFile); - $aCC = array(); - for ($i = 0; $i < strlen($aFile); $i++) { - if ($aFile[$i] === '1') { - $aCC[$i + 1] = -1; - } - } - file_put_contents($sCCFileName, serialize($aCC)); - - return $aCC; - } else { - return unserialize(file_get_contents($sCCFileName)); - } - } -} - - -class oxTestModuleLoader -{ - - protected static $_aChain = array(); - protected static $_blLoaded = false; - protected static $_blOriginal = true; - - /** - * Sets the original chain loading command - * - * @param boolean $blOriginal - */ - public static function useOriginalChain($blOriginal) - { - self::$_blOriginal = $blOriginal; - } - - /** - * Tries to initiate the module classes and includes required files from metadata - */ - public static function initFromMetadata() - { - $sPath = getenv('oxMETADATA'); - - // if metadata exists - if (file_exists($sPath)) { - include $sPath; - - // including all filles from ["files"] - if (isset($aModule["files"]) && count($aModule["files"])) { - foreach ($aModule["files"] as $sFilePath) { - require_once oxConfig::getInstance()->getConfigParam("sShopDir") . "/modules/" . $sFilePath; - } - } - - // adding and extending the module files - if (isset($aModule["extend"]) && count($aModule["extend"])) { - foreach ($aModule["extend"] as $sParent => $sPathToModule) { - $sClassName = basename($sPathToModule); - $sFakeParent = $sClassName . "_parent"; - if (!class_exists($sFakeParent)) { - eval("class $sFakeParent extends $sParent {}"); - } - require_once oxConfig::getInstance()->getConfigParam("sShopDir") . "/modules/" . $sPathToModule . ".php"; - } - - self::_appendToChain($aModule["extend"]); - } - } - } - - /** - * Loads the module from metadata file - * If no metadata found and the module chain is empty, then does nothing. - * - * On first load the data is saved and on consecutive calls the saved data is used - */ - public static function loadModule() - { - // if theres a chain already saved and is not empty - if (count(self::$_aChain)) { - \OxidEsales\Eshop\Core\Registry::getConfig()->setConfigParam("aModules", self::$_aChain); - \OxidEsales\Eshop\Core\Registry::get("oxUtilsObject")->setModuleVar("aDisabledModules", array()); - } - } - - /** - * Appends modules to the oxTestModuleLoader chain - * - * @param array $aChain array with the module chain - */ - public static function append(array $aChain) - { - self::_appendToChain($aChain); - } - - public static function _appendToChain($aExtend) - { - // if the chain is still empty and "original" chain is needed - if (self::$_blOriginal && !count(self::$_aChain)) { - self::$_aChain = (array) modConfig::getInstance()->getConfigParam("aModules"); - } - - // addping the "extend" chain to the main chain - foreach ($aExtend as $sParent => $sExtends) { - if (isset(self::$_aChain[$sParent])) { - $sExtends = trim(self::$_aChain[$sParent], "& ") . "&" - . trim($sExtends, "& "); - } - self::$_aChain[$sParent] = $sExtends; - } - } -} diff --git a/tests/unit/testdata/.gitkeep b/tests/unit/testdata/.gitkeep deleted file mode 100644 index e69de29b..00000000 From 6ea38a416c65c77169785d8615eb41f1fe028d47 Mon Sep 17 00:00:00 2001 From: Keywan Ghadami Date: Fri, 12 Feb 2021 17:52:05 +0100 Subject: [PATCH 4/5] fix ref to sql from new src subfolder --- composer.json | 2 +- src/Core/PasswordPolicyModule.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/composer.json b/composer.json index e9264f60..f94b42e9 100644 --- a/composer.json +++ b/composer.json @@ -9,7 +9,7 @@ }, "require-dev": { - } + }, "extra": { "oxideshop": { "target-directory": "oxps/passwordpolicy" diff --git a/src/Core/PasswordPolicyModule.php b/src/Core/PasswordPolicyModule.php index 12d47cd1..7de8a971 100644 --- a/src/Core/PasswordPolicyModule.php +++ b/src/Core/PasswordPolicyModule.php @@ -275,7 +275,7 @@ protected static function dbEvent($sSqlFile, $sFailureError = "Operation failed: // @codeCoverageIgnoreStart // Generated from developer tools, no need to test this try { - $sSqlDir = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'docs' . DIRECTORY_SEPARATOR . $sSqlFile; + $sSqlDir = dirname(__DIR__) . DIRECTORY_SEPARATOR . '../docs' . DIRECTORY_SEPARATOR . $sSqlFile; if (preg_match('/\.tpl$/', $sSqlFile)) { // If file extension is .tpl /** @var Smarty $oSmarty */ $oSmarty = Registry::get('oxUtilsView')->getSmarty(); From e3cfe85ed962b0810474818ad87a419711743824 Mon Sep 17 00:00:00 2001 From: Keywan Ghadami Date: Fri, 12 Feb 2021 18:02:30 +0100 Subject: [PATCH 5/5] fix composer.json --- composer.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/composer.json b/composer.json index f94b42e9..a82615f4 100644 --- a/composer.json +++ b/composer.json @@ -18,7 +18,7 @@ "autoload": { "psr-4": { "OxidProfessionalServices\\PasswordPolicy\\": "src", - "OxidProfessionalServices\\PasswordPolicy\\Tests": "tests" + "OxidProfessionalServices\\PasswordPolicy\\Tests\\": "tests" } } -}, +}