diff --git a/Bootstrap.php b/Bootstrap.php index f0b60c64..a4c3c3c1 100755 --- a/Bootstrap.php +++ b/Bootstrap.php @@ -1,241 +1,245 @@ . + * + * Bootstrap + * + * @category RatePAY + * @package RpayRatePAY + * @copyright Copyright (c) 2013 RatePAY GmbH (http://www.ratepay.com) + */ +require_once __DIR__ . '/Component/CSRFWhitelistAware.php'; + +class Shopware_Plugins_Frontend_RpayRatePay_Bootstrap extends Shopware_Components_Plugin_Bootstrap +{ + private $str; + + public static function getPaymentMethods() + { + return [ + 'rpayratepayinvoice', + 'rpayratepayrate', + 'rpayratepaydebit', + 'rpayratepayrate0', + ]; + } + /** - * This program is free software; you can redistribute it and/or modify it under the terms of - * the GNU General Public License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU General Public License for more details. + * Returns the Label of the Plugin * - * You should have received a copy of the GNU General Public License along with this program; - * if not, see . - * - * Bootstrap + * @return string + */ + public function getLabel() + { + return 'RatePay Payment'; + } + + public function afterInit() + { + $loader = $this->get('Loader'); + + //Plugin + $loader->registerNamespace('RpayRatePay', $this->Path() . '/'); + + //library + $loader->registerNamespace('RatePAY', $this->Path() . 'Component/Library/src/'); + } + + /** + * Returns the Plugin version * - * @category RatePAY - * @package RpayRatePAY - * @copyright Copyright (c) 2013 RatePAY GmbH (http://www.ratepay.com) + * @return string + * @throws Exception */ - require_once __DIR__ . '/Component/CSRFWhitelistAware.php'; + public function getVersion() + { + $info = json_decode(file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . 'plugin.json'), true); + if ($info) { + return $info['currentVersion']; + } else { + throw new Exception('The plugin has an invalid version file.'); + } + } - class Shopware_Plugins_Frontend_RpayRatePay_Bootstrap extends Shopware_Components_Plugin_Bootstrap + /** + * Returns the PaymentConfirm Config + * + * @return mixed + * @throws Exception + */ + public static function getPCConfig() { - public static function getPaymentMethods() { - return array( - 'rpayratepayinvoice', - 'rpayratepayrate', - 'rpayratepaydebit', - 'rpayratepayrate0', - ); + $info = json_decode(file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . 'plugin.json'), true); + if ($info) { + return $info['payment_confirm']; + } else { + throw new Exception('The plugin has an invalid version file.'); } + } - /** - * Returns the Label of the Plugin - * - * @return string - */ - public function getLabel() - { - return 'RatePay Payment'; + /** + * Returns all allowed actions + * + * @return array + */ + public function getCapabilities() + { + return [ + 'install' => true, + 'update' => true, + 'enable' => true + ]; + } + + /** + * Installs the Plugin and its components + * + * @return array + * @throws Exception + */ + public function install() + { + $this->subscribeEvent('Enlight_Controller_Front_StartDispatch', 'onRegisterSubscriber'); + $this->str = 'Shopware_Console_Add_Command'; + $this->subscribeEvent('' . $this->str . '', 'onRegisterSubscriber'); + + $queue = [ + new \RpayRatePay\Bootstrapping\PaymentsSetup($this), + new \RpayRatePay\Bootstrapping\FormsSetup($this), + new \RpayRatePay\Bootstrapping\TranslationsSetup($this), + new \RpayRatePay\Bootstrapping\MenuesSetup($this), + new \RpayRatePay\Bootstrapping\DatabaseSetup($this), + new \RpayRatePay\Bootstrapping\PaymentStatusesSetup($this), + new \RpayRatePay\Bootstrapping\DeliveryStatusesSetup($this), + new \RpayRatePay\Bootstrapping\CronjobSetup($this), + new \RpayRatePay\Bootstrapping\AdditionalOrderAttributeSetup($this), + ]; + + foreach ($queue as $bootstrapper) { + $bootstrapper->install(); } - public function afterInit() - { - $loader = $this->get('Loader'); + $this->Plugin()->setActive(true); - //Plugin - $loader->registerNamespace('RpayRatePay', $this->Path() . '/'); + return [ + 'success' => true, + 'invalidateCache' => ['frontend', 'backend'] + ]; + } - //library - $loader->registerNamespace('RatePAY', $this->Path() . 'Component/Library/src/'); + /** + * Updates the Plugin and its components + * + * @param string $version + * @return array|bool + * @throws exception + * @todo: implement translation update while updating + */ + public function update($version) + { + $queue = [ + new \RpayRatePay\Bootstrapping\FormsSetup($this), + new \RpayRatePay\Bootstrapping\DatabaseSetup($this), + new \RpayRatePay\Bootstrapping\TranslationsSetup($this), + new \RpayRatePay\Bootstrapping\PaymentsSetup($this), + new \RpayRatePay\Bootstrapping\ShopConfigSetup($this), + new \RpayRatePay\Bootstrapping\CronjobSetup($this), + new \RpayRatePay\Bootstrapping\AdditionalOrderAttributeSetup($this), + ]; + + $this->_dropOrderAdditionalAttributes(); + + foreach ($queue as $bootstrapper) { + $bootstrapper->update(); } - /** - * Returns the Plugin version - * - * @return string - * @throws Exception - */ - public function getVersion() - { - $info = json_decode(file_get_contents(__DIR__ . DIRECTORY_SEPARATOR .'plugin.json'), true); - if ($info) { - return $info['currentVersion']; - } else { - throw new Exception('The plugin has an invalid version file.'); - } - } + \RpayRatePay\Component\Service\Logger::singleton()->addNotice('Successful module update'); - /** - * Returns the PaymentConfirm Config - * - * @return mixed - * @throws Exception - */ - public static function getPCConfig() - { - $info = json_decode(file_get_contents(__DIR__ . DIRECTORY_SEPARATOR .'plugin.json'), true); - if ($info) { - return $info['payment_confirm']; - } else { - throw new Exception('The plugin has an invalid version file.'); - } - } + return [ + 'success' => true, + 'invalidateCache' => ['frontend', 'backend'] + ]; + } - /** - * Returns all allowed actions - * - * @return array - */ - public function getCapabilities() - { - return array( - 'install' => true, - 'update' => true, - 'enable' => true - ); - } + /** + * drops additional attributes for ratepay orders in s_order_attributes + */ + public function _dropOrderAdditionalAttributes() + { + $metaDataCache = Shopware()->Models()->getConfiguration()->getMetadataCacheImpl(); + $metaDataCache->deleteAll(); + Shopware()->Models()->generateAttributeModels( + ['s_order_attributes'] + ); + } - /** - * Installs the Plugin and its components - * - * @return array - * @throws Exception - */ - public function install() - { - $this->subscribeEvent('Enlight_Controller_Front_StartDispatch', 'onRegisterSubscriber'); - $this->subscribeEvent('Shopware_Console_Add_Command', 'onRegisterSubscriber'); - - $queue = [ - new \RpayRatePay\Bootstrapping\PaymentsSetup($this), - new \RpayRatePay\Bootstrapping\FormsSetup($this), - new \RpayRatePay\Bootstrapping\TranslationsSetup($this), - new \RpayRatePay\Bootstrapping\MenuesSetup($this), - new \RpayRatePay\Bootstrapping\DatabaseSetup($this), - new \RpayRatePay\Bootstrapping\PaymentStatusesSetup($this), - new \RpayRatePay\Bootstrapping\DeliveryStatusesSetup($this), - new \RpayRatePay\Bootstrapping\CronjobSetup($this), - new \RpayRatePay\Bootstrapping\AdditionalOrderAttributeSetup($this), - ]; - - foreach ($queue as $bootstrapper) { - $bootstrapper->install(); - } - - $this->Plugin()->setActive(true); - - return array( - 'success' => true, - 'invalidateCache' => array('frontend', 'backend') - ); - } + /** + * Uninstalls the Plugin and its components + * + * @return array|bool + * @throws Zend_Db_Adapter_Exception + */ + public function uninstall() + { + $queue = [ + new \RpayRatePay\Bootstrapping\DatabaseSetup($this), + ]; - /** - * Updates the Plugin and its components - * - * @param string $version - * @return array|bool - * @throws exception - * @todo: implement translation update while updating - */ - public function update($version) - { - $queue = [ - new \RpayRatePay\Bootstrapping\FormsSetup($this), - new \RpayRatePay\Bootstrapping\DatabaseSetup($this), - new \RpayRatePay\Bootstrapping\TranslationsSetup($this), - new \RpayRatePay\Bootstrapping\PaymentsSetup($this), - new \RpayRatePay\Bootstrapping\ShopConfigSetup($this), - new \RpayRatePay\Bootstrapping\CronjobSetup($this), - new \RpayRatePay\Bootstrapping\AdditionalOrderAttributeSetup($this), - ]; - - $this->_dropOrderAdditionalAttributes(); - - foreach ($queue as $bootstrapper) { - $bootstrapper->update(); - } - - Shopware()->PluginLogger()->addNotice('Successful module update'); - - return array( - 'success' => true, - 'invalidateCache' => array('frontend', 'backend') - ); - } + $this->disable(); - /** - * drops additional attributes for ratepay orders in s_order_attributes - */ - public function _dropOrderAdditionalAttributes() - { - $metaDataCache = Shopware()->Models()->getConfiguration()->getMetadataCacheImpl(); - $metaDataCache->deleteAll(); - Shopware()->Models()->generateAttributeModels( - array('s_order_attributes') - ); + foreach ($queue as $bootstrap) { + $bootstrap->uninstall(); } - /** - * Uninstalls the Plugin and its components - * - * @return array|bool - * @throws Zend_Db_Adapter_Exception - */ - public function uninstall() - { - $queue = [ - new \RpayRatePay\Bootstrapping\DatabaseSetup($this), - ]; - - $this->disable(); - - foreach ($queue as $bootstrap) { - $bootstrap->uninstall(); - } - - return parent::uninstall(); - } + return parent::uninstall(); + } - /** - * Deactivates the Plugin and its components - * - * @return bool - * @throws Zend_Db_Adapter_Exception - */ - public function disable() - { - $sql = "UPDATE `s_core_paymentmeans` SET `active` = 0 WHERE `name` LIKE 'rpayratepay%'"; + /** + * Deactivates the Plugin and its components + * + * @return bool + * @throws Zend_Db_Adapter_Exception + */ + public function disable() + { + $sql = "UPDATE `s_core_paymentmeans` SET `active` = 0 WHERE `name` LIKE 'rpayratepay%'"; - Shopware()->Db()->query($sql); + Shopware()->Db()->query($sql); - return true; - } + return true; + } - public function onRegisterSubscriber() - { - $subscribers = [ - new \RpayRatePay\Bootstrapping\Events\OrderOperationsSubscriber(), - new \RpayRatePay\Bootstrapping\Events\TemplateExtensionSubscriber($this->Path()), - new \RpayRatePay\Bootstrapping\Events\PaymentControllerSubscriber($this->Path()), - new \RpayRatePay\Bootstrapping\Events\LoggingControllerSubscriber($this->Path()), - new \RpayRatePay\Bootstrapping\Events\OrderDetailControllerSubscriber($this->Path()), - new \RpayRatePay\Bootstrapping\Events\CheckoutValidationSubscriber($this->Path()), - new \RpayRatePay\Bootstrapping\Events\PaymentFilterSubscriber(), - new \RpayRatePay\Bootstrapping\Events\PluginConfigurationSubscriber($this->getName()), - new \RpayRatePay\Bootstrapping\Events\OrderDetailsProcessSubscriber(), - new \RpayRatePay\Bootstrapping\Events\JavascriptSourceSubscriber($this->Path()), - new \RpayRatePay\Bootstrapping\Events\OrderViewExtensionSubscriber($this->Path()), - new \RpayRatePay\Bootstrapping\Events\UpdateTransactionsSubscriber(), - new \RpayRatePay\Bootstrapping\Events\BackendOrderControllerSubscriber($this->Path()), - new \RpayRatePay\Bootstrapping\Events\BackendOrderViewExtensionSubscriber($this->Path()), - ]; - - foreach ($subscribers as $subscriber) { - Shopware()->Events()->addSubscriber($subscriber); - } + public function onRegisterSubscriber() + { + $subscribers = [ + new \RpayRatePay\Bootstrapping\Events\OrderOperationsSubscriber(), + new \RpayRatePay\Bootstrapping\Events\TemplateExtensionSubscriber($this->Path()), + new \RpayRatePay\Bootstrapping\Events\PaymentControllerSubscriber($this->Path()), + new \RpayRatePay\Bootstrapping\Events\LoggingControllerSubscriber($this->Path()), + new \RpayRatePay\Bootstrapping\Events\OrderDetailControllerSubscriber($this->Path()), + new \RpayRatePay\Bootstrapping\Events\CheckoutValidationSubscriber($this->Path()), + new \RpayRatePay\Bootstrapping\Events\PaymentFilterSubscriber(), + new \RpayRatePay\Bootstrapping\Events\PluginConfigurationSubscriber($this->getName()), + new \RpayRatePay\Bootstrapping\Events\OrderDetailsProcessSubscriber(), + new \RpayRatePay\Bootstrapping\Events\JavascriptSourceSubscriber($this->Path()), + new \RpayRatePay\Bootstrapping\Events\OrderViewExtensionSubscriber($this->Path()), + new \RpayRatePay\Bootstrapping\Events\UpdateTransactionsSubscriber(), + new \RpayRatePay\Bootstrapping\Events\BackendOrderControllerSubscriber($this->Path()), + new \RpayRatePay\Bootstrapping\Events\BackendOrderViewExtensionSubscriber($this->Path()), + ]; + + foreach ($subscribers as $subscriber) { + Shopware()->Events()->addSubscriber($subscriber); } } +} diff --git a/Bootstrapping/AdditionalOrderAttributeSetup.php b/Bootstrapping/AdditionalOrderAttributeSetup.php index 329d8e92..083649b2 100644 --- a/Bootstrapping/AdditionalOrderAttributeSetup.php +++ b/Bootstrapping/AdditionalOrderAttributeSetup.php @@ -1,13 +1,6 @@ Config()->version); $configured = array_map('intval', $sConfigured); - - for ($i=0; $i<3; $i++) { - if ($expected[$i] < $configured[$i]) + for ($i = 0; $i < 3; $i++) { + if ($expected[$i] < $configured[$i]) { return true; + } - if ($expected[$i] > $configured[$i]) + if ($expected[$i] > $configured[$i]) { return false; + } } return true; } -} \ No newline at end of file +} diff --git a/Bootstrapping/Bootstrapper.php b/Bootstrapping/Bootstrapper.php index 0fd6ef47..2b4b1114 100644 --- a/Bootstrapping/Bootstrapper.php +++ b/Bootstrapping/Bootstrapper.php @@ -1,10 +1,5 @@ Db()->query('DELETE FROM s_crontab WHERE `action` = ?', [self::UPDATE_TRANSACTIONS_ACTION]); } -} \ No newline at end of file +} diff --git a/Bootstrapping/Database/CreateConfigInstallmentTable.php b/Bootstrapping/Database/CreateConfigInstallmentTable.php index 1bec6009..9f76dad8 100644 --- a/Bootstrapping/Database/CreateConfigInstallmentTable.php +++ b/Bootstrapping/Database/CreateConfigInstallmentTable.php @@ -1,35 +1,29 @@ query("DROP TABLE IF EXISTS `rpay_ratepay_config_installment`"); + $database->query('DROP TABLE IF EXISTS `rpay_ratepay_config_installment`'); $database->query($this->getQuery()); } -} \ No newline at end of file +} diff --git a/Bootstrapping/Database/CreateConfigPaymentTable.php b/Bootstrapping/Database/CreateConfigPaymentTable.php index 5dbad6cb..9f830995 100644 --- a/Bootstrapping/Database/CreateConfigPaymentTable.php +++ b/Bootstrapping/Database/CreateConfigPaymentTable.php @@ -1,10 +1,5 @@ query("DROP TABLE IF EXISTS `rpay_ratepay_config_payment`"); + $database->query('DROP TABLE IF EXISTS `rpay_ratepay_config_payment`'); $database->query($this->getQuery()); } -} \ No newline at end of file +} diff --git a/Bootstrapping/Database/CreateConfigTable.php b/Bootstrapping/Database/CreateConfigTable.php index 9059e820..8c662a79 100644 --- a/Bootstrapping/Database/CreateConfigTable.php +++ b/Bootstrapping/Database/CreateConfigTable.php @@ -1,13 +1,8 @@ RatePAY-Datenschutzerklärung', " . - "`sandbox` int(1) NOT NULL, " . - "PRIMARY KEY (`shopId`, `country`)" . - ") ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci"; + '`sandbox` int(1) NOT NULL, ' . + 'PRIMARY KEY (`shopId`, `country`)' . + ') ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci'; return $query; } - /** * @param Enlight_Components_Db_Adapter_Pdo_Mysql $database * @throws Zend_Db_Adapter_Exception @@ -46,14 +40,14 @@ public function __invoke($database) { $database->query($this->getQuery()); - $hasColumnBackend = Util::tableHasColumn('rpay_ratepay_config', 'backend'); + $hasColumnBackend = ShopwareUtil::tableHasColumn('rpay_ratepay_config', 'backend'); if (!$hasColumnBackend) { - $sql = "ALTER TABLE rpay_ratepay_config ADD COLUMN backend int(1) NOT NULL"; + $sql = 'ALTER TABLE rpay_ratepay_config ADD COLUMN backend int(1) NOT NULL'; $database->query($sql); } - $sql = "ALTER TABLE rpay_ratepay_config DROP PRIMARY KEY, ADD PRIMARY KEY (shopId, country, backend);"; + $sql = 'ALTER TABLE rpay_ratepay_config DROP PRIMARY KEY, ADD PRIMARY KEY (shopId, country, backend);'; $database->query($sql); } -} \ No newline at end of file +} diff --git a/Bootstrapping/Database/CreateLoggingTable.php b/Bootstrapping/Database/CreateLoggingTable.php index 4170727a..dcbac64c 100644 --- a/Bootstrapping/Database/CreateLoggingTable.php +++ b/Bootstrapping/Database/CreateLoggingTable.php @@ -1,10 +1,5 @@ query($this->getQuery()); } -} \ No newline at end of file +} diff --git a/Bootstrapping/Database/CreateOrderHistoryTable.php b/Bootstrapping/Database/CreateOrderHistoryTable.php index 8d11ea85..f601c77a 100644 --- a/Bootstrapping/Database/CreateOrderHistoryTable.php +++ b/Bootstrapping/Database/CreateOrderHistoryTable.php @@ -1,34 +1,28 @@ query($this->getQuery()); } -} \ No newline at end of file +} diff --git a/Bootstrapping/Database/CreateOrderPositionsTable.php b/Bootstrapping/Database/CreateOrderPositionsTable.php index 29549939..3b484013 100644 --- a/Bootstrapping/Database/CreateOrderPositionsTable.php +++ b/Bootstrapping/Database/CreateOrderPositionsTable.php @@ -1,10 +1,5 @@ query($this->getQuery()); } -} \ No newline at end of file +} diff --git a/Bootstrapping/Database/CreateOrderShippingTable.php b/Bootstrapping/Database/CreateOrderShippingTable.php index f725692f..af703212 100644 --- a/Bootstrapping/Database/CreateOrderShippingTable.php +++ b/Bootstrapping/Database/CreateOrderShippingTable.php @@ -1,10 +1,5 @@ query($this->getQuery()); } -} \ No newline at end of file +} diff --git a/Bootstrapping/DatabaseSetup.php b/Bootstrapping/DatabaseSetup.php index 2cbf0708..c6192c8b 100644 --- a/Bootstrapping/DatabaseSetup.php +++ b/Bootstrapping/DatabaseSetup.php @@ -1,14 +1,8 @@ createDatabaseTables(); } @@ -24,7 +19,8 @@ public function install() { * @return mixed|void * @throws Exception */ - public function update() { + public function update() + { $this->updateConfigurationTables(); $this->removeSandboxColumns(); } @@ -101,7 +97,7 @@ private function updateConfigurationTables() private function removeSandboxColumns() { - if (Util::tableHasColumn('s_core_config_elements', 'RatePaySandboxDE')) { + if (ShopwareUtil::tableHasColumn('s_core_config_elements', 'RatePaySandboxDE')) { try { Shopware()->Db()->query( "DELETE FROM `s_core_config_elements` WHERE `s_core_config_elements`.`name` LIKE 'RatePaySandbox%'" @@ -111,4 +107,4 @@ private function removeSandboxColumns() } } } -} \ No newline at end of file +} diff --git a/Bootstrapping/DeliveryStatusesSetup.php b/Bootstrapping/DeliveryStatusesSetup.php index 72b2f897..6d0fdeb8 100644 --- a/Bootstrapping/DeliveryStatusesSetup.php +++ b/Bootstrapping/DeliveryStatusesSetup.php @@ -1,34 +1,30 @@ Db()->query($sql, array( + Shopware()->Db()->query($sql, [ 255, 'Teil-(Retoure)', 255, 'state', 0 - )); + ]); } catch (\Exception $exception) { - Shopware()->Pluginlogger()->addNotice($exception->getMessage()); + Logger::singleton()->addNotice($exception->getMessage()); } try { - Shopware()->Db()->query($sql, array( + Shopware()->Db()->query($sql, [ 265, 'Teil-(Storno)', 265, 'state', 0 - )); + ]); } catch (\Exception $exception) { - Shopware()->Pluginlogger()->addNotice($exception->getMessage()); + Logger::singleton()->addNotice($exception->getMessage()); } } @@ -36,10 +32,14 @@ public function install() { * @return mixed|void * @throws Exception */ - public function update() {} + public function update() + { + } /** * @return mixed|void */ - public function uninstall() {} -} \ No newline at end of file + public function uninstall() + { + } +} diff --git a/Bootstrapping/Events/BackendOrderControllerSubscriber.php b/Bootstrapping/Events/BackendOrderControllerSubscriber.php index f607b257..4cf23aae 100644 --- a/Bootstrapping/Events/BackendOrderControllerSubscriber.php +++ b/Bootstrapping/Events/BackendOrderControllerSubscriber.php @@ -1,17 +1,11 @@ Template()->addTemplateDir($this->path . 'Views/'); - return $this->path . "Controller/backend/RpayRatepayBackendOrder.php"; + return $this->path . 'Controller/backend/RpayRatepayBackendOrder.php'; } public function beforeCreateOrderAction(\Enlight_Hook_HookArgs $hookArgs) @@ -72,14 +66,14 @@ public function beforeCreateOrderAction(\Enlight_Hook_HookArgs $hookArgs) $swagValidations = $this->runSwagValidations($orderStruct); - if($swagValidations->getMessages()) { + if ($swagValidations->getMessages()) { $this->fail($view, $swagValidations->getMessages()); return; } $paymentRequestData = $this->orderStructToPaymentRequestData($orderStruct, $paymentType, $customer); - $netItemPrices = \Shopware_Plugins_Frontend_RpayRatePay_Component_Service_Util::customerCreatesNetOrders($customer); + $netItemPrices = \RpayRatePay\Component\Service\ShopwareUtil::customerCreatesNetOrders($customer); $paymentRequester = new \Shopware_Plugins_Frontend_RpayRatePay_Component_Mapper_ModelFactory(null, true, $netItemPrices); $answer = $paymentRequester->callPaymentRequest($paymentRequestData); @@ -88,28 +82,27 @@ public function beforeCreateOrderAction(\Enlight_Hook_HookArgs $hookArgs) //let SWAG write order to db $this->forwardToSWAGBackendOrders($hookArgs); - $orderId = $view->getAssign("orderId"); + $orderId = $view->getAssign('orderId'); $this->doPostProcessing($orderId, $answer, $paymentRequestData); - } else { $customerMessage = $answer->getCustomerMessage(); $this->fail($view, [$customerMessage]); } - - } catch(\Exception $e) { - Shopware()->Pluginlogger()->error($e->getMessage()); - Shopware()->Pluginlogger()->error($e->getTraceAsString()); + } catch (\Exception $e) { + Logger::singleton()->error($e->getMessage()); + Logger::singleton()->error($e->getTraceAsString()); $this->fail($view, [$e->getMessage()]); } } - private function orderStructToPaymentRequestData(\SwagBackendOrder\Components\Order\Struct\OrderStruct $orderStruct, + private function orderStructToPaymentRequestData( + \SwagBackendOrder\Components\Order\Struct\OrderStruct $orderStruct, \Shopware\Models\Payment\Payment $paymentType, - \Shopware\Models\Customer\Customer $customer) - { - $method = \Shopware_Plugins_Frontend_RpayRatePay_Component_Service_Util::getPaymentMethod( + \Shopware\Models\Customer\Customer $customer + ) { + $method = \RpayRatePay\Component\Service\ShopwareUtil::getPaymentMethod( $paymentType->getName() ); @@ -118,11 +111,11 @@ private function orderStructToPaymentRequestData(\SwagBackendOrder\Components\Or $shipping = Shopware()->Models()->find('Shopware\Models\Customer\Address', $orderStruct->getShippingAddressId()); $items = []; - foreach($orderStruct->getPositions() as $positionStruct) { + foreach ($orderStruct->getPositions() as $positionStruct) { $items[] = $this->positionStructToArray($positionStruct); } - $shippingTax = Math::taxFromPrices( + $shippingTax = Math::taxFromPrices( $orderStruct->getShippingCostsNet(), $orderStruct->getShippingCosts() ); @@ -135,7 +128,7 @@ private function orderStructToPaymentRequestData(\SwagBackendOrder\Components\Or $dfpToken = ''; $shop = Shopware()->Models()->find('Shopware\Models\Shop\Shop', $orderStruct->getLanguageShopId()); - $localeLang = $shop->getLocale()->getLocale(); + $localeLang = $shop->getLocale()->getLocale(); $lang = substr($localeLang, 0, 2); $amount = $orderStruct->getTotal(); @@ -176,9 +169,9 @@ private function fail($view, $messages) private function runSwagValidations($orderStruct) { - $validator = Shopware()->Container()->get('swag_backend_order.order.order_validator'); - $violations = $validator ->validate($orderStruct); - return $violations; + $validator = Shopware()->Container()->get('swag_backend_order.order.order_validator'); + $violations = $validator->validate($orderStruct); + return $violations; } private function doPostProcessing($orderId, $answer, $paymentRequestData) @@ -196,7 +189,8 @@ private function doPostProcessing($orderId, $answer, $paymentRequestData) } //set order attributes - $paymentProcessor->setOrderAttributes($order, + $paymentProcessor->setOrderAttributes( + $order, $answer, Shopware()->Plugins()->Frontend()->RpayRatePay()->Config()->get('RatePayUseFallbackShippingItem'), true @@ -213,4 +207,4 @@ private function doPostProcessing($orderId, $answer, $paymentRequestData) $paymentProcessor->sendPaymentConfirm($answer->getTransactionId(), $order, true); } } -} \ No newline at end of file +} diff --git a/Bootstrapping/Events/BackendOrderViewExtensionSubscriber.php b/Bootstrapping/Events/BackendOrderViewExtensionSubscriber.php index f9cd7026..bb707473 100644 --- a/Bootstrapping/Events/BackendOrderViewExtensionSubscriber.php +++ b/Bootstrapping/Events/BackendOrderViewExtensionSubscriber.php @@ -1,10 +1,5 @@ getSubject()->Request(); + $request = $arguments->getSubject()->Request(); $response = $arguments->getSubject()->Response(); - $view = $arguments->getSubject()->View(); + $view = $arguments->getSubject()->View(); if (!$request->isDispatched() || $response->isException() @@ -55,13 +52,13 @@ public function preValidation(\Enlight_Event_EventArgs $arguments) $userId = Shopware()->Session()->sUserId; if (empty($userId)) { - Shopware()->Pluginlogger()->warning('RatePAY: sUserId is empty'); + Logger::singleton()->warning('RatePAY: sUserId is empty'); return; } Shopware()->Template()->addTemplateDir($this->path . 'Views/'); $user = Shopware()->Models()->find('Shopware\Models\Customer\Customer', $userId); - $paymentType = Shopware()->Models()->find('Shopware\Models\Payment\Payment', $user->getPaymentId()); + $paymentType = Shopware()->Models()->find('Shopware\Models\Payment\Payment', $user->getPaymentId()); $validation = new \Shopware_Plugins_Frontend_RpayRatePay_Component_Validation($user, $paymentType); @@ -69,13 +66,13 @@ public function preValidation(\Enlight_Event_EventArgs $arguments) $view->sRegisterFinished = 'false'; $view->ratepayValidateCompanyName = $validation->isCompanyNameSet() ? 'true' : 'false'; - Shopware()->Pluginlogger()->info('RatePAY: isCompanyNameSet->' . $view->ratepayValidateCompanyName); + Logger::singleton()->info('RatePAY: isCompanyNameSet->' . $view->ratepayValidateCompanyName); $view->ratepayValidateIsB2B = $validation->isCompanyNameSet() ? 'true' : 'false'; - Shopware()->Pluginlogger()->info('RatePAY: isB2B->' . $view->ratepayValidateIsB2B); + Logger::singleton()->info('RatePAY: isB2B->' . $view->ratepayValidateIsB2B); $view->ratepayIsBillingAddressSameLikeShippingAddress = $validation->isBillingAddressSameLikeShippingAddress() ? 'true' : 'false'; - Shopware()->Pluginlogger()->info('RatePAY: isBillingAddressSameLikeShippingAddress->' . $view->ratepayIsBillingAddressSameLikeShippingAddress); + Logger::singleton()->info('RatePAY: isBillingAddressSameLikeShippingAddress->' . $view->ratepayIsBillingAddressSameLikeShippingAddress); if ($view->ratepayValidateIsB2B === false) { $view->ratepayValidateIsBirthdayValid = $validation->isBirthdayValid(); @@ -88,4 +85,4 @@ public function preValidation(\Enlight_Event_EventArgs $arguments) $view->errorRatenrechner = (!Shopware()->Session()->RatePAY['errorRatenrechner']) ? 'false' : Shopware()->Session()->RatePAY['errorRatenrechner']; } } -} \ No newline at end of file +} diff --git a/Bootstrapping/Events/JavascriptSourceSubscriber.php b/Bootstrapping/Events/JavascriptSourceSubscriber.php index 61ec7926..1b1c585a 100644 --- a/Bootstrapping/Events/JavascriptSourceSubscriber.php +++ b/Bootstrapping/Events/JavascriptSourceSubscriber.php @@ -1,10 +1,5 @@ path . 'Views/responsive/frontend/_public/src/javascripts/jquery.ratepay_checkout.js' - ); + ]; return new \Doctrine\Common\Collections\ArrayCollection($jsPath); } -} \ No newline at end of file +} diff --git a/Bootstrapping/Events/LoggingControllerSubscriber.php b/Bootstrapping/Events/LoggingControllerSubscriber.php index 364c1b3b..f526cc02 100644 --- a/Bootstrapping/Events/LoggingControllerSubscriber.php +++ b/Bootstrapping/Events/LoggingControllerSubscriber.php @@ -1,10 +1,5 @@ Template()->addTemplateDir($this->path. 'Views/'); + Shopware()->Template()->addTemplateDir($this->path . 'Views/'); - return $this->path . "Controller/backend/RpayRatepayLogging.php"; + return $this->path . 'Controller/backend/RpayRatepayLogging.php'; } -} \ No newline at end of file +} diff --git a/Bootstrapping/Events/OrderDetailControllerSubscriber.php b/Bootstrapping/Events/OrderDetailControllerSubscriber.php index cc7ac27c..d291eeaf 100644 --- a/Bootstrapping/Events/OrderDetailControllerSubscriber.php +++ b/Bootstrapping/Events/OrderDetailControllerSubscriber.php @@ -1,10 +1,5 @@ Template()->addTemplateDir($this->path . 'Views/'); - return $this->path . "Controller/backend/RpayRatepayOrderDetail.php"; + return $this->path . 'Controller/backend/RpayRatepayOrderDetail.php'; } -} \ No newline at end of file +} diff --git a/Bootstrapping/Events/OrderDetailsProcessSubscriber.php b/Bootstrapping/Events/OrderDetailsProcessSubscriber.php index 09f9d428..640b57d2 100644 --- a/Bootstrapping/Events/OrderDetailsProcessSubscriber.php +++ b/Bootstrapping/Events/OrderDetailsProcessSubscriber.php @@ -1,12 +1,9 @@ Db()->fetchOne($isRatePAYpaymentSQL, array($orderNumber))); + $isRatepayPayment = (1 <= Shopware()->Db()->fetchOne($isRatePAYpaymentSQL, [$orderNumber])); } catch (\Exception $exception) { - Shopware()->Pluginlogger()->error($exception->getMessage()); + Logger::singleton()->error($exception->getMessage()); } return (bool) $isRatepayPayment; } -} \ No newline at end of file +} diff --git a/Bootstrapping/Events/OrderOperationsSubscriber.php b/Bootstrapping/Events/OrderOperationsSubscriber.php index 529f82b6..1b0bdc11 100644 --- a/Bootstrapping/Events/OrderOperationsSubscriber.php +++ b/Bootstrapping/Events/OrderOperationsSubscriber.php @@ -1,12 +1,9 @@ getPayment()->getName(), $paymentMethods) && in_array($newPaymentMethod->getName(), $paymentMethods)) || (in_array($order->getPayment()->getName(), $paymentMethods) && $newPaymentMethod->getName() != $order->getPayment()->getName()) ) { - Shopware()->Pluginlogger()->addNotice('Bestellungen können nicht nachträglich auf RatePay Zahlungsmethoden geändert werden und RatePay Bestellungen können nicht nachträglich auf andere Zahlungsarten geändert werden.'); + Logger::singleton()->addNotice('Bestellungen können nicht nachträglich auf RatePay Zahlungsmethoden geändert werden und RatePay Bestellungen können nicht nachträglich auf andere Zahlungsarten geändert werden.'); $arguments->stop(); throw new Exception('Bestellungen können nicht nachträglich auf RatePay Zahlungsmethoden geändert werden und RatePay Bestellungen können nicht nachträglich auf andere Zahlungsarten geändert werden.'); } @@ -115,7 +112,6 @@ public function afterOrderBatchProcess(\Enlight_Hook_HookArgs $arguments) } } - /** * Stops Order deletion, when its not permitted * @@ -132,7 +128,7 @@ public function beforeDeleteOrderPosition(\Enlight_Hook_HookArgs $arguments) $order = Shopware()->Models()->find('Shopware\Models\Order\Order', $parameter['orderID']); $paymentMethods = \Shopware_Plugins_Frontend_RpayRatePay_Bootstrap::getPaymentMethods(); if ($parameter['valid'] != true && in_array($order->getPayment()->getName(), $paymentMethods)) { - Shopware()->Pluginlogger()->warning('Positionen einer RatePAY-Bestellung können nicht gelöscht werden. Bitte Stornieren Sie die Artikel in der Artikelverwaltung.'); + Logger::singleton()->warning('Positionen einer RatePAY-Bestellung können nicht gelöscht werden. Bitte Stornieren Sie die Artikel in der Artikelverwaltung.'); $arguments->stop(); } @@ -156,23 +152,22 @@ public function beforeDeleteOrder(\Enlight_Hook_HookArgs $arguments) if (!in_array($parameter['payment'][0]['name'], $paymentMethods)) { return false; } - $sql = "SELECT COUNT(*) FROM `s_order_details` AS `detail` " - . "INNER JOIN `rpay_ratepay_order_positions` AS `position` " - . "ON `position`.`s_order_details_id` = `detail`.`id` " - . "WHERE `detail`.`orderID`=? AND " - . "(`position`.`delivered` > 0 OR `position`.`cancelled` > 0 OR `position`.`returned` > 0)"; - $count = Shopware()->Db()->fetchOne($sql, array($parameter['id'])); + $sql = 'SELECT COUNT(*) FROM `s_order_details` AS `detail` ' + . 'INNER JOIN `rpay_ratepay_order_positions` AS `position` ' + . 'ON `position`.`s_order_details_id` = `detail`.`id` ' + . 'WHERE `detail`.`orderID`=? AND ' + . '(`position`.`delivered` > 0 OR `position`.`cancelled` > 0 OR `position`.`returned` > 0)'; + $count = Shopware()->Db()->fetchOne($sql, [$parameter['id']]); if ($count > 0) { - Shopware()->Pluginlogger()->warning('RatePAY-Bestellung können nicht gelöscht werden, wenn sie bereits bearbeitet worden sind.'); + Logger::singleton()->warning('RatePAY-Bestellung können nicht gelöscht werden, wenn sie bereits bearbeitet worden sind.'); $arguments->stop(); - } - else { + } else { $order = Shopware()->Models()->find('Shopware\Models\Order\Order', $parameter['id']); - $sqlShipping = "SELECT invoice_shipping FROM s_order WHERE id = ?"; - $shippingCosts = Shopware()->Db()->fetchOne($sqlShipping, array($parameter['id'])); + $sqlShipping = 'SELECT invoice_shipping FROM s_order WHERE id = ?'; + $shippingCosts = Shopware()->Db()->fetchOne($sqlShipping, [$parameter['id']]); - $items = array(); + $items = []; $i = 0; foreach ($order->getDetails() as $item) { $items[$i]['articlename'] = $item->getArticlename(); @@ -205,7 +200,7 @@ public function beforeDeleteOrder(\Enlight_Hook_HookArgs $arguments) $result = $modelFactory->callRequest('PaymentChange', $operationData); if ($result !== true) { - Shopware()->Pluginlogger()->warning('Bestellung könnte nicht gelöscht werden, da die Stornierung bei RatePAY fehlgeschlagen ist.'); + Logger::singleton()->warning('Bestellung könnte nicht gelöscht werden, da die Stornierung bei RatePAY fehlgeschlagen ist.'); $arguments->stop(); } } @@ -222,4 +217,4 @@ public function usesBidirectionalUpdates($paymentName) return $config->get('RatePayBidirectional') && in_array($paymentName, $paymentMethods); } -} \ No newline at end of file +} diff --git a/Bootstrapping/Events/OrderViewExtensionSubscriber.php b/Bootstrapping/Events/OrderViewExtensionSubscriber.php index 6b1ed4e4..e70bccd2 100644 --- a/Bootstrapping/Events/OrderViewExtensionSubscriber.php +++ b/Bootstrapping/Events/OrderViewExtensionSubscriber.php @@ -1,10 +1,5 @@ Template()->addTemplateDir($this->path . 'Views/responsive', 'rpay'); } -} \ No newline at end of file +} diff --git a/Bootstrapping/Events/PaymentFilterSubscriber.php b/Bootstrapping/Events/PaymentFilterSubscriber.php index 80364495..7bddf3c3 100644 --- a/Bootstrapping/Events/PaymentFilterSubscriber.php +++ b/Bootstrapping/Events/PaymentFilterSubscriber.php @@ -1,16 +1,11 @@ Session()->checkoutBillingAddressId > 0) { // From Shopware 5.2 find current address information in default billing address $addressModel = Shopware()->Models()->getRepository('Shopware\Models\Customer\Address'); - $customerAddressBilling = $addressModel->findOneBy(array('id' => Shopware()->Session()->checkoutBillingAddressId)); + $customerAddressBilling = $addressModel->findOneBy(['id' => Shopware()->Session()->checkoutBillingAddressId]); $countryBilling = $customerAddressBilling->getCountry(); if (Shopware()->Session()->checkoutShippingAddressId > 0 && Shopware()->Session()->checkoutShippingAddressId != Shopware()->Session()->checkoutBillingAddressId) { - $customerAddressShipping = $addressModel->findOneBy(array('id' => Shopware()->Session()->checkoutShippingAddressId)); + $customerAddressShipping = $addressModel->findOneBy(['id' => Shopware()->Session()->checkoutShippingAddressId]); $countryDelivery = $customerAddressShipping->getCountry(); } else { $countryDelivery = $countryBilling; } } else { - $countryBilling = $wrappedUser->getBillingCountry(); $countryDelivery = $wrappedUser->getShippingCountry(); @@ -81,7 +75,7 @@ public function filterPayments(\Enlight_Event_EventArgs $arguments) $backend = false; $config = $this->getRatePayPluginConfigByCountry($shopId, $countryBilling, $backend); - foreach ($config AS $payment => $data) { + foreach ($config as $payment => $data) { $show[$payment] = $data['status'] == 2 ? true : false; $validation = $this->getValidator($user); @@ -121,10 +115,10 @@ public function filterPayments(\Enlight_Event_EventArgs $arguments) $basket = Shopware()->Modules()->Basket()->sGetAmount(); $basket = $basket['totalAmount']; //is this always brutto? - Shopware()->Pluginlogger()->info('BasketAmount: ' . $basket); + Logger::singleton()->info('BasketAmount: ' . $basket); $isB2b = $validation->isCompanyNameSet(); - if (!ValidationService::areAmountsValid($isB2b,$data, $basket)) { + if (!ValidationService::areAmountsValid($isB2b, $data, $basket)) { $show[$payment] = false; continue; } @@ -134,26 +128,26 @@ public function filterPayments(\Enlight_Event_EventArgs $arguments) $paymentModel = Shopware()->Models()->find('Shopware\Models\Payment\Payment', $user->getPaymentId()); $setToDefaultPayment = false; - $payments = array(); + $payments = []; foreach ($return as $payment) { if ($payment['name'] === 'rpayratepayinvoice' && !$show['invoice']) { - Shopware()->Pluginlogger()->info('RatePAY: Filter RatePAY-Invoice'); - $setToDefaultPayment = $paymentModel->getName() === "rpayratepayinvoice" ? : $setToDefaultPayment; + Logger::singleton()->info('RatePAY: Filter RatePAY-Invoice'); + $setToDefaultPayment = $paymentModel->getName() === 'rpayratepayinvoice' ?: $setToDefaultPayment; continue; } if ($payment['name'] === 'rpayratepaydebit' && !$show['debit']) { - Shopware()->Pluginlogger()->info('RatePAY: Filter RatePAY-Debit'); - $setToDefaultPayment = $paymentModel->getName() === "rpayratepaydebit" ? : $setToDefaultPayment; + Logger::singleton()->info('RatePAY: Filter RatePAY-Debit'); + $setToDefaultPayment = $paymentModel->getName() === 'rpayratepaydebit' ?: $setToDefaultPayment; continue; } if ($payment['name'] === 'rpayratepayrate' && !$show['installment']) { - Shopware()->Pluginlogger()->info('RatePAY: Filter RatePAY-Rate'); - $setToDefaultPayment = $paymentModel->getName() === "rpayratepayrate" ? : $setToDefaultPayment; + Logger::singleton()->info('RatePAY: Filter RatePAY-Rate'); + $setToDefaultPayment = $paymentModel->getName() === 'rpayratepayrate' ?: $setToDefaultPayment; continue; } if ($payment['name'] === 'rpayratepayrate0' && !$show['installment0']) { - Shopware()->Pluginlogger()->info('RatePAY: Filter RatePAY-Rate0'); - $setToDefaultPayment = $paymentModel->getName() === "rpayratepayrate0" ? : $setToDefaultPayment; + Logger::singleton()->info('RatePAY: Filter RatePAY-Rate0'); + $setToDefaultPayment = $paymentModel->getName() === 'rpayratepayrate0' ?: $setToDefaultPayment; continue; } $payments[] = $payment; @@ -174,7 +168,6 @@ private function getValidator($user) return new \Shopware_Plugins_Frontend_RpayRatePay_Component_Validation($user); } - /** * Get ratepay plugin config from rpay_ratepay_config table * @@ -183,14 +176,14 @@ private function getValidator($user) * @param bool $backend * @return array */ - private function getRatePayPluginConfigByCountry($shopId, $country, $backend = false) { - + private function getRatePayPluginConfigByCountry($shopId, $country, $backend = false) + { $configLoader = new ConfigLoader(Shopware()->Db()); - $payments = array("installment", "invoice", "debit", "installment0"); - $paymentConfig = array(); + $payments = ['installment', 'invoice', 'debit', 'installment0']; + $paymentConfig = []; - foreach ($payments AS $payment) { + foreach ($payments as $payment) { $result = $configLoader->getPluginConfigForPaymentType($shopId, $country->getIso(), $payment, $backend); if (!empty($result)) { @@ -200,4 +193,4 @@ private function getRatePayPluginConfigByCountry($shopId, $country, $backend = f return $paymentConfig; } -} \ No newline at end of file +} diff --git a/Bootstrapping/Events/PluginConfigurationSubscriber.php b/Bootstrapping/Events/PluginConfigurationSubscriber.php index d81e4dfb..01a8d6ca 100644 --- a/Bootstrapping/Events/PluginConfigurationSubscriber.php +++ b/Bootstrapping/Events/PluginConfigurationSubscriber.php @@ -1,17 +1,13 @@ _countries AS $country) { + foreach ($this->_countries as $country) { if ($element['name'] === 'RatePayProfileID' . strtoupper($country)) { - foreach($element['values'] as $element) { + foreach ($element['values'] as $element) { $shopCredentials[$element['shopId']][$country]['profileID'] = trim($element['value']); } } - if ($element['name'] === 'RatePaySecurityCode' . strtoupper($country)) { - foreach($element['values'] as $element) { + if ($element['name'] === 'RatePaySecurityCode' . strtoupper($country)) { + foreach ($element['values'] as $element) { $shopCredentials[$element['shopId']][$country]['securityCode'] = trim($element['value']); } } if ($element['name'] === 'RatePayProfileID' . strtoupper($country) . 'Backend') { - foreach($element['values'] as $element) { + foreach ($element['values'] as $element) { $shopCredentials[$element['shopId']][$country]['profileIDBackend'] = trim($element['value']); } } if ($element['name'] === 'RatePaySecurityCode' . strtoupper($country) . 'Backend') { - foreach($element['values'] as $element) { + foreach ($element['values'] as $element) { $shopCredentials[$element['shopId']][$country]['securityCodeBackend'] = trim($element['value']); } } @@ -81,31 +77,31 @@ public function beforeSavePluginConfig(\Enlight_Hook_HookArgs $arguments) $rpayConfigWriter->truncateConfigTables(); - foreach($shopCredentials as $shopId => $credentials) { - foreach ($this->_countries AS $country) { + foreach ($shopCredentials as $shopId => $credentials) { + foreach ($this->_countries as $country) { if (null !== $credentials[$country]['profileID'] && null !== $credentials[$country]['securityCode']) { if ($rpayConfigWriter->writeRatepayConfig($credentials[$country]['profileID'], $credentials[$country]['securityCode'], $shopId, $country)) { - Shopware()->PluginLogger()->addNotice('Ruleset for ' . strtoupper($country) . ' successfully updated.'); + Logger::singleton()->addNotice('Ruleset for ' . strtoupper($country) . ' successfully updated.'); } if ($country == 'de') { if ($rpayConfigWriter->writeRatepayConfig($credentials[$country]['profileID'] . '_0RT', $credentials[$country]['securityCode'], $shopId, $country)) { - Shopware()->PluginLogger()->addNotice('Ruleset 0RT for ' . strtoupper($country) . ' successfully updated.'); + Logger::singleton()->addNotice('Ruleset 0RT for ' . strtoupper($country) . ' successfully updated.'); } } } if (null !== $credentials[$country]['profileIDBackend'] && null !== $credentials[$country]['securityCodeBackend']) { if ($rpayConfigWriter->writeRatepayConfig($credentials[$country]['profileIDBackend'], $credentials[$country]['securityCodeBackend'], $shopId, $country, true)) { - Shopware()->PluginLogger()->addNotice('Ruleset BACKEND for ' . strtoupper($country) . ' successfully updated.'); + Logger::singleton()->addNotice('Ruleset BACKEND for ' . strtoupper($country) . ' successfully updated.'); } if ($country == 'de') { if ($rpayConfigWriter->writeRatepayConfig($credentials[$country]['profileIDBackend'] . '_0RT', $credentials[$country]['securityCodeBackend'], $shopId, $country, true)) { - Shopware()->PluginLogger()->addNotice('Ruleset BACKEND 0RT for ' . strtoupper($country) . ' successfully updated.'); + Logger::singleton()->addNotice('Ruleset BACKEND 0RT for ' . strtoupper($country) . ' successfully updated.'); } } } } } } -} \ No newline at end of file +} diff --git a/Bootstrapping/Events/TemplateExtensionSubscriber.php b/Bootstrapping/Events/TemplateExtensionSubscriber.php index 4848fb37..e9f3bada 100644 --- a/Bootstrapping/Events/TemplateExtensionSubscriber.php +++ b/Bootstrapping/Events/TemplateExtensionSubscriber.php @@ -1,10 +1,5 @@ getControllerName() && 'confirm' === $request->getActionName() && strstr($paymentMethod->getName(), 'rpayratepay') @@ -89,12 +84,13 @@ public function extendTemplates(\Enlight_Event_EventArgs $args) $view->extendsTemplate('frontend/payment_rpay_part/checkout/confirm.tpl'); //if no DF token is set, receive all the necessary data to set it and extend template - if(true == $configPlugin['device-fingerprint-status'] && !Shopware()->Session()->RatePAY['dfpToken']) { + if (true == $configPlugin['device-fingerprint-status'] && !Shopware()->Session()->RatePAY['dfpToken']) { $view->assign('snippetId', $configPlugin['device-fingerprint-snippet-id']); try { $sId = Shopware()->SessionID(); - } catch (\Exception $exception) {} + } catch (\Exception $exception) { + } $tokenFirstPart = (!empty($sId)) ? $sId : rand(); @@ -121,11 +117,12 @@ protected function registerMyTemplateDir() * @param $shopId * @return mixed */ - private function getRatePayPluginConfig($shopId) { + private function getRatePayPluginConfig($shopId) + { //get ratepay config based on shopId return Shopware()->Db()->fetchRow( 'SELECT * FROM `rpay_ratepay_config` WHERE `shopId`=? AND backend=0', - array($shopId) + [$shopId] ); } -} \ No newline at end of file +} diff --git a/Bootstrapping/Events/UpdateTransactionsSubscriber.php b/Bootstrapping/Events/UpdateTransactionsSubscriber.php index 16f02b58..b0a00a0c 100644 --- a/Bootstrapping/Events/UpdateTransactionsSubscriber.php +++ b/Bootstrapping/Events/UpdateTransactionsSubscriber.php @@ -1,9 +1,11 @@ findCandidateOrdersForUpdate($config); $orderProcessor = new \Shopware_Plugins_Frontend_RpayRatePay_Component_Service_OrderStatusChangeHandler(); - foreach($orderIds as $orderId) { + foreach ($orderIds as $orderId) { /* @var \Shopware\Models\Order\Order $order */ $order = Shopware()->Models()->find('Shopware\Models\Order\Order', $orderId); $orderProcessor->informRatepayOfOrderStatusChange($order); } - } catch(\Exception $e) { - Shopware()->Pluginlogger()->error('Fehler UpdateTransactionsSubscriber: ' . + } catch (\Exception $e) { + Logger::singleton()->error('Fehler UpdateTransactionsSubscriber: ' . $e->getMessage() . ' ' . $e->getTraceAsString()); return $e->getMessage(); } - return "Success"; + return 'Success'; } /** @@ -69,9 +71,8 @@ private function findCandidateOrdersForUpdate($config) $config['RatePayFullReturn'], ]; - $paymentMethodsWrapped = []; - foreach($paymentMethods as $paymentMethod) { + foreach ($paymentMethods as $paymentMethod) { $paymentMethodsWrapped[] = "'{$paymentMethod}'"; } @@ -86,13 +87,13 @@ private function findCandidateOrdersForUpdate($config) $query = 'SELECT o.id FROM s_order o INNER JOIN s_order_history oh ON oh.orderID = o.id LEFT JOIN s_core_paymentmeans cp ON cp.id = o.paymentID - WHERE cp.name in ('. join(',', $paymentMethodsWrapped) . ') - AND o.status in ('. join(',', $orderStatus) .") + WHERE cp.name in (' . join(',', $paymentMethodsWrapped) . ') + AND o.status in (' . join(',', $orderStatus) . ') AND oh.change_date >= :changeDate - GROUP BY o.id"; + GROUP BY o.id'; $rows = Shopware()->Db()->fetchAll($query, [':changeDate' => $changeDate]); return array_column($rows, 'id'); } -} \ No newline at end of file +} diff --git a/Bootstrapping/FormsSetup.php b/Bootstrapping/FormsSetup.php index 67401a59..6d915ae4 100644 --- a/Bootstrapping/FormsSetup.php +++ b/Bootstrapping/FormsSetup.php @@ -1,21 +1,15 @@ bootstrap->Form(); @@ -33,7 +27,7 @@ public function install() { $this->bootstrap->addFormTranslations($translations); } catch (\Exception $exception) { $this->bootstrap->uninstall(); - throw new Exception("Can not create config elements." . $exception->getMessage()); + throw new Exception('Can not create config elements.' . $exception->getMessage()); } } @@ -41,12 +35,15 @@ public function install() { * @return mixed|void * @throws Exception */ - public function update() { + public function update() + { $this->install(); } /** * @return mixed|void */ - public function uninstall() {} -} \ No newline at end of file + public function uninstall() + { + } +} diff --git a/Bootstrapping/MenuesSetup.php b/Bootstrapping/MenuesSetup.php index 7b832af5..b7bd177d 100644 --- a/Bootstrapping/MenuesSetup.php +++ b/Bootstrapping/MenuesSetup.php @@ -1,34 +1,29 @@ bootstrap->Menu()->findOneBy(array('label' => 'logfile')); - $this->bootstrap->createMenuItem(array( - 'label' => 'RatePAY', - 'class' => 'sprite-cards-stack', - 'active' => 1, + $parent = $this->bootstrap->Menu()->findOneBy(['label' => 'logfile']); + $this->bootstrap->createMenuItem( + [ + 'label' => 'RatePAY', + 'class' => 'sprite-cards-stack', + 'active' => 1, 'controller' => 'RpayRatepayLogging', - 'action' => 'index', - 'parent' => $parent - ) + 'action' => 'index', + 'parent' => $parent + ] ); } catch (\Exception $exception) { $this->bootstrap->uninstall(); - throw new Exception("Can not create menu entry." . $exception->getMessage()); + throw new Exception('Can not create menu entry.' . $exception->getMessage()); } } @@ -36,10 +31,14 @@ public function install() { * @return mixed|void * @throws Exception */ - public function update() {} + public function update() + { + } /** * @return mixed|void */ - public function uninstall() {} -} \ No newline at end of file + public function uninstall() + { + } +} diff --git a/Bootstrapping/PaymentStatusesSetup.php b/Bootstrapping/PaymentStatusesSetup.php index a501dfb0..55eaacda 100644 --- a/Bootstrapping/PaymentStatusesSetup.php +++ b/Bootstrapping/PaymentStatusesSetup.php @@ -1,27 +1,23 @@ Db()->query($sql, array( + Shopware()->Db()->query($sql, [ 155, 'Zahlungsabwicklung durch RatePAY', 155, 'payment', 0 - )); + ]); } catch (\Exception $exception) { - Shopware()->Pluginlogger()->addNotice($exception->getMessage()); + Logger::singleton()->addNotice($exception->getMessage()); } } @@ -29,10 +25,14 @@ public function install() { * @return mixed|void * @throws Exception */ - public function update() {} + public function update() + { + } /** * @return mixed|void */ - public function uninstall() {} -} \ No newline at end of file + public function uninstall() + { + } +} diff --git a/Bootstrapping/PaymentsSetup.php b/Bootstrapping/PaymentsSetup.php index 7c1929f5..b146d343 100644 --- a/Bootstrapping/PaymentsSetup.php +++ b/Bootstrapping/PaymentsSetup.php @@ -1,20 +1,14 @@ loadConfig('payment_methods_install.json'); foreach ($paymentMethods as $payment) { @@ -23,7 +17,7 @@ public function install() { } } catch (\Exception $exception) { $this->bootstrap->uninstall(); - throw new Exception("Can not create payment." . $exception->getMessage()); + throw new Exception('Can not create payment.' . $exception->getMessage()); } } @@ -31,7 +25,8 @@ public function install() { * @return mixed|void * @throws Exception */ - public function update() { + public function update() + { $paymentMethods = $this->loadConfig('payment_methods_update.json'); foreach ($paymentMethods as $payment) { $payment['pluginID'] = $this->bootstrap->getId(); @@ -42,5 +37,7 @@ public function update() { /** * @return mixed|void */ - public function uninstall() {} -} \ No newline at end of file + public function uninstall() + { + } +} diff --git a/Bootstrapping/ShopConfigSetup.php b/Bootstrapping/ShopConfigSetup.php index a6d9878a..c2b3b46b 100644 --- a/Bootstrapping/ShopConfigSetup.php +++ b/Bootstrapping/ShopConfigSetup.php @@ -1,10 +1,5 @@ Db()); $configWriter = new RatepayConfigWriter(Shopware()->Db()); @@ -38,7 +35,7 @@ public function update() { $shops = $repo->findBy(['active' => true]); /** @var \Shopware\Models\Shop\Shop $shop */ - foreach($shops as $shop) { + foreach ($shops as $shop) { $this->updateRatepayConfig($configLoader, $configWriter, $shop->getId(), false); $this->updateRatepayConfig($configLoader, $configWriter, $shop->getId(), true); } @@ -47,8 +44,9 @@ public function update() { /** * @return mixed|void */ - public function uninstall() {} - + public function uninstall() + { + } /** * @param $configLoader @@ -62,7 +60,7 @@ private function updateRatepayConfig($configLoader, $configWriter, $shopId, $bac $profileId = $configLoader->getProfileId($iso, $shopId, false, $backend); $securityCode = $configLoader->getSecurityCode($iso, $shopId, $backend); - if(empty($profileId)) { + if (empty($profileId)) { continue; } @@ -74,4 +72,4 @@ private function updateRatepayConfig($configLoader, $configWriter, $shopId, $bac } } } -} \ No newline at end of file +} diff --git a/Bootstrapping/TranslationsSetup.php b/Bootstrapping/TranslationsSetup.php index 5ff82a75..215df58c 100644 --- a/Bootstrapping/TranslationsSetup.php +++ b/Bootstrapping/TranslationsSetup.php @@ -1,14 +1,6 @@ languageUpdate(); } @@ -25,28 +18,30 @@ public function install() { * @return mixed|void * @throws Exception */ - public function update() { + public function update() + { $this->languageUpdate(); } /** * @return mixed|void */ - public function uninstall() {} - + public function uninstall() + { + } private function languageUpdate() { - $locales = array( + $locales = [ 2 => 'en_EN', 108 => 'fr_FR', 176 => 'nl_NL', - ); + ]; $germanMessages = $this->getInstalledGermanMessages(); foreach ($germanMessages as $messageName) { - foreach ($locales AS $locale => $code) { + foreach ($locales as $locale => $code) { $lang = Shopware()->Db()->fetchRow( "SELECT `name` FROM `s_core_snippets` WHERE `namespace` LIKE 'RatePay' AND `localeID` = " . $locale . " AND `name` = '" . $messageName . "'" ); @@ -54,13 +49,13 @@ private function languageUpdate() if (empty($lang)) { $translation = $this->getTranslatedMessage($code, $messageName); if (!empty($translation)) { - Shopware()->Db()->insert('s_core_snippets', array( + Shopware()->Db()->insert('s_core_snippets', [ 'namespace' => 'RatePay', 'localeID' => $locale, 'shopID' => 1, 'name' => $messageName, 'value' => $translation, - )); + ]); } } } @@ -77,7 +72,7 @@ private function getInstalledGermanMessages() "SELECT `name` FROM `s_core_snippets` WHERE `namespace` LIKE 'RatePay' AND `localeID` = 1" ); - return array_map(function($item) { + return array_map(function ($item) { return $item['name']; }, $messages); } @@ -90,11 +85,12 @@ private function getInstalledGermanMessages() * @return mixed * @throws Exception */ - private function getTranslatedMessage($locale, $name) { + private function getTranslatedMessage($locale, $name) + { if (empty($this->translations) || !array_key_exists($locale, $this->translations)) { - $this->translations[$locale] = $this->loadConfig('locale/frontend/'.$locale.'.json'); + $this->translations[$locale] = $this->loadConfig('locale/frontend/' . $locale . '.json'); } return $this->translations[$locale][$name]; } -} \ No newline at end of file +} diff --git a/Component/CSRFWhitelistAware.php b/Component/CSRFWhitelistAware.php index 0be6e795..3acb0ab3 100755 --- a/Component/CSRFWhitelistAware.php +++ b/Component/CSRFWhitelistAware.php @@ -21,5 +21,7 @@ namespace Shopware\Components; if (!interface_exists('\Shopware\Components\CSRFWhitelistAware')) { - interface CSRFWhitelistAware {} -} \ No newline at end of file + interface CSRFWhitelistAware + { + } +} diff --git a/Component/History.php b/Component/History.php index 5c873bd0..b0ded185 100755 --- a/Component/History.php +++ b/Component/History.php @@ -19,7 +19,6 @@ */ class Shopware_Plugins_Frontend_RpayRatePay_Component_History { - /** * Logs the History for an Request * @@ -31,10 +30,10 @@ class Shopware_Plugins_Frontend_RpayRatePay_Component_History */ public function logHistory($orderId, $event, $name = '', $articlenumber = '', $quantity = '') { - $sql = "INSERT INTO `rpay_ratepay_order_history` " - . "(`orderId`, `event`, `articlename`, `articlenumber`, `quantity`) " - . "VALUES(?, ?, ?, ?, ?)"; - Shopware()->Db()->query($sql, array($orderId, $event, $name, $articlenumber, $quantity)); + $sql = 'INSERT INTO `rpay_ratepay_order_history` ' + . '(`orderId`, `event`, `articlename`, `articlenumber`, `quantity`) ' + . 'VALUES(?, ?, ?, ?, ?)'; + Shopware()->Db()->query($sql, [$orderId, $event, $name, $articlenumber, $quantity]); } /** @@ -46,12 +45,11 @@ public function logHistory($orderId, $event, $name = '', $articlenumber = '', $q */ public function getHistory($orderId) { - $sql = "SELECT * FROM `rpay_ratepay_order_history`" - . " WHERE `orderId`=? " - . "ORDER BY `id` DESC"; - $history = Shopware()->Db()->fetchAll($sql, array($orderId)); + $sql = 'SELECT * FROM `rpay_ratepay_order_history`' + . ' WHERE `orderId`=? ' + . 'ORDER BY `id` DESC'; + $history = Shopware()->Db()->fetchAll($sql, [$orderId]); return $history; } - } diff --git a/Component/Library/src/Model/Request/SubModel/Content/ShoppingBasket.php b/Component/Library/src/Model/Request/SubModel/Content/ShoppingBasket.php index b330b431..b6a91c4a 100755 --- a/Component/Library/src/Model/Request/SubModel/Content/ShoppingBasket.php +++ b/Component/Library/src/Model/Request/SubModel/Content/ShoppingBasket.php @@ -96,7 +96,7 @@ public function toArray() $amount += floatval($unitPrice); } - $this->admittedFields['Amount']['value'] = $amount; + $this->admittedFields['Amount']['value'] = round($amount, 2); } return parent::toArray(); diff --git a/Component/Library/src/Service/Math.php b/Component/Library/src/Service/Math.php index 33554f88..da7c7c2d 100644 --- a/Component/Library/src/Service/Math.php +++ b/Component/Library/src/Service/Math.php @@ -1,6 +1,7 @@ . + * + * Logging + * + * @category RatePAY + * @copyright Copyright (c) 2013 RatePAY GmbH (http://www.ratepay.com) + */ +class Shopware_Plugins_Frontend_RpayRatePay_Component_Logging +{ /** - * This program is free software; you can redistribute it and/or modify it under the terms of - * the GNU General Public License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License along with this program; - * if not, see . + * Logs the Request and Response * - * Logging - * - * @category RatePAY - * @copyright Copyright (c) 2013 RatePAY GmbH (http://www.ratepay.com) + * @param string $requestXml + * @param string $responseXml */ - class Shopware_Plugins_Frontend_RpayRatePay_Component_Logging + public function logRequest($requestXml, $responseXml) { + $version = Shopware()->Plugins()->Frontend()->RpayRatePay()->getVersion(); - /** - * Logs the Request and Response - * - * @param string $requestXml - * @param string $responseXml - */ - public function logRequest($requestXml, $responseXml) - { - $version = Shopware()->Plugins()->Frontend()->RpayRatePay()->getVersion(); - - preg_match("/(.*)<\/operation>/", $requestXml, $operationMatches); - $operation = $operationMatches[1]; + preg_match("/(.*)<\/operation>/", $requestXml, $operationMatches); + $operation = $operationMatches[1]; - preg_match('/(.*)<\/operation>/', $requestXml, $operationSubtypeMatches); - $operationSubtype = $operationSubtypeMatches[1] ? : 'N/A'; + preg_match('/(.*)<\/operation>/', $requestXml, $operationSubtypeMatches); + $operationSubtype = $operationSubtypeMatches[1] ?: 'N/A'; - preg_match("/(.*)<\/transaction-id>/", $requestXml, $transactionMatches); - $transactionId = $transactionMatches[1] ? : 'N/A'; + preg_match("/(.*)<\/transaction-id>/", $requestXml, $transactionMatches); + $transactionId = $transactionMatches[1] ?: 'N/A'; - preg_match("/(.*)<\/transaction-id>/", $responseXml, $transactionMatchesResponse); - $transactionId = $transactionId == 'N/A' && $transactionMatchesResponse[1] ? $transactionMatchesResponse[1] : $transactionId; + preg_match("/(.*)<\/transaction-id>/", $responseXml, $transactionMatchesResponse); + $transactionId = $transactionId == 'N/A' && $transactionMatchesResponse[1] ? $transactionMatchesResponse[1] : $transactionId; - $requestXml = preg_replace("/(.*)<\/owner>/", "xxxxxxxx", $requestXml); - $requestXml = preg_replace("/(.*)<\/bank-account-number>/", "xxxxxxxx", $requestXml); - $requestXml = preg_replace("/(.*)<\/bank-code>/", "xxxxxxxx", $requestXml); + $requestXml = preg_replace("/(.*)<\/owner>/", 'xxxxxxxx', $requestXml); + $requestXml = preg_replace("/(.*)<\/bank-account-number>/", 'xxxxxxxx', $requestXml); + $requestXml = preg_replace("/(.*)<\/bank-code>/", 'xxxxxxxx', $requestXml); - $bind = array( - 'version' => $version, - 'operation' => $operation, - 'suboperation' => $operationSubtype, - 'transactionId' => $transactionId, - 'request' => $requestXml, - 'response' => $responseXml - ); + $bind = [ + 'version' => $version, + 'operation' => $operation, + 'suboperation' => $operationSubtype, + 'transactionId' => $transactionId, + 'request' => $requestXml, + 'response' => $responseXml + ]; - try { - Shopware()->Db()->insert('rpay_ratepay_logging', $bind); - } catch (Exception $exception) { - Shopware()->Pluginlogger()->error('Fehler beim Loggen: ' . $exception->getMessage()); - } + try { + Shopware()->Db()->insert('rpay_ratepay_logging', $bind); + } catch (Exception $exception) { + Logger::singleton()->error('Fehler beim Loggen: ' . $exception->getMessage()); } - } +} diff --git a/Component/Mapper/BankData.php b/Component/Mapper/BankData.php index 9896e367..85a0f48b 100644 --- a/Component/Mapper/BankData.php +++ b/Component/Mapper/BankData.php @@ -1,14 +1,7 @@ accountNumber = $accountNumber; } - /** * @return array */ @@ -97,4 +89,4 @@ public function toArray() return $a; } -} \ No newline at end of file +} diff --git a/Component/Mapper/BasketArrayBuilder.php b/Component/Mapper/BasketArrayBuilder.php index bc4835a1..865e717b 100644 --- a/Component/Mapper/BasketArrayBuilder.php +++ b/Component/Mapper/BasketArrayBuilder.php @@ -1,16 +1,8 @@ itemObjectHasName($item)) { $itemData = $this->getUnnamedItem($item); } else { - $itemData = array( + $itemData = [ 'Description' => $item->name, 'ArticleNumber' => $item->articlenumber, 'Quantity' => $item->quantity, 'UnitPriceGross' => $unitPriceGross, 'TaxRate' => $item->taxRate, - ); + ]; } if (!empty($this->requestType)) { @@ -219,7 +211,6 @@ private function addItemFromObject($item) */ private function getUnnamedItem($item) { - $swPrice = $item->getPrice(); $unitPriceGross = $this->netItemPrices ? Math::netToGross($swPrice, $item->taxRate) : $swPrice; @@ -324,4 +315,4 @@ private function getQuantityForRequest($item) return $quantity; } -} \ No newline at end of file +} diff --git a/Component/Mapper/ModelFactory.php b/Component/Mapper/ModelFactory.php index 298ef715..44f3f2a1 100755 --- a/Component/Mapper/ModelFactory.php +++ b/Component/Mapper/ModelFactory.php @@ -6,6 +6,8 @@ use RatePAY\Service\Util; use RpayRatePay\Component\Model\ShopwareCustomerWrapper; use RpayRatePay\Component\Service\SessionLoader; +use RpayRatePay\Component\Service\Logger; +use RpayRatePay\Component\Service\ShopwareUtil; /** * This program is free software; you can redistribute it and/or modify it under the terms of @@ -57,7 +59,8 @@ public function setOrderId($orderId) $this->_orderId = $orderId; } - public function setZPercent() { + public function setZPercent() + { $this->_zPercent = true; } @@ -73,7 +76,7 @@ private function _getCountryCodesByBillingAddress() // Checkout address ids are set from shopware version >=5.2.0 if (isset($this->getSession()->checkoutBillingAddressId) && $this->getSession()->checkoutBillingAddressId > 0) { $addressModel = Shopware()->Models()->getRepository('Shopware\Models\Customer\Address'); - $checkoutAddressBilling = $addressModel->findOneBy(array('id' => $this->getSession()->checkoutBillingAddressId)); + $checkoutAddressBilling = $addressModel->findOneBy(['id' => $this->getSession()->checkoutBillingAddressId]); return $checkoutAddressBilling->getCountry()->getIso(); } else { $shopUser = Shopware()->Models()->find('Shopware\Models\Customer\Customer', $this->getSession()->sUserId); @@ -111,7 +114,8 @@ public function setTransactionId($transactionId) * @deprecated * @return bool|array|object */ - public function callRequest($operationType, array $operationData = []) { + public function callRequest($operationType, array $operationData = []) + { switch ($operationType) { case 'ProfileRequest': return $this->callProfileRequest($operationData); @@ -134,7 +138,8 @@ public function callRequest($operationType, array $operationData = []) { } } - public function callCalculationRequest($operationData) { + public function callCalculationRequest($operationData) + { $mbHead = $this->getHead(); $mbContent = new RatePAY\ModelBuilder('Content'); @@ -181,9 +186,10 @@ public function callPaymentConfirm($countryCode = false) * @return \RatePAY\ModelBuilder * @throws \RatePAY\Exception\ModelException */ - private function getHead($countryCode = false) { - $systemId = $this->getSystemId(); - $bootstrap = new \Shopware_Plugins_Frontend_RpayRatePay_Bootstrap('ratepay_config'); + private function getHead($countryCode = false) + { + $systemId = $this->getSystemId(); + $bootstrap = new \Shopware_Plugins_Frontend_RpayRatePay_Bootstrap('ratepay_config'); $head = [ 'SystemId' => $systemId, @@ -226,13 +232,14 @@ private function getHead($countryCode = false) { * @param $countryCode * @return int */ - public function getSandboxMode($countryCode) { + public function getSandboxMode($countryCode) + { $profileId = $this->getProfileId($countryCode); if (strstr($profileId, '_0RT') !== false) { $profileId = substr($profileId, 0, -4); } - $qry = 'SELECT sandbox FROM rpay_ratepay_config WHERE profileId = "'. $profileId .'"'; + $qry = 'SELECT sandbox FROM rpay_ratepay_config WHERE profileId = "' . $profileId . '"'; $sandbox = Shopware()->Db()->fetchOne($qry); return $sandbox; @@ -248,7 +255,8 @@ public function getSandboxMode($countryCode) { */ public function callPaymentRequest($paymentRequestData = null, $bankData = null) { - $sessionLoader = new SessionLoader($this->backend ? + $sessionLoader = new SessionLoader( + $this->backend ? Shopware()->BackendSession() : $this->getSession() ); @@ -276,21 +284,21 @@ public function callPaymentRequest($paymentRequestData = null, $bankData = null) $checkoutAddressShipping = $paymentRequestData->getShippingAddress(); $company = $checkoutAddressBilling->getCompany(); - if(empty($company)) { + if (empty($company)) { $dateOfBirth = $paymentRequestData->getBirthday(); } - if (Util::existsAndNotEmpty($customer, "getNumber")) { // From Shopware 5.2 billing number has moved to customer object + if (Util::existsAndNotEmpty($customer, 'getNumber')) { // From Shopware 5.2 billing number has moved to customer object $merchantCustomerId = $customer->getNumber(); - } elseif (Util::existsAndNotEmpty($checkoutAddressBilling, "getNumber")) { + } elseif (Util::existsAndNotEmpty($checkoutAddressBilling, 'getNumber')) { $merchantCustomerId = $checkoutAddressBilling->getNumber(); } $countryCodeBilling = PaymentRequestData::findCountryISO($checkoutAddressBilling); $countryCodeShipping = PaymentRequestData::findCountryISO($checkoutAddressShipping); - if(is_null($countryCodeBilling || is_null($countryCodeShipping))) { - Shopware()->Pluginlogger()->error('Country code not loaded....'); + if (is_null($countryCodeBilling || is_null($countryCodeShipping))) { + Logger::singleton()->error('Country code not loaded....'); } $mbHead->setArray([ @@ -352,7 +360,6 @@ public function callPaymentRequest($paymentRequestData = null, $bankData = null) ], [ 'Address' => $this->_getCheckoutAddress($checkoutAddressShipping, 'DELIVERY', $countryCodeShipping) ] - ], 'Contacts' => [ 'Email' => $customer->getEmail(), @@ -374,9 +381,10 @@ public function callPaymentRequest($paymentRequestData = null, $bankData = null) } $elv = false; if (!empty($installmentDetails)) { - $serviceUtil = new Shopware_Plugins_Frontend_RpayRatePay_Component_Service_Util(); + $serviceUtil = new ShopwareUtil(); - $contentArr['Payment']['DebitPayType'] = $serviceUtil->getDebitPayType($this->getSession()->RatePAY['ratenrechner']['payment_firstday'] + $contentArr['Payment']['DebitPayType'] = $serviceUtil->getDebitPayType( + $this->getSession()->RatePAY['ratenrechner']['payment_firstday'] ); if ($contentArr['Payment']['DebitPayType'] == 'DIRECT-DEBIT') { @@ -385,9 +393,10 @@ public function callPaymentRequest($paymentRequestData = null, $bankData = null) $calculatorAmountWithoutInterest = $this->getSession()->RatePAY['ratenrechner']['amount']; - if ((string)$calculatorAmountWithoutInterest !== (string)$paymentRequestData->getAmount()) { - throw new \Exception('Attempt to create order with wrong amount in installment calculator.' . - 'Expected '. $paymentRequestData->getAmount() . " Got " . $calculatorAmountWithoutInterest + if ((string)$calculatorAmountWithoutInterest !== (string)$paymentRequestData->getAmount()) { + throw new \Exception( + 'Attempt to create order with wrong amount in installment calculator.' . + 'Expected ' . $paymentRequestData->getAmount() . ' Got ' . $calculatorAmountWithoutInterest ); } @@ -408,10 +417,10 @@ public function callPaymentRequest($paymentRequestData = null, $bankData = null) $paymentRequest = $rb->callPaymentRequest($mbHead, $mbContent); $this->_logging->logRequest($paymentRequest->getRequestRaw(), $paymentRequest->getResponseRaw()); - /*Shopware()->Pluginlogger()->info("REQUEST"); - Shopware()->Pluginlogger()->info($paymentRequest->getRequestRaw()); - Shopware()->Pluginlogger()->info("RESPONSE"); - Shopware()->Pluginlogger()->info($paymentRequest->getResponseRaw());*/ + /*Logger::singleton()->info("REQUEST"); + Logger::singleton()->info($paymentRequest->getRequestRaw()); + Logger::singleton()->info("RESPONSE"); + Logger::singleton()->info($paymentRequest->getResponseRaw());*/ return $paymentRequest; } @@ -426,8 +435,9 @@ private function getSession() * * @return array */ - private function getPaymentDetails() { - $paymentDetails = array(); + private function getPaymentDetails() + { + $paymentDetails = []; $paymentDetails['InstallmentNumber'] = $this->getSession()->RatePAY['ratenrechner']['number_of_rates']; $paymentDetails['InstallmentAmount'] = $this->getSession()->RatePAY['ratenrechner']['rate']; @@ -438,16 +448,16 @@ private function getPaymentDetails() { return $paymentDetails; } - /** - * @param $operationData - * @return bool|array - * @throws \RatePAY\Exception\ModelException - */ - private function callProfileRequest($operationData) - { - $systemId = $this->getSystemId(); - $sandbox = true; - $bootstrap = new \Shopware_Plugins_Frontend_RpayRatePay_Bootstrap('ratepay_config'); + /** + * @param $operationData + * @return bool|array + * @throws \RatePAY\Exception\ModelException + */ + private function callProfileRequest($operationData) + { + $systemId = $this->getSystemId(); + $sandbox = true; + $bootstrap = new \Shopware_Plugins_Frontend_RpayRatePay_Bootstrap('ratepay_config'); if (strpos($operationData['profileId'], '_TE_')) { $sandbox = true; @@ -484,7 +494,6 @@ private function callProfileRequest($operationData) $profileRequest = $rb->callProfileRequest($mbHead); $this->_logging->logRequest($profileRequest->getRequestRaw(), $profileRequest->getResponseRaw()); - } if ($profileRequest->isSuccessful()) { if ($sandbox == true) { @@ -492,7 +501,7 @@ private function callProfileRequest($operationData) } else { $sandbox = 0; } - return array('result' =>$profileRequest->getResult(), 'sandbox' => $sandbox); + return ['result' => $profileRequest->getResult(), 'sandbox' => $sandbox]; } return false; } @@ -517,8 +526,7 @@ public function isSandboxMode() */ private function getSystemId() { - - $systemId = Shopware()->Db()->fetchOne("SELECT `host` FROM `s_core_shops` WHERE `default`=1") ? : $_SERVER['SERVER_ADDR']; + $systemId = Shopware()->Db()->fetchOne('SELECT `host` FROM `s_core_shops` WHERE `default`=1') ?: $_SERVER['SERVER_ADDR']; return $systemId; } @@ -530,11 +538,11 @@ private function getSystemId() * @param bool$type* @param null $orderId * @return array */ - private function createBasketArray($items, $type = false, $orderId = null) { - + private function createBasketArray($items, $type = false, $orderId = null) + { $useFallbackShipping = $this->usesShippingItemFallback($orderId); $basketFactory = new \Shopware_Plugins_Frontend_RpayRatePay_Component_Mapper_BasketArrayBuilder( - $this->_retry , + $this->_retry, $type, $this->netItemPrices, $useFallbackShipping @@ -578,13 +586,13 @@ private function callConfirmationDeliver($operationData) $mbContent->setArray($shoppingBasket); $documentModel = Shopware()->Models()->getRepository('Shopware\Models\Order\Document\Document'); - $document = $documentModel->findOneBy(array('orderId' => $operationData['orderId'], 'type' => 1)); + $document = $documentModel->findOneBy(['orderId' => $operationData['orderId'], 'type' => 1]); if (!is_null($document)) { $dateObject = new \DateTime(); - $currentDate = $dateObject->format("Y-m-d"); - $currentTime = $dateObject->format("H:m:s"); - $currentDateTime = $currentDate . "T" . $currentTime; + $currentDate = $dateObject->format('Y-m-d'); + $currentTime = $dateObject->format('H:m:s'); + $currentDateTime = $currentDate . 'T' . $currentTime; $invoicing = [ 'Invoicing' => [ @@ -600,16 +608,16 @@ private function callConfirmationDeliver($operationData) $confirmationDeliver = $rb->callConfirmationDeliver($mbHead, $mbContent); $this->_logging->logRequest($confirmationDeliver->getRequestRaw(), $confirmationDeliver->getResponseRaw()); - if ($confirmationDeliver->isSuccessful()) { - return true; - } elseif ($this->_retry == false && (int)$confirmationDeliver->getReasonCode() == 2300) { - $this->_retry = true; - return $this->callRequest('ConfirmationDeliver', $operationData); - } - - return false; + if ($confirmationDeliver->isSuccessful()) { + return true; + } elseif ($this->_retry == false && (int)$confirmationDeliver->getReasonCode() == 2300) { + $this->_retry = true; + return $this->callRequest('ConfirmationDeliver', $operationData); } + return false; + } + /** * call a payment change (return, cancellation, order change) * @@ -630,21 +638,20 @@ private function callPaymentChange($operationData) if ($operationData['subtype'] == 'credit') { if ($operationData['items']['price'] > 0) { - $shoppingItems['Items'] = array('Item' => $item = array( + $shoppingItems['Items'] = ['Item' => $item = [ 'ArticleNumber' => $operationData['items']['articleordernumber'], 'Quantity' => 1, 'Description' => $operationData['items']['name'], 'UnitPriceGross' => $operationData['items']['price'], 'TaxRate' => $operationData['items']['tax_rate'], - )); + ]]; } else { - $shoppingItems = array('Discount' => $item = array( + $shoppingItems = ['Discount' => $item = [ 'Description' => $operationData['items']['name'], 'UnitPriceGross' => $operationData['items']['price'], 'TaxRate' => $operationData['items']['tax_rate'] - )); + ]]; } - } else { $shoppingItems = $this->createBasketArray($operationData['items'], $operationData['subtype'], $operationData['orderId']); } @@ -669,7 +676,6 @@ private function callPaymentChange($operationData) return false; } - /** * Returns the OrderID for the TransactionId set to this Factory * @@ -682,10 +688,10 @@ private function _getOrderIdFromTransactionId() if (!empty($transactionId)) { $returnValue = Shopware()->Db()->fetchOne( - "SELECT `ordernumber` FROM `s_order` " - . "INNER JOIN `s_core_paymentmeans` ON `s_core_paymentmeans`.`id` = `s_order`.`paymentID` " - . "WHERE `s_order`.`transactionID`=?;", - array($transactionId) + 'SELECT `ordernumber` FROM `s_order` ' + . 'INNER JOIN `s_core_paymentmeans` ON `s_core_paymentmeans`.`id` = `s_order`.`paymentID` ' + . 'WHERE `s_order`.`transactionID`=?;', + [$transactionId] ); } @@ -705,7 +711,7 @@ private function _getCustomerIP() } else { if (!empty($this->_transactionId)) { $customerIp = Shopware()->Db()->fetchOne( - "SELECT `remote_addr` FROM `s_order` WHERE `transactionID`=" . $this->_transactionId + 'SELECT `remote_addr` FROM `s_order` WHERE `transactionID`=' . $this->_transactionId ); } else { $customerIp = $_SERVER['SERVER_ADDR']; @@ -723,14 +729,15 @@ private function _getCustomerIP() * @param $countryCode * @return array */ - private function _getCheckoutAddress($checkoutAddress, $type, $countryCode) { - $address = array( + private function _getCheckoutAddress($checkoutAddress, $type, $countryCode) + { + $address = [ 'Type' => strtolower($type), 'Street' => $checkoutAddress->getStreet(), 'ZipCode' => $checkoutAddress->getZipCode(), 'City' => $checkoutAddress->getCity(), 'CountryCode' => $countryCode, - ); + ]; if ($type == 'DELIVERY') { $address['FirstName'] = $checkoutAddress->getFirstName(); @@ -754,15 +761,14 @@ private function _getCheckoutAddress($checkoutAddress, $type, $countryCode) { */ public function getProfileId($countryCode = false) { - if (!$countryCode) { $countryCode = $this->_getCountryCodesByBillingAddress(); } $configKey = RpayRatePay\Component\Service\ConfigLoader::getProfileIdKey($countryCode, $this->backend); - if(null !== $this->_config) { + if (null !== $this->_config) { $profileId = $this->_config->get($configKey); - } else{ + } else { if (!empty($this->_transactionId)) { $shopId = Shopware()->Db()->fetchOne( "SELECT `subshopID` FROM `s_order` WHERE `transactionID`= '" . $this->_transactionId . "'" @@ -776,7 +782,7 @@ public function getProfileId($countryCode = false) } if (empty($profileId)) { - throw new \Exception("Profile id not found: key " . $configKey); + throw new \Exception('Profile id not found: key ' . $configKey); } return $profileId; @@ -790,13 +796,12 @@ public function getProfileId($countryCode = false) */ public function getSecurityCode($countryCode = false) { - if (!$countryCode) { $countryCode = $this->_getCountryCodesByBillingAddress(); } $configKey = RpayRatePay\Component\Service\ConfigLoader::getSecurityCodeKey($countryCode, $this->backend); - if(null !== $this->_config) { + if (null !== $this->_config) { $securityCode = $this->_config->get($configKey); } else { if (!empty($this->_transactionId)) { @@ -808,7 +813,7 @@ public function getSecurityCode($countryCode = false) } if (empty($securityCode)) { - throw new \Exception("Security code not found: key " . $configKey); + throw new \Exception('Security code not found: key ' . $configKey); } return $securityCode; @@ -825,7 +830,7 @@ private function getShippingItemData(PaymentRequestData $shippingData, $useFallb Math::netToGross($shippingData->getShippingCost(), $shippingData->getShippingTax()) : $shippingData->getShippingCost(); - $priceGross = round($priceGross, 2); + $priceGross = round($priceGross, 3); $item = [ 'Description' => 'Shipping costs', @@ -857,9 +862,9 @@ private function usesShippingItemFallback($orderId = null) // return boolval($result['ratepay_fallback_shipping']); } - $query = "SELECT ratepay_fallback_shipping FROM `s_order_attributes` WHERE orderID = ?"; - $result = Shopware()->Db()->executeQuery($query, [$orderId])->fetch()["ratepay_fallback_shipping"]; + $query = 'SELECT ratepay_fallback_shipping FROM `s_order_attributes` WHERE orderID = ?'; + $result = Shopware()->Db()->executeQuery($query, [$orderId])->fetch()['ratepay_fallback_shipping']; return is_null($result) ? false : (boolval($result) || $configured); } -} \ No newline at end of file +} diff --git a/Component/Mapper/PaymentRequestData.php b/Component/Mapper/PaymentRequestData.php index 1a612bd8..598e7b7a 100644 --- a/Component/Mapper/PaymentRequestData.php +++ b/Component/Mapper/PaymentRequestData.php @@ -1,10 +1,4 @@ dfpToken; } - public function __construct($method, + public function __construct( + $method, $customer, $billingAddress, $shippingAddress, @@ -136,8 +131,7 @@ public function __construct($method, $dfpToken, $lang, $amount - ) - { + ) { $this->method = $method; $this->customer = $customer; $this->billingAddress = $billingAddress; @@ -163,11 +157,11 @@ public function getBirthday() $customerBilling = $customerWrapped->getBilling(); if (Util::existsAndNotEmpty($this->customer, 'getBirthday')) { - $dateOfBirth = $this->customer->getBirthday()->format("Y-m-d"); // From Shopware 5.2 date of birth has moved to customer object - } else if (Util::existsAndNotEmpty($customerBilling, 'getBirthday')) { - $dateOfBirth = $customerBilling->getBirthday()->format("Y-m-d"); - } else if (Util::existsAndNotEmpty($this->billingAddress, 'getBirthday')) { - $dateOfBirth = $this->billingAddress->getBirthday()->format("Y-m-d"); + $dateOfBirth = $this->customer->getBirthday()->format('Y-m-d'); // From Shopware 5.2 date of birth has moved to customer object + } elseif (Util::existsAndNotEmpty($customerBilling, 'getBirthday')) { + $dateOfBirth = $customerBilling->getBirthday()->format('Y-m-d'); + } elseif (Util::existsAndNotEmpty($this->billingAddress, 'getBirthday')) { + $dateOfBirth = $this->billingAddress->getBirthday()->format('Y-m-d'); } return $dateOfBirth; diff --git a/Component/Model/ShopwareAddressWrapper.php b/Component/Model/ShopwareAddressWrapper.php index e4c12936..482c174d 100644 --- a/Component/Model/ShopwareAddressWrapper.php +++ b/Component/Model/ShopwareAddressWrapper.php @@ -2,8 +2,6 @@ namespace RpayRatePay\Component\Model; - - /** * Class ShopwareAddressWrapper * @package RpayRatePay\Component\Model @@ -19,7 +17,6 @@ class ShopwareAddressWrapper /** @var string */ private $addressClass; - /** * ShopwareAddressWrapper constructor. * @param object $address @@ -48,5 +45,4 @@ public function getCountry() throw new \Exception('False object type sent to ShopwareAddressWrapper'); } - -} \ No newline at end of file +} diff --git a/Component/Model/ShopwareCustomerWrapper.php b/Component/Model/ShopwareCustomerWrapper.php index 55e8e069..573660f6 100644 --- a/Component/Model/ShopwareCustomerWrapper.php +++ b/Component/Model/ShopwareCustomerWrapper.php @@ -14,11 +14,9 @@ */ class ShopwareCustomerWrapper { - /** @var Customer $customer */ private $customer; - /** @var \Shopware\Components\Model\ModelManager $em */ private $em; @@ -115,7 +113,6 @@ private function getShippingChaotic() return $rotten; } - /** * @return null|object|\Shopware\Models\Country\Country * @throws \Doctrine\ORM\ORMException @@ -166,8 +163,6 @@ public function getShippingCountry() return $country; } - - /** * @return null|\Shopware\Models\Customer\Address */ @@ -215,4 +210,4 @@ private function getShippingRotten() return null; } -} \ No newline at end of file +} diff --git a/Component/Service/ConfigLoader.php b/Component/Service/ConfigLoader.php index 4bc7d2e6..57fe3d88 100644 --- a/Component/Service/ConfigLoader.php +++ b/Component/Service/ConfigLoader.php @@ -1,10 +1,5 @@ config = Shopware()->Plugins()->Frontend()->RpayRatePay()->Config(); - } - - private function getPaymentMeansMap() { + private function getPaymentMeansMap() + { return [ - "rpayratepayrate" => "installment", - "rpayratepayinvoice" => "invoice", - "rpayratepaydebit" => "debit", - "rpayratepayrate0" => "installment0" + 'rpayratepayrate' => 'installment', + 'rpayratepayinvoice' => 'invoice', + 'rpayratepaydebit' => 'debit', + 'rpayratepayrate0' => 'installment0' ]; } @@ -43,13 +37,13 @@ private function getPaymentMeansMap() { public function getPaymentColumnFromPaymentMeansName($paymentName) { $map = $this->getPaymentMeansMap(); - if( array_key_exists($paymentName, $map)) { + if (array_key_exists($paymentName, $map)) { return $map[$paymentName]; } else { return null; } } - + /** * @param int $shopId * @param string $countryISO @@ -64,12 +58,12 @@ public function getPluginConfigForPaymentType($shopId, $countryISO, $paymentColu $sBackend = $backend ? '1' : '0'; - $qry = "SELECT * + $qry = 'SELECT * FROM `rpay_ratepay_config` AS rrc JOIN `rpay_ratepay_config_payment` AS rrcp - ON rrcp.`rpay_id` = rrc.`" . $paymentColumn . "` + ON rrcp.`rpay_id` = rrc.`' . $paymentColumn . '` LEFT JOIN `rpay_ratepay_config_installment` AS rrci - ON rrci.`rpay_id` = rrc.`" . $paymentColumn . "` + ON rrci.`rpay_id` = rrc.`' . $paymentColumn . "` WHERE rrc.`shopId` = '" . $shopId . "' AND rrc.`profileId`= '" . $profileId . "' AND rrc.backend=$sBackend"; @@ -133,4 +127,4 @@ public static function getSecurityCodeKey($countryISO, $backend = false) } return $securityCodeKey; } -} \ No newline at end of file +} diff --git a/Component/Service/Logger.php b/Component/Service/Logger.php new file mode 100644 index 00000000..7577746c --- /dev/null +++ b/Component/Service/Logger.php @@ -0,0 +1,24 @@ +logger = $logger; + } + + /** + * @return \Shopware\Components\Logger + */ + public static function singleton() + { + return Shopware()->Container()->get('pluginlogger'); + // return Shopware()->Container()->get('logger'); + } +} diff --git a/Component/Service/OrderStatusChangeHandler.php b/Component/Service/OrderStatusChangeHandler.php index 037c1c27..75c1e414 100644 --- a/Component/Service/OrderStatusChangeHandler.php +++ b/Component/Service/OrderStatusChangeHandler.php @@ -23,7 +23,7 @@ private function mustSendFullShipped(Shopware\Models\Order\Order $order, $config WHERE o.id = ? AND (rop.delivered != 0 OR rop.cancelled != 0 OR rop.returned != 0)'; - $count = Shopware()->Db()->fetchOne($query, array($order->getId())); + $count = Shopware()->Db()->fetchOne($query, [$order->getId()]); return (int)$count === 0; } @@ -49,10 +49,9 @@ private function mustSendFullCancellation(Shopware\Models\Order\Order $order, $c WHERE o.id = ? AND (rop.delivered !=0 OR rop.cancelled != 0 OR rop.returned != 0)'; - $count = Shopware()->Db()->fetchOne($query, array($order->getId())); + $count = Shopware()->Db()->fetchOne($query, [$order->getId()]); return (int)$count === 0; - } /** @@ -76,7 +75,7 @@ private function mustSendFullReturn(Shopware\Models\Order\Order $order, $config) WHERE o.id = ? AND (rop.delivered = 0 OR rop.cancelled != 0 OR rop.returned != 0)'; - $count = Shopware()->Db()->fetchOne($query, array($order->getId())); + $count = Shopware()->Db()->fetchOne($query, [$order->getId()]); return (int)$count === 0; } @@ -96,11 +95,11 @@ public function informRatepayOfOrderStatusChange(Shopware\Models\Order\Order $or $netPrices = $order->getNet() === 1; $modelFactory = new Shopware_Plugins_Frontend_RpayRatePay_Component_Mapper_ModelFactory(null, $backend, $netPrices); - $history = new Shopware_Plugins_Frontend_RpayRatePay_Component_History(); + $history = new Shopware_Plugins_Frontend_RpayRatePay_Component_History(); $shippingCosts = $order->getInvoiceShipping(); - $items = array(); + $items = []; $i = 0; foreach ($order->getDetails() as $item) { $items[$i]['articlename'] = $item->getArticlename(); @@ -128,15 +127,15 @@ public function informRatepayOfOrderStatusChange(Shopware\Models\Order\Order $or if ($result === true) { foreach ($items as $item) { - $bind = array( + $bind = [ 'delivered' => $item['quantity'] - ); + ]; $this->updateItem($order->getId(), $item['ordernumber'], $bind); if ($item['quantity'] <= 0) { continue; } - $history->logHistory($order->getId(), "Artikel wurde versand.", $item['articlename'], $item['ordernumber'], $item['quantity']); + $history->logHistory($order->getId(), 'Artikel wurde versand.', $item['articlename'], $item['ordernumber'], $item['quantity']); } } } @@ -151,14 +150,14 @@ public function informRatepayOfOrderStatusChange(Shopware\Models\Order\Order $or if ($result === true) { foreach ($items as $item) { - $bind = array( + $bind = [ 'cancelled' => $item['quantity'] - ); + ]; $this->updateItem($order->getId(), $item['ordernumber'], $bind); if ($item['quantity'] <= 0) { continue; } - $history->logHistory($order->getId(), "Artikel wurde storniert.", $item['articlename'], $item['ordernumber'], $item['quantity']); + $history->logHistory($order->getId(), 'Artikel wurde storniert.', $item['articlename'], $item['ordernumber'], $item['quantity']); } } } @@ -173,14 +172,14 @@ public function informRatepayOfOrderStatusChange(Shopware\Models\Order\Order $or if ($result === true) { foreach ($items as $item) { - $bind = array( + $bind = [ 'returned' => $item['quantity'] - ); + ]; $this->updateItem($order->getId(), $item['ordernumber'], $bind); if ($item['quantity'] <= 0) { continue; } - $history->logHistory($order->getId(), "Artikel wurde retourniert.", $item['articlename'], $item['ordernumber'], $item['quantity']); + $history->logHistory($order->getId(), 'Artikel wurde retourniert.', $item['articlename'], $item['ordernumber'], $item['quantity']); } } } @@ -199,9 +198,8 @@ private function updateItem($orderID, $articleOrderNumber, $bind) if ($articleOrderNumber === 'shipping') { Shopware()->Db()->update('rpay_ratepay_order_shipping', $bind, '`s_order_id`=' . $orderID); } else { - $positionId = Shopware()->Db()->fetchOne("SELECT `id` FROM `s_order_details` WHERE `orderID`=? AND `articleordernumber`=?", array($orderID, $articleOrderNumber)); + $positionId = Shopware()->Db()->fetchOne('SELECT `id` FROM `s_order_details` WHERE `orderID`=? AND `articleordernumber`=?', [$orderID, $articleOrderNumber]); Shopware()->Db()->update('rpay_ratepay_order_positions', $bind, '`s_order_details_id`=' . $positionId); } } - -} \ No newline at end of file +} diff --git a/Component/Service/PaymentProcessor.php b/Component/Service/PaymentProcessor.php index 2cff5e25..425984a8 100644 --- a/Component/Service/PaymentProcessor.php +++ b/Component/Service/PaymentProcessor.php @@ -1,15 +1,8 @@ db->query( - "INSERT INTO `rpay_ratepay_order_shipping` (`s_order_id`) VALUES(?)", - array($order->getId()) + 'INSERT INTO `rpay_ratepay_order_shipping` (`s_order_id`) VALUES(?)', + [$order->getId()] ); } @@ -41,12 +34,12 @@ public function setOrderAttributes($order, $paymentRequestResult, $fallbackShipp { $this->db->update( //wird wohl nicht gehen, da das Custom-Feld nicht da ist 's_order_attributes', - array( + [ 'attribute5' => $paymentRequestResult->getDescriptor(), 'attribute6' => $paymentRequestResult->getTransactionId(), 'ratepay_fallback_shipping' => $fallbackShipping, 'ratepay_backend' => $backend, - ), + ], 'orderID=' . $order->getId() ); } @@ -56,24 +49,24 @@ public function setOrderAttributes($order, $paymentRequestResult, $fallbackShipp */ public function insertRatepayPositions($order) { - $sql = "SELECT `id` FROM `s_order_details` WHERE `ordernumber`=?;"; - Shopware()->Pluginlogger()->info('NOW SETTING ORDER DETAILS: ' . $sql); + $sql = 'SELECT `id` FROM `s_order_details` WHERE `ordernumber`=?;'; + Logger::singleton()->info('NOW SETTING ORDER DETAILS: ' . $sql); - $rows = $this->db->fetchAll($sql, array($order->getNumber())); + $rows = $this->db->fetchAll($sql, [$order->getNumber()]); - Shopware()->Pluginlogger()->info('GOT ROWS ' . count($rows)); + Logger::singleton()->info('GOT ROWS ' . count($rows)); - $values = ""; + $values = ''; foreach ($rows as $row) { - $values .= "(" . $row['id'] . "),"; + $values .= '(' . $row['id'] . '),'; } $values = substr($values, 0, -1); - $sqlInsert = "INSERT INTO `rpay_ratepay_order_positions` (`s_order_details_id`) VALUES " . $values; - Shopware()->Pluginlogger()->info('INSERT NOW ' . $sqlInsert); + $sqlInsert = 'INSERT INTO `rpay_ratepay_order_positions` (`s_order_details_id`) VALUES ' . $values; + Logger::singleton()->info('INSERT NOW ' . $sqlInsert); try { $this->db->query($sqlInsert); } catch (Exception $exception) { - Shopware()->Pluginlogger()->error($exception->getMessage()); + Logger::singleton()->error($exception->getMessage()); } } @@ -96,7 +89,8 @@ public function setPaymentStatusPaid($order) Shopware()->Models()->flush($order); Shopware()->Modules()->Order() - ->setPaymentStatus($order->getId(), + ->setPaymentStatus( + $order->getId(), self::PAYMENT_STATUS_COMPLETELY_PAID, false ); @@ -105,6 +99,8 @@ public function setPaymentStatusPaid($order) /** * @param $transactionId * @param \Shopware\Models\Order\Order $order + * @param bool $backend + * @throws \Exception */ public function sendPaymentConfirm($transactionId, $order, $backend = false) { @@ -115,5 +111,4 @@ public function sendPaymentConfirm($transactionId, $order, $backend = false) $modelFactory->setOrderId($order->getNumber()); $modelFactory->callPaymentConfirm($countryCode); } - -} \ No newline at end of file +} diff --git a/Component/Service/RatepayConfigWriter.php b/Component/Service/RatepayConfigWriter.php index 48b2f784..57274beb 100644 --- a/Component/Service/RatepayConfigWriter.php +++ b/Component/Service/RatepayConfigWriter.php @@ -24,13 +24,12 @@ public function truncateConfigTables() $this->db->query($configPaymentSql); $this->db->query($configInstallmentSql); } catch (\Exception $exception) { - Shopware()->Pluginlogger()->info($exception->getMessage()); + Logger::singleton()->info($exception->getMessage()); return false; } return true; } - /** * Sends a Profile_request and saves the data into the Database * @@ -46,32 +45,31 @@ public function truncateConfigTables() public function writeRatepayConfig($profileId, $securityCode, $shopId, $country, $backend = false) { $factory = new \Shopware_Plugins_Frontend_RpayRatePay_Component_Mapper_ModelFactory(null, $backend); - $data = array( + $data = [ 'profileId' => $profileId, 'securityCode' => $securityCode - ); + ]; $response = $factory->callRequest('ProfileRequest', $data); - $payments = array('invoice', 'elv', 'installment'); + $payments = ['invoice', 'elv', 'installment']; if (is_array($response) && $response !== false) { - - foreach ($payments AS $payment) { + foreach ($payments as $payment) { if (strstr($profileId, '_0RT') !== false) { if ($payment !== 'installment') { continue; } } - $dataPayment = array( + $dataPayment = [ $response['result']['merchantConfig']['activation-status-' . $payment], $response['result']['merchantConfig']['b2b-' . $payment] == 'yes' ? 1 : 0, $response['result']['merchantConfig']['tx-limit-' . $payment . '-min'], $response['result']['merchantConfig']['tx-limit-' . $payment . '-max'], $response['result']['merchantConfig']['tx-limit-' . $payment . '-max-b2b'], $response['result']['merchantConfig']['delivery-address-' . $payment] == 'yes' ? 1 : 0, - ); + ]; $paymentSql = 'INSERT INTO `rpay_ratepay_config_payment`' . '(`status`, `b2b`,`limit_min`,`limit_max`,' @@ -82,19 +80,19 @@ public function writeRatepayConfig($profileId, $securityCode, $shopId, $country, $id = $this->db->fetchOne('SELECT `rpay_id` FROM `rpay_ratepay_config_payment` ORDER BY `rpay_id` DESC'); $type[$payment] = $id; } catch (\Exception $exception) { - Shopware()->Pluginlogger()->error($exception->getMessage()); + Logger::singleton()->error($exception->getMessage()); return false; } } if ($response['result']['merchantConfig']['activation-status-installment'] == 2) { - $installmentConfig = array( + $installmentConfig = [ $type['installment'], $response['result']['installmentConfig']['month-allowed'], $response['result']['installmentConfig']['valid-payment-firstdays'], $response['result']['installmentConfig']['rate-min-normal'], $response['result']['installmentConfig']['interestrate-default'], - ); + ]; $paymentSql = 'INSERT INTO `rpay_ratepay_config_installment`' . '(`rpay_id`, `month-allowed`,`payment-firstday`,`interestrate-default`,' . '`rate-min-normal`)' @@ -102,17 +100,16 @@ public function writeRatepayConfig($profileId, $securityCode, $shopId, $country, try { $this->db->query($paymentSql, $installmentConfig); } catch (\Exception $exception) { - Shopware()->Pluginlogger()->error($exception->getMessage()); + Logger::singleton()->error($exception->getMessage()); return false; } - } if (strstr($profileId, '_0RT') !== false) { $qry = "UPDATE rpay_ratepay_config SET installment0 = '" . $type['installment'] . "' WHERE profileId = '" . substr($profileId, 0, -4) . "'"; $this->db->query($qry); } else { - $data = array( + $data = [ $response['result']['merchantConfig']['profile-id'], $type['invoice'], $type['installment'], @@ -129,7 +126,7 @@ public function writeRatepayConfig($profileId, $securityCode, $shopId, $country, $backend, //shopId always needs be the last line $shopId - ); + ]; $activePayments[] = '"rpayratepayinvoice"'; $activePayments[] = '"rpayratepaydebit"'; @@ -137,7 +134,7 @@ public function writeRatepayConfig($profileId, $securityCode, $shopId, $country, $activePayments[] = '"rpayratepayrate0"'; if (count($activePayments) > 0) { - $updateSqlActivePaymentMethods = 'UPDATE `s_core_paymentmeans` SET `active` = 1 WHERE `name` in(' . implode(",", $activePayments) . ') AND `active` <> 0'; + $updateSqlActivePaymentMethods = 'UPDATE `s_core_paymentmeans` SET `active` = 1 WHERE `name` in(' . implode(',', $activePayments) . ') AND `active` <> 0'; } $configSql = 'INSERT INTO `rpay_ratepay_config`' . '(`profileId`, `invoice`, `installment`, `debit`, `installment0`, `installmentDebit`,' @@ -154,17 +151,17 @@ public function writeRatepayConfig($profileId, $securityCode, $shopId, $country, return true; } catch (\Exception $exception) { - Shopware()->Pluginlogger()->error($exception->getMessage()); + Logger::singleton()->error($exception->getMessage()); return false; } } } else { - Shopware()->Pluginlogger()->error('RatePAY: Profile_Request failed!'); + Logger::singleton()->error('RatePAY: Profile_Request failed!'); if (strstr($profileId, '_0RT') == false) { throw new Exception('RatePAY: Profile_Request failed!'); } } } -} \ No newline at end of file +} diff --git a/Component/Service/SessionLoader.php b/Component/Service/SessionLoader.php index b94404a8..54ee2cc1 100644 --- a/Component/Service/SessionLoader.php +++ b/Component/Service/SessionLoader.php @@ -1,10 +1,5 @@ Models()); if (isset($this->session->RatePAY['checkoutShippingAddressId']) && $this->session->RatePAY['checkoutShippingAddressId'] > 0) { $addressModel = Shopware()->Models()->getRepository('Shopware\Models\Customer\Address'); - $checkoutAddressShipping = $addressModel->findOneBy(array('id' => $this->session->RatePAY['checkoutShippingAddressId'] ? $this->session->RatePAY['checkoutShippingAddressId'] : $this->session->RatePAY['checkoutBillingAddressId'])); + $checkoutAddressShipping = $addressModel->findOneBy(['id' => $this->session->RatePAY['checkoutShippingAddressId'] ? $this->session->RatePAY['checkoutShippingAddressId'] : $this->session->RatePAY['checkoutBillingAddressId']]); } else { $checkoutAddressShipping = $customerWrapped->getShipping() !== null ? $customerWrapped->getShipping() : $billing; } return $checkoutAddressShipping; } - + /** * @param \Shopware\Models\Customer\Customer $customer * @return mixed @@ -92,7 +87,7 @@ private function findAddressBilling($customer) if (isset($this->session->RatePAY['checkoutBillingAddressId']) && $this->session->RatePAY['checkoutBillingAddressId'] > 0) { $addressModel = Shopware()->Models()->getRepository('Shopware\Models\Customer\Address'); - $checkoutAddressBilling = $addressModel->findOneBy(array('id' => $this->session->RatePAY['checkoutBillingAddressId'])); + $checkoutAddressBilling = $addressModel->findOneBy(['id' => $this->session->RatePAY['checkoutBillingAddressId']]); } else { $checkoutAddressBilling = $customerWrapped->getBilling(); } @@ -121,7 +116,7 @@ private static function findLangInSession() public function getPaymentRequestData() { - $method = \Shopware_Plugins_Frontend_RpayRatePay_Component_Service_Util::getPaymentMethod( + $method = ShopwareUtil::getPaymentMethod( $this->session->sOrderVariables['sUserData']['additional']['payment']['name'] ); @@ -153,10 +148,10 @@ public function getPaymentRequestData() $shippingTax, $dfpToken, $lang, - $amount); + $amount + ); } - - + public function setInstallmentData($total_amount, $amount, $interest_rate, $interest_amount, $service_charge, $annual_percentage_rate, $monthly_debit_interest, $number_of_rates, $rate, $last_rate, $payment_firstday) { /* Saving Data as example in the Session */ @@ -178,4 +173,4 @@ public function setInstallmentPaymentSubtype($subtype) $this->session->RatePAY['ratenrechner']['payment_firstday'] = $subtype; $this->session->RatePAY['dueDate'] = $subtype; } -} \ No newline at end of file +} diff --git a/Component/Service/Util.php b/Component/Service/ShopwareUtil.php similarity index 89% rename from Component/Service/Util.php rename to Component/Service/ShopwareUtil.php index 7389c974..c93618c9 100755 --- a/Component/Service/Util.php +++ b/Component/Service/ShopwareUtil.php @@ -1,5 +1,8 @@ . */ -class Shopware_Plugins_Frontend_RpayRatePay_Component_Service_Util +class ShopwareUtil { protected $debitPayTypes = [ - '2' => "DIRECT-DEBIT", - '28' => "BANK-TRANSFER", - '2,28' => "FIRSTDAY-SWITCH" + '2' => 'DIRECT-DEBIT', + '28' => 'BANK-TRANSFER', + '2,28' => 'FIRSTDAY-SWITCH' ]; /** @@ -76,6 +79,6 @@ public static function tableHasColumn($table, $column) */ public static function customerCreatesNetOrders(Shopware\Models\Customer\Customer $customer) { - return $customer->getGroup()->getTax() === false; + return $customer->getGroup()->getTax() === false; } -} \ No newline at end of file +} diff --git a/Component/Service/ValidationLib.php b/Component/Service/ValidationLib.php index 2b5f0cea..d990c6c2 100644 --- a/Component/Service/ValidationLib.php +++ b/Component/Service/ValidationLib.php @@ -1,10 +1,5 @@ format('Y-m-d')) !== 0) - { + if (preg_match("/^\d{4}-\d{2}-\d{2}$/", $birthday->format('Y-m-d')) !== 0) { $return = true; } } @@ -66,18 +60,18 @@ public static function isTelephoneNumberSet(Customer $customer) */ public static function areBillingAndShippingSame($billing, $shipping = null) { - $classFunctions = array( + $classFunctions = [ 'getCompany', 'getFirstname', 'getLastName', 'getStreet', 'getZipCode', 'getCity', - ); + ]; if (!is_null($shipping)) { foreach ($classFunctions as $function) { - if (strval(call_user_func(array($billing, $function))) != strval(call_user_func(array($shipping, $function)))) { + if (strval(call_user_func([$billing, $function])) != strval(call_user_func([$shipping, $function]))) { return false; } } @@ -98,8 +92,8 @@ public static function areAmountsValid($b2b, $configData, $totalAmount) return false; } - if ($b2b) { - if ($configData['b2b'] != "1") { //this is a string, for some reason + if ($b2b) { + if ($configData['b2b'] != '1') { //this is a string, for some reason return false; } @@ -108,7 +102,6 @@ public static function areAmountsValid($b2b, $configData, $totalAmount) if ($totalAmount > $b2bmax) { return false; } - } else { if ($totalAmount > $configData['limit_max']) { return false; @@ -117,4 +110,4 @@ public static function areAmountsValid($b2b, $configData, $totalAmount) return true; } -} \ No newline at end of file +} diff --git a/Component/Validation.php b/Component/Validation.php index fac13925..54ef0098 100755 --- a/Component/Validation.php +++ b/Component/Validation.php @@ -2,6 +2,7 @@ use RpayRatePay\Component\Model\ShopwareCustomerWrapper; use RpayRatePay\Component\Service\ValidationLib as ValidationService; + /** * This program is free software; you can redistribute it and/or modify it under the terms of * the GNU General Public License as published by the Free Software Foundation; either @@ -21,7 +22,6 @@ */ class Shopware_Plugins_Frontend_RpayRatePay_Component_Validation { - /** * An Instance of the Shopware-CustomerModel * @@ -29,7 +29,6 @@ class Shopware_Plugins_Frontend_RpayRatePay_Component_Validation */ private $_user; - /** * @var ShopwareCustomerWrapper */ @@ -81,7 +80,8 @@ public function __construct($user, $payment = null, $backend = false) * * @param $currencyStr */ - public function setAllowedCurrencies($currenciesStr) { + public function setAllowedCurrencies($currenciesStr) + { $this->_allowedCurrencies = explode(',', $currenciesStr); } @@ -90,7 +90,8 @@ public function setAllowedCurrencies($currenciesStr) { * * @param $currencyStr */ - public function setAllowedCountriesBilling($countriesStr) { + public function setAllowedCountriesBilling($countriesStr) + { $this->_allowedCountriesBilling = explode(',', $countriesStr); } @@ -99,7 +100,8 @@ public function setAllowedCountriesBilling($countriesStr) { * * @param $currencyStr */ - public function setAllowedCountriesDelivery($countriesStr) { + public function setAllowedCountriesDelivery($countriesStr) + { $this->_allowedCountriesDelivery = explode(',', $countriesStr); } @@ -109,7 +111,7 @@ public function setAllowedCountriesDelivery($countriesStr) { */ public function isRatePAYPayment() { - return in_array($this->_payment->getName(), array("rpayratepayinvoice", "rpayratepayrate", "rpayratepaydebit", "rpayratepayrate0")); + return in_array($this->_payment->getName(), ['rpayratepayinvoice', 'rpayratepayrate', 'rpayratepaydebit', 'rpayratepayrate0']); } /** @@ -120,7 +122,7 @@ public function isRatePAYPayment() */ public function isAgeValid() { - $today = new \DateTime("now"); + $today = new \DateTime('now'); $birthday = $this->_user->getBirthday(); if (empty($birthday) || is_null($birthday)) { @@ -129,8 +131,7 @@ public function isAgeValid() $return = false; if (!is_null($birthday)) { - if ($birthday->diff($today)->y >= 18 && $birthday->diff($today)->y <= 120) - { + if ($birthday->diff($today)->y >= 18 && $birthday->diff($today)->y <= 120) { $return = true; } } @@ -167,10 +168,9 @@ public function isCompanyNameSet() { if (Shopware()->Session()->checkoutBillingAddressId > 0) { // From Shopware 5.2 session contains current billing address $addressModel = Shopware()->Models()->getRepository('Shopware\Models\Customer\Address'); - $checkoutAddressBilling = $addressModel->findOneBy(array('id' => Shopware()->Session()->checkoutBillingAddressId)); + $checkoutAddressBilling = $addressModel->findOneBy(['id' => Shopware()->Session()->checkoutBillingAddressId]); $companyName = $checkoutAddressBilling->getCompany(); } else { - $companyName = $this->userWrapped->getBilling('company'); } @@ -186,14 +186,14 @@ public function isBillingAddressSameLikeShippingAddress() { if (Shopware()->Session()->checkoutBillingAddressId > 0) { // From Shopware 5.2 session contains current billing address $addressModel = Shopware()->Models()->getRepository('Shopware\Models\Customer\Address'); - $billingAddress = $addressModel->findOneBy(array('id' => Shopware()->Session()->checkoutBillingAddressId)); + $billingAddress = $addressModel->findOneBy(['id' => Shopware()->Session()->checkoutBillingAddressId]); } else { $billingAddress = $this->userWrapped->getBilling(); } if (Shopware()->Session()->checkoutShippingAddressId > 0) { // From Shopware 5.2 session contains current shipping address $addressModel = Shopware()->Models()->getRepository('Shopware\Models\Customer\Address'); - $shippingAddress = $addressModel->findOneBy(array('id' => Shopware()->Session()->checkoutShippingAddressId)); + $shippingAddress = $addressModel->findOneBy(['id' => Shopware()->Session()->checkoutShippingAddressId]); } else { $shippingAddress = $this->userWrapped->getShipping(); } @@ -261,11 +261,12 @@ public function isDeliveryCountryValid($country) * @throws \Doctrine\ORM\OptimisticLockException * @throws \Doctrine\ORM\TransactionRequiredException */ - public function isRatepayHidden() { + public function isRatepayHidden() + { $config = Shopware()->Plugins()->Frontend()->RpayRatePay()->Config(); $country = $this->userWrapped->getBillingCountry()->getIso(); - if('DE' === $country || 'AT' === $country || 'CH' === $country) { + if ('DE' === $country || 'AT' === $country || 'CH' === $country) { $sandbox = $config->get('RatePaySandbox' . $country); } @@ -280,5 +281,4 @@ public function getUser() { return $this->_user; } - } diff --git a/Controller/backend/RpayRatepayBackendOrder.php b/Controller/backend/RpayRatepayBackendOrder.php index 00f56ba9..ef1114ba 100755 --- a/Controller/backend/RpayRatepayBackendOrder.php +++ b/Controller/backend/RpayRatepayBackendOrder.php @@ -21,10 +21,10 @@ use RpayRatePay\Component\Mapper\PaymentRequestData; use RpayRatePay\Component\Service\SessionLoader; use RpayRatePay\Component\Service\ConfigLoader; +use RpayRatePay\Component\Service\Logger; class Shopware_Controllers_Backend_RpayRatepayBackendOrder extends Shopware_Controllers_Backend_ExtJs { - /** * @param string $namespace * @param string $name @@ -42,20 +42,21 @@ private function getSnippet($namespace, $name, $default) */ public function setExtendedDataAction() { - Shopware()->Pluginlogger()->info('Now calling setExtendedData'); + Logger::singleton()->info('Now calling setExtendedData'); $params = $this->Request()->getParams(); - $iban = trim($params["iban"]); - $accountNumber = trim($params["accountNumber"]); - $bankCode = trim($params["bankCode"]); - $customerId = $params["customerId"]; + $iban = trim($params['iban']); + $accountNumber = trim($params['accountNumber']); + $bankCode = trim($params['bankCode']); + $customerId = $params['customerId']; $sessionLoader = new SessionLoader(Shopware()->BackendSession()); $sessionLoader->setBankData( $customerId, $accountNumber ? $accountNumber : $iban, - $bankCode, Shopware()->BackendSession() + $bankCode, + Shopware()->BackendSession() ); $this->view->assign([ @@ -95,7 +96,7 @@ private function getInstallmentBuilderFromConfig($paymentMeansName, $addressObj, $configLoader = new ConfigLoader(Shopware()->Db()); //TODO: put magic strings in consts - $nullPercent = $paymentMeansName ==='rpayratepayrate0'; + $nullPercent = $paymentMeansName === 'rpayratepayrate0'; $profileId = $configLoader->getProfileId($countryIso, $shopId, $nullPercent, true); $securityCodeKey = ConfigLoader::getSecurityCodeKey($countryIso, true); @@ -202,7 +203,6 @@ public function getInstallmentPlanAction() $paymentSubtype = $params['paymentSubtype']; - $calcParamSet = !empty($params['value']) && !empty($params['type']); $type = $calcParamSet ? $params['type'] : 'time'; @@ -220,7 +220,7 @@ public function getInstallmentPlanAction() return; } - $plan = json_decode($result, true); + $plan = json_decode($result, true); $sessionLoader = new SessionLoader(Shopware()->BackendSession()); @@ -244,7 +244,6 @@ public function getInstallmentPlanAction() ]); } - public function updatePaymentSubtypeAction() { $params = $this->Request()->getParams(); diff --git a/Controller/backend/RpayRatepayLogging.php b/Controller/backend/RpayRatepayLogging.php index 3fad26bd..8986a457 100755 --- a/Controller/backend/RpayRatepayLogging.php +++ b/Controller/backend/RpayRatepayLogging.php @@ -19,7 +19,6 @@ */ class Shopware_Controllers_Backend_RpayRatepayLogging extends Shopware_Controllers_Backend_ExtJs { - /** * index action is called if no other action is triggered * @@ -27,8 +26,8 @@ class Shopware_Controllers_Backend_RpayRatepayLogging extends Shopware_Controlle */ public function indexAction() { - $this->View()->loadTemplate("backend/rpay_ratepay_logging/app.js"); - $this->View()->assign("title", "RatePAY-Logging"); + $this->View()->loadTemplate('backend/rpay_ratepay_logging/app.js'); + $this->View()->assign('title', 'RatePAY-Logging'); } /** @@ -36,49 +35,49 @@ public function indexAction() */ public function loadStoreAction() { - $start = intval($this->Request()->getParam("start")); - $limit = intval($this->Request()->getParam("limit")); - $orderId = $this->Request()->getParam("orderId"); + $start = intval($this->Request()->getParam('start')); + $limit = intval($this->Request()->getParam('limit')); + $orderId = $this->Request()->getParam('orderId'); if (!is_null($orderId)) { - $transactionId = Shopware()->Db()->fetchOne("SELECT `transactionId` FROM `s_order` WHERE `id`=?", array($orderId)); - $sqlTotal = "SELECT COUNT(*) FROM `rpay_ratepay_logging` WHERE `transactionId`=?"; - $sql = "SELECT log.*, `s_user_billingaddress`.`firstname`,`s_user_billingaddress`.`lastname` FROM `rpay_ratepay_logging` AS `log` " - . "LEFT JOIN `s_order` ON `log`.`transactionId`=`s_order`.`transactionID`" - . "LEFT JOIN `s_user_billingaddress` ON `s_order`.`userID`=`s_user_billingaddress`.`userID`" - . "WHERE `log`.`transactionId`=?" - . "ORDER BY `id` DESC"; - $data = Shopware()->Db()->fetchAll($sql, array($transactionId)); - $total = Shopware()->Db()->fetchOne($sqlTotal, array($transactionId)); - } - else { - $sqlTotal = "SELECT COUNT(*) FROM `rpay_ratepay_logging`"; - $sql = "SELECT log.*, `s_user_billingaddress`.`firstname`,`s_user_billingaddress`.`lastname` FROM `rpay_ratepay_logging` AS `log` " - . "LEFT JOIN `s_order` ON `log`.`transactionId`=`s_order`.`transactionID`" - . "LEFT JOIN `s_user_billingaddress` ON `s_order`.`userID`=`s_user_billingaddress`.`userID`" - . "ORDER BY `id` DESC " + $transactionId = Shopware()->Db()->fetchOne('SELECT `transactionId` FROM `s_order` WHERE `id`=?', [$orderId]); + $sqlTotal = 'SELECT COUNT(*) FROM `rpay_ratepay_logging` WHERE `transactionId`=?'; + $sql = 'SELECT log.*, `s_user_billingaddress`.`firstname`,`s_user_billingaddress`.`lastname` FROM `rpay_ratepay_logging` AS `log` ' + . 'LEFT JOIN `s_order` ON `log`.`transactionId`=`s_order`.`transactionID`' + . 'LEFT JOIN `s_user_billingaddress` ON `s_order`.`userID`=`s_user_billingaddress`.`userID`' + . 'WHERE `log`.`transactionId`=?' + . 'ORDER BY `id` DESC'; + $data = Shopware()->Db()->fetchAll($sql, [$transactionId]); + $total = Shopware()->Db()->fetchOne($sqlTotal, [$transactionId]); + } else { + $sqlTotal = 'SELECT COUNT(*) FROM `rpay_ratepay_logging`'; + $sql = 'SELECT log.*, `s_user_billingaddress`.`firstname`,`s_user_billingaddress`.`lastname` FROM `rpay_ratepay_logging` AS `log` ' + . 'LEFT JOIN `s_order` ON `log`.`transactionId`=`s_order`.`transactionID`' + . 'LEFT JOIN `s_user_billingaddress` ON `s_order`.`userID`=`s_user_billingaddress`.`userID`' + . 'ORDER BY `id` DESC ' . "LIMIT $start,$limit"; $data = Shopware()->Db()->fetchAll($sql); $total = Shopware()->Db()->fetchOne($sqlTotal); } - $store = array(); + $store = []; foreach ($data as $row) { - $matchesRequest = array(); + $matchesRequest = []; preg_match("/(.*)(<\?.*)/s", $row['request'], $matchesRequest); $row['request'] = $matchesRequest[1] . "\n" . $this->formatXml(trim($matchesRequest[2])); - $matchesResponse = array(); - preg_match("/(.*)(formatXml(trim($matchesResponse[2])); $store[] = $row; } - $this->View()->assign(array( - "data" => $store, - "total" => $total, - "success" => true - ) + $this->View()->assign( + [ + 'data' => $store, + 'total' => $total, + 'success' => true + ] ); } @@ -89,7 +88,7 @@ public function loadStoreAction() */ private function formatXml($xmlString) { - $str = str_replace("\n", "", $xmlString); + $str = str_replace("\n", '', $xmlString); $xml = new DOMDocument('1.0'); $xml->preserveWhiteSpace = false; $xml->formatOutput = true; @@ -148,5 +147,4 @@ public static function getXmlValidationError() return $message; } - } diff --git a/Controller/backend/RpayRatepayOrderDetail.php b/Controller/backend/RpayRatepayOrderDetail.php index a797ba6f..c1366057 100755 --- a/Controller/backend/RpayRatepayOrderDetail.php +++ b/Controller/backend/RpayRatepayOrderDetail.php @@ -1,644 +1,639 @@ . + * + * RpayRatepayOrderDetail + * + * @category RatePAY + * @copyright Copyright (c) 2013 RatePAY GmbH (http://www.ratepay.com) + */ +class Shopware_Controllers_Backend_RpayRatepayOrderDetail extends Shopware_Controllers_Backend_ExtJs +{ + private $_config; + + /** @var Shopware_Plugins_Frontend_RpayRatePay_Component_Mapper_ModelFactory */ + private $_modelFactory; + private $_service; + private $_history; + /** - * This program is free software; you can redistribute it and/or modify it under the terms of - * the GNU General Public License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; - * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - * See the GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License along with this program; - * if not, see . + * index action is called if no other action is triggered * - * RpayRatepayOrderDetail - * - * @category RatePAY - * @copyright Copyright (c) 2013 RatePAY GmbH (http://www.ratepay.com) + * @return void + * @throws \Exception */ - class Shopware_Controllers_Backend_RpayRatepayOrderDetail extends Shopware_Controllers_Backend_ExtJs + public function init() { - - private $_config; - - /** @var Shopware_Plugins_Frontend_RpayRatePay_Component_Mapper_ModelFactory */ - private $_modelFactory; - private $_service; - private $_history; - - /** - * index action is called if no other action is triggered - * - * @return void - * @throws \Exception - */ - public function init() - { - //set correct subshop for backend processes - $orderId = $this->Request()->getParam("orderId"); - if(null !== $orderId) - { - $order = Shopware()->Models()->find('Shopware\Models\Order\Order', $orderId); - - $attributes = $order->getAttribute(); - $backend = (bool)($attributes->getRatepayBackend()); - $netPrices = $order->getNet() === 1; - $this->_modelFactory = new Shopware_Plugins_Frontend_RpayRatePay_Component_Mapper_ModelFactory($this->_config, $backend, $netPrices); - } else { - throw new \Exception('RatepayOrderDetail controller requires parameter orderId'); - //$this->_modelFactory = new Shopware_Plugins_Frontend_RpayRatePay_Component_Mapper_ModelFactory(); - } - $this->_history = new Shopware_Plugins_Frontend_RpayRatePay_Component_History(); + //set correct subshop for backend processes + $orderId = $this->Request()->getParam('orderId'); + if (null !== $orderId) { + $order = Shopware()->Models()->find('Shopware\Models\Order\Order', $orderId); + + $attributes = $order->getAttribute(); + $backend = (bool)($attributes->getRatepayBackend()); + $netPrices = $order->getNet() === 1; + $this->_modelFactory = new Shopware_Plugins_Frontend_RpayRatePay_Component_Mapper_ModelFactory($this->_config, $backend, $netPrices); + } else { + throw new \Exception('RatepayOrderDetail controller requires parameter orderId'); + //$this->_modelFactory = new Shopware_Plugins_Frontend_RpayRatePay_Component_Mapper_ModelFactory(); } + $this->_history = new Shopware_Plugins_Frontend_RpayRatePay_Component_History(); + } - /** - * Initiate the PositionDetails for the given Article in the given Order - */ - public function initPositionsAction() - { - $articleNumbers = json_decode($this->Request()->getParam('articleNumber')); - $orderID = $this->Request()->getParam('orderId'); - $success = true; - $bindings = array($orderID); - $bind = ''; - $values = ''; - foreach (array_unique($articleNumbers) as $articleNumber) { - $sqlCountEntrys = "SELECT `id`, COUNT(*) AS 'count', SUM(`quantity`) AS 'quantity' FROM `s_order_details` " - . "WHERE `orderID`=? " - . "AND `articleordernumber` = ? " - . "ORDER BY `id` ASC"; - try { - $row = Shopware()->Db()->fetchRow($sqlCountEntrys, array($orderID, $articleNumber)); - if ($row['count'] > 1) { // article already in order, update its quantity - $sqlUpdate = "UPDATE `s_order_details` SET `quantity`=? WHERE `id`=?"; - $sqlDelete = "DELETE FROM `s_order_details` WHERE `orderID`=? AND `articleordernumber` = ? AND `id`!=?"; - Shopware()->Db()->query($sqlUpdate, array($row['quantity'], $row['id'])); - Shopware()->Db()->query($sqlDelete, array($orderID, $articleNumber, $row['id'])); - } - else { - $bindings[] = $articleNumber; - $bind .= '?,'; - } - } catch (Exception $exception) { - $success = false; - Shopware()->Pluginlogger()->error('Exception:' . $exception->getMessage()); + /** + * Initiate the PositionDetails for the given Article in the given Order + */ + public function initPositionsAction() + { + $articleNumbers = json_decode($this->Request()->getParam('articleNumber')); + $orderID = $this->Request()->getParam('orderId'); + $success = true; + $bindings = [$orderID]; + $bind = ''; + $values = ''; + foreach (array_unique($articleNumbers) as $articleNumber) { + $sqlCountEntrys = "SELECT `id`, COUNT(*) AS 'count', SUM(`quantity`) AS 'quantity' FROM `s_order_details` " + . 'WHERE `orderID`=? ' + . 'AND `articleordernumber` = ? ' + . 'ORDER BY `id` ASC'; + try { + $row = Shopware()->Db()->fetchRow($sqlCountEntrys, [$orderID, $articleNumber]); + if ($row['count'] > 1) { // article already in order, update its quantity + $sqlUpdate = 'UPDATE `s_order_details` SET `quantity`=? WHERE `id`=?'; + $sqlDelete = 'DELETE FROM `s_order_details` WHERE `orderID`=? AND `articleordernumber` = ? AND `id`!=?'; + Shopware()->Db()->query($sqlUpdate, [$row['quantity'], $row['id']]); + Shopware()->Db()->query($sqlDelete, [$orderID, $articleNumber, $row['id']]); + } else { + $bindings[] = $articleNumber; + $bind .= '?,'; } + } catch (Exception $exception) { + $success = false; + Logger::singleton()->error('Exception:' . $exception->getMessage()); } + } - if (!is_null($bind)) { // add new items to order - $bind = substr($bind, 0, -1); - $sqlSelectIDs = "SELECT `id` FROM `s_order_details` " - . "WHERE `orderID`=? AND `articleordernumber` IN ($bind) "; - try { - $detailIDs = Shopware()->Db()->fetchAll($sqlSelectIDs, $bindings); - foreach ($detailIDs as $row) { - $values .= "(" . $row['id'] . "),"; - } - $values = substr($values, 0, -1); - $sqlInsert = "INSERT INTO `rpay_ratepay_order_positions` " - . "(`s_order_details_id`) " - . "VALUES " . $values; - Shopware()->Db()->query($sqlInsert); - } catch (Exception $exception) { - $success = false; - Shopware()->Pluginlogger()->error('Exception:' . $exception->getMessage(), " SQL:" . $sqlInsert); + if (!is_null($bind)) { // add new items to order + $bind = substr($bind, 0, -1); + $sqlSelectIDs = 'SELECT `id` FROM `s_order_details` ' + . "WHERE `orderID`=? AND `articleordernumber` IN ($bind) "; + try { + $detailIDs = Shopware()->Db()->fetchAll($sqlSelectIDs, $bindings); + foreach ($detailIDs as $row) { + $values .= '(' . $row['id'] . '),'; } + $values = substr($values, 0, -1); + $sqlInsert = 'INSERT INTO `rpay_ratepay_order_positions` ' + . '(`s_order_details_id`) ' + . 'VALUES ' . $values; + Shopware()->Db()->query($sqlInsert); + } catch (Exception $exception) { + $success = false; + Logger::singleton()->error('Exception:' . $exception->getMessage(), ' SQL:' . $sqlInsert); } + } + $this->View()->assign( + [ + 'success' => $success + ] + ); + } - $this->View()->assign( - array( - "success" => $success - ) - ); - } + /** + * Loads the History for the given Order + */ + public function loadHistoryStoreAction() + { + $orderId = $this->Request()->getParam('orderId'); + $history = new Shopware_Plugins_Frontend_RpayRatePay_Component_History(); + $historyData = $history->getHistory($orderId); + $this->View()->assign( + [ + 'data' => $historyData, + 'success' => true + ] + ); + } - /** - * Loads the History for the given Order - */ - public function loadHistoryStoreAction() - { - $orderId = $this->Request()->getParam("orderId"); - $history = new Shopware_Plugins_Frontend_RpayRatePay_Component_History(); - $historyData = $history->getHistory($orderId); - $this->View()->assign( - array( - "data" => $historyData, - "success" => true - ) - ); + /** + * This Action loads the data from the datebase into the backendview + */ + public function loadPositionStoreAction() + { + $orderId = $this->Request()->getParam('orderId'); + $zero = $this->Request()->getParam('setToZero'); + $data = $this->getFullBasket($orderId); + $positions = []; + if ($zero) { + foreach ($data as $row) { + $row['quantityDeliver'] = 0; + $row['quantityReturn'] = 0; + $positions[] = $row; + } + } else { + $positions = $data; } + $total = Shopware()->Db()->fetchOne('SELECT count(*) FROM `s_order_details` WHERE `s_order_details`.`orderID`=?;', [$orderId]); + + $this->View()->assign( + [ + 'data' => $positions, + 'total' => $total, + 'success' => true + ] + ); + } - /** - * This Action loads the data from the datebase into the backendview - */ - public function loadPositionStoreAction() - { - $orderId = $this->Request()->getParam("orderId"); - $zero = $this->Request()->getParam("setToZero"); - $data = $this->getFullBasket($orderId); - $positions = array(); - if ($zero) { - foreach ($data as $row) { - $row['quantityDeliver'] = 0; - $row['quantityReturn'] = 0; - $positions[] = $row; + /** + * Delivers the given Items and assigns the result to the backend + */ + public function deliverItemsAction() + { + $orderId = $this->Request()->getParam('orderId'); + $items = json_decode($this->Request()->getParam('items')); + $orderModel = Shopware()->Models()->getRepository('Shopware\Models\Order\Order'); + $order = $orderModel->findOneBy(['id' => $orderId]); + + $payment = $order->getPayment()->getName(); + $this->_modelFactory->setTransactionId($order->getTransactionID()); + $this->_modelFactory->setOrderId($order->getNumber()); + $itemsToDeliver = null; + + $sendItem = true; + foreach ($items as $item) { + $itemsToDeliver += $item->deliveredItems; + + if ($payment == 'rpayratepayrate0' || $payment == 'rpayratepayrate') { + if (($item->maxQuantity - $item->deliveredItems - $item->cancelled - $item->retournedItems - $item->delivered) !== 0) { + $itemsToDeliver += $item->delivered; + $sendItem = false; } } - else { - $positions = $data; - } - $total = Shopware()->Db()->fetchOne("SELECT count(*) FROM `s_order_details` WHERE `s_order_details`.`orderID`=?;", array($orderId)); - - $this->View()->assign(array( - "data" => $positions, - "total" => $total, - "success" => true - ) - ); } - /** - * Delivers the given Items and assigns the result to the backend - */ - public function deliverItemsAction() - { - $orderId = $this->Request()->getParam("orderId"); - $items = json_decode($this->Request()->getParam("items")); - $orderModel = Shopware()->Models()->getRepository('Shopware\Models\Order\Order'); - $order = $orderModel->findOneBy(array('id' => $orderId)); - - $payment = $order->getPayment()->getName(); - $this->_modelFactory->setTransactionId($order->getTransactionID()); - $this->_modelFactory->setOrderId($order->getNumber()); - $itemsToDeliver = null; + if ($itemsToDeliver > 0) { + $operationData['orderId'] = $orderId; + $operationData['method'] = $payment; + $operationData['items'] = $items; + $result = false; + + if ($sendItem == true) { + $result = $this->_modelFactory->callRequest('ConfirmationDeliver', $operationData); + } - $sendItem = true; - foreach ($items as $item) { - $itemsToDeliver += $item->deliveredItems; + if ($result === true || $sendItem == false) { + foreach ($items as $item) { + $bind = [ + 'delivered' => $item->delivered + $item->deliveredItems + ]; + $this->updateItem($orderId, $item->articlenumber, $bind); + if ($item->quantity <= 0) { + continue; + } - if ($payment == 'rpayratepayrate0' || $payment == 'rpayratepayrate') { - if (($item->maxQuantity - $item->deliveredItems - $item->cancelled - $item->retournedItems - $item->delivered) !== 0) { - $itemsToDeliver += $item->delivered; - $sendItem = false; + if ($sendItem == true) { + $this->_history->logHistory($orderId, 'Artikel wurde versand.', $item->name, $item->articlenumber, $item->quantity); + } else { + $this->_history->logHistory($orderId, 'Artikel wurde für versand vorbereitet.', $item->name, $item->articlenumber, $item->quantity); } } } - if ($itemsToDeliver > 0) { - $operationData['orderId'] = $orderId; - $operationData['method'] = $payment; - $operationData['items'] = $items; - $result = false; + $this->setNewOrderState($orderId, 'delivery'); + $this->View()->assign( + [ + 'result' => $result, + 'success' => true + ] + ); + } else { + $this->View()->assign( + [ + 'success' => false + ] + ); + } + } - if ($sendItem == true) { - $result = $this->_modelFactory->callRequest('ConfirmationDeliver', $operationData); - } + /** + * Cancel the given Items and returns the result to the backend + */ + public function cancelItemsAction() + { + $orderId = $this->Request()->getParam('orderId'); + $items = json_decode($this->Request()->getParam('items')); + $orderModel = Shopware()->Models()->getRepository('Shopware\Models\Order\Order'); + $order = $orderModel->findOneBy(['id' => $orderId]); + $this->_modelFactory->setTransactionId($order->getTransactionID()); + $itemsToCancel = null; + + foreach ($items as $item) { + // count all item which are in cancellation process + $itemsToCancel += $item->cancelledItems; + + /* + * Why a continue at the end of a loop + * if ($item->quantity <= 0) { + continue; + }*/ + } - if ($result === true || $sendItem == false) { - foreach ($items as $item) { - $bind = array( - 'delivered' => $item->delivered + $item->deliveredItems - ); - $this->updateItem($orderId, $item->articlenumber, $bind); - if ($item->quantity <= 0) { - continue; - } - - if ($sendItem == true) { - $this->_history->logHistory($orderId, "Artikel wurde versand.", $item->name, $item->articlenumber, $item->quantity); - } else { - $this->_history->logHistory($orderId, "Artikel wurde für versand vorbereitet.", $item->name, $item->articlenumber, $item->quantity); - } + //only call the logic if there are items to cancel + if ($itemsToCancel > 0) { + $operationData['orderId'] = $orderId; + $operationData['items'] = $items; + $operationData['subtype'] = 'cancellation'; + $this->_modelFactory->setOrderId($order->getNumber()); + $result = $this->_modelFactory->callRequest('PaymentChange', $operationData); + + if ($result === true) { + foreach ($items as $item) { + $bind = [ + 'cancelled' => $item->cancelled + $item->cancelledItems + ]; + $this->updateItem($orderId, $item->articlenumber, $bind); + if ($item->cancelledItems <= 0) { + continue; } - } - $this->setNewOrderState($orderId, 'delivery'); - $this->View()->assign(array( - "result" => $result, - "success" => true - ) - ); - } else { - $this->View()->assign(array( - "success" => false - ) - ); + if ($this->Request()->getParam('articleStock') == 1) { + $this->_updateArticleStock($item->articlenumber, $item->cancelledItems); + } + + $this->_history->logHistory($orderId, 'Artikel wurde storniert.', $item->name, $item->articlenumber, $item->cancelledItems); + } } + $this->setNewOrderState($orderId, 'cancellation'); + $this->View()->assign( + [ + 'result' => $result, + 'success' => true + ] + ); + } else { + $this->View()->assign( + [ + 'success' => false + ] + ); } + } - /** - * Cancel the given Items and returns the result to the backend - */ - public function cancelItemsAction() - { - $orderId = $this->Request()->getParam("orderId"); - $items = json_decode($this->Request()->getParam("items")); - $orderModel = Shopware()->Models()->getRepository('Shopware\Models\Order\Order'); - $order = $orderModel->findOneBy(array('id' => $orderId)); - $this->_modelFactory->setTransactionId($order->getTransactionID()); - $itemsToCancel = null; - - foreach ($items as $item) { - // count all item which are in cancellation process - $itemsToCancel += $item->cancelledItems; - - /* - * Why a continue at the end of a loop - * if ($item->quantity <= 0) { - continue; - }*/ + /** + * returns the given Items and returns the result to the backend + */ + public function returnItemsAction() + { + $orderId = $this->Request()->getParam('orderId'); + $items = json_decode($this->Request()->getParam('items')); + $orderModel = Shopware()->Models()->getRepository('Shopware\Models\Order\Order'); + $order = $orderModel->findOneBy(['id' => $orderId]); + $this->_modelFactory->setTransactionId($order->getTransactionID()); + $itemsToReturn = null; + + foreach ($items as $item) { + // count all item which are in returning process + $itemsToReturn += $item->returnedItems; + if ($item->quantity <= 0) { + continue; } + } - //only call the logic if there are items to cancel - if($itemsToCancel > 0) { - $operationData['orderId'] = $orderId; - $operationData['items'] = $items; - $operationData['subtype'] = 'cancellation'; - $this->_modelFactory->setOrderId($order->getNumber()); - $result = $this->_modelFactory->callRequest('PaymentChange', $operationData); + //only call the logic if there are items to return + if ($itemsToReturn > 0) { + $operationData['orderId'] = $orderId; + $operationData['items'] = $items; + $operationData['subtype'] = 'return'; + $this->_modelFactory->setOrderId($order->getNumber()); + $result = $this->_modelFactory->callRequest('PaymentChange', $operationData); + + if ($result === true) { + foreach ($items as $item) { + $bind = [ + 'returned' => $item->returned + $item->returnedItems + ]; + $this->updateItem($orderId, $item->articlenumber, $bind); + if ($item->returnedItems <= 0) { + continue; + } - if ($result === true) { - foreach ($items as $item) { - $bind = array( - 'cancelled' => $item->cancelled + $item->cancelledItems - ); - $this->updateItem($orderId, $item->articlenumber, $bind); - if ($item->cancelledItems <= 0) { - continue; - } - - if ($this->Request()->getParam('articleStock') == 1) { - $this->_updateArticleStock($item->articlenumber, $item->cancelledItems); - } - - $this->_history->logHistory($orderId, "Artikel wurde storniert.", $item->name, $item->articlenumber, $item->cancelledItems); + if ($this->Request()->getParam('articleStock') == 1) { + $this->_updateArticleStock($item->articlenumber, $item->returnedItems); } + + $this->_history->logHistory($orderId, 'Artikel wurde retourniert.', $item->name, $item->articlenumber, $item->returnedItems); } - $this->setNewOrderState($orderId, 'cancellation'); - $this->View()->assign(array( - "result" => $result, - "success" => true - ) - ); - } - else - { - $this->View()->assign(array( - "success" => false - ) - ); } + $this->setNewOrderState($orderId, 'return'); + + $this->View()->assign( + [ + 'result' => $result, + 'success' => true + ] + ); + } else { + $this->View()->assign( + [ + 'success' => false + ] + ); } + } - /** - * returns the given Items and returns the result to the backend - */ - public function returnItemsAction() - { - $orderId = $this->Request()->getParam("orderId"); - $items = json_decode($this->Request()->getParam("items")); - $orderModel = Shopware()->Models()->getRepository('Shopware\Models\Order\Order'); - $order = $orderModel->findOneBy(array('id' => $orderId)); - $this->_modelFactory->setTransactionId($order->getTransactionID()); - $itemsToReturn = null; - - foreach ($items as $item) { - // count all item which are in returning process - $itemsToReturn += $item->returnedItems; - if ($item->quantity <= 0) { - continue; - } + /** + * Add the given Items to the given order + */ + public function addAction() + { + $onlyDebit = true; + $orderId = $this->Request()->getParam('orderId'); + $insertedIds = json_decode($this->Request()->getParam('insertedIds')); + $subOperation = $this->Request()->getParam('suboperation'); + $order = Shopware()->Db()->fetchRow('SELECT * FROM `s_order` WHERE `id`=?', [$orderId]); + $orderItems = Shopware()->Db()->fetchAll('SELECT *, (`quantity` - `delivered` - `cancelled`) AS `quantityDeliver` FROM `s_order_details` ' + . 'INNER JOIN `rpay_ratepay_order_positions` ON `s_order_details`.`id` = `rpay_ratepay_order_positions`.`s_order_details_id` ' + . 'WHERE `orderID`=?', [$orderId]); + + foreach ($orderItems as $row) { + if ($row['quantityDeliver'] == 0) { + continue; } - //only call the logic if there are items to return - if($itemsToReturn > 0) - { - $operationData['orderId'] = $orderId; - $operationData['items'] = $items; - $operationData['subtype'] = 'return'; - $this->_modelFactory->setOrderId($order->getNumber()); - $result = $this->_modelFactory->callRequest('PaymentChange', $operationData); - - if ($result === true) { - foreach ($items as $item) { - $bind = array( - 'returned' => $item->returned + $item->returnedItems - ); - $this->updateItem($orderId, $item->articlenumber, $bind); - if ($item->returnedItems <= 0) { - continue; - } - - if ($this->Request()->getParam('articleStock') == 1) { - $this->_updateArticleStock($item->articlenumber, $item->returnedItems); - } - - $this->_history->logHistory($orderId, "Artikel wurde retourniert.", $item->name, $item->articlenumber, $item->returnedItems); - } - } - - $this->setNewOrderState($orderId, 'return'); - - $this->View()->assign(array( - "result" => $result, - "success" => true - ) - ); - } else - { - $this->View()->assign(array( - "success" => false - ) - ); + if ((substr($row['articleordernumber'], 0, 5) == 'Debit') + || (substr($row['articleordernumber'], 0, 6) == 'Credit') + ) { + $onlyDebit = false; } + + $items = $row; } - /** - * Add the given Items to the given order - */ - public function addAction() - { - $onlyDebit = true; - $orderId = $this->Request()->getParam("orderId"); - $insertedIds = json_decode($this->Request()->getParam("insertedIds")); - $subOperation = $this->Request()->getParam("suboperation"); - $order = Shopware()->Db()->fetchRow("SELECT * FROM `s_order` WHERE `id`=?", array($orderId)); - $orderItems = Shopware()->Db()->fetchAll("SELECT *, (`quantity` - `delivered` - `cancelled`) AS `quantityDeliver` FROM `s_order_details` " - . "INNER JOIN `rpay_ratepay_order_positions` ON `s_order_details`.`id` = `rpay_ratepay_order_positions`.`s_order_details_id` " - . "WHERE `orderID`=?", array($orderId)); - - foreach ($orderItems as $row) { - if ($row['quantityDeliver'] == 0) { - continue; - } + $shippingRow = $this->getShippingFromDBAsItem($orderId); + if (!is_null($shippingRow) && $shippingRow['quantityDeliver'] != 0) { + $items = $shippingRow; + } - if ((substr($row['articleordernumber'], 0, 5) == 'Debit') - || (substr($row['articleordernumber'], 0, 6) == 'Credit') - ) { - $onlyDebit = false; - } + if ($onlyDebit == false) { + $this->_modelFactory->setTransactionId($order['transactionID']); + $operationData['orderId'] = $orderId; + $operationData['items'] = $items; + $operationData['subtype'] = 'credit'; + $this->_modelFactory->setOrderId($order['ordernumber']); - $items = $row; - } + $rpRate = Shopware()->Db()->fetchRow('SELECT id FROM `s_core_paymentmeans` WHERE `name`=?', ['rpayratepayrate']); + $rpRate0 = Shopware()->Db()->fetchRow('SELECT id FROM `s_core_paymentmeans` WHERE `name`=?', ['rpayratepayrate0']); - $shippingRow = $this->getShippingFromDBAsItem($orderId); - if (!is_null($shippingRow) && $shippingRow['quantityDeliver'] != 0) { - $items = $shippingRow; + if ( + $subOperation === 'debit' && + ($order['paymentID'] == $rpRate['id'] || $order['paymentID'] == $rpRate0['id']) + ) { + $result = false; + } else { + $result = $this->_modelFactory->callRequest('PaymentChange', $operationData); } - if ($onlyDebit == false) { - $this->_modelFactory->setTransactionId($order['transactionID']); - $operationData['orderId'] = $orderId; - $operationData['items'] = $items; - $operationData['subtype'] = 'credit'; - $this->_modelFactory->setOrderId($order['ordernumber']); - - $rpRate = Shopware()->Db()->fetchRow("SELECT id FROM `s_core_paymentmeans` WHERE `name`=?", array('rpayratepayrate')); - $rpRate0 = Shopware()->Db()->fetchRow("SELECT id FROM `s_core_paymentmeans` WHERE `name`=?", array('rpayratepayrate0')); - - if( - $subOperation === 'debit' && - ($order['paymentID'] == $rpRate['id'] || $order['paymentID'] == $rpRate0['id']) - ) { - $result = false; - } else { - $result = $this->_modelFactory->callRequest('PaymentChange', $operationData); - } - - if ($result === true) { - if ($subOperation === 'credit' || $subOperation === 'debit') { - if ($row['price'] > 0) { - $event = 'Nachbelastung wurde hinzugefügt'; - } else { - $event = 'Nachlass wurde hinzugefügt'; - } - $bind = array('delivered' => 1); + if ($result === true) { + if ($subOperation === 'credit' || $subOperation === 'debit') { + if ($row['price'] > 0) { + $event = 'Nachbelastung wurde hinzugefügt'; } else { - $event = 'Artikel wurde hinzugefügt'; + $event = 'Nachlass wurde hinzugefügt'; } + $bind = ['delivered' => 1]; + } else { + $event = 'Artikel wurde hinzugefügt'; + } - foreach ($insertedIds as $id) { - - $newItems = Shopware()->Db()->fetchRow("SELECT * FROM `s_order_details` WHERE `id`=?", array($id)); - $this->updateItem($orderId, $newItems['articleordernumber'], $bind); + foreach ($insertedIds as $id) { + $newItems = Shopware()->Db()->fetchRow('SELECT * FROM `s_order_details` WHERE `id`=?', [$id]); + $this->updateItem($orderId, $newItems['articleordernumber'], $bind); - if ($newItems['quantity'] <= 0) { - continue; - } - $this->_history->logHistory($orderId, $event, $newItems['name'], $newItems['articleordernumber'], $newItems['quantity']); + if ($newItems['quantity'] <= 0) { + continue; } + $this->_history->logHistory($orderId, $event, $newItems['name'], $newItems['articleordernumber'], $newItems['quantity']); } } - - $this->setNewOrderState($orderId); - - $this->View()->assign(array( - "result" => $result, - "success" => true - ) - ); } - /** - * Updates the given binding for the given article - * - * @param string $orderID - * @param string $articleordernumber - * @param array $bind - */ - private function updateItem($orderID, $articleordernumber, $bind) - { - if ($articleordernumber === 'shipping') { - Shopware()->Db()->update('rpay_ratepay_order_shipping', $bind, '`s_order_id`=' . $orderID); - } - else { - $positionId = Shopware()->Db()->fetchOne("SELECT `id` FROM `s_order_details` WHERE `orderID`=? AND `articleordernumber`=?", array($orderID, $articleordernumber)); - Shopware()->Db()->update('rpay_ratepay_order_positions', $bind, '`s_order_details_id`=' . $positionId); - } - } + $this->setNewOrderState($orderId); - /** - * update the stock of an article - * - * @param $article - * @param $count - */ - protected function _updateArticleStock($article, $count) { - $repository = Shopware()->Models()->getRepository('Shopware\Models\Article\Detail'); - $article = $repository->findOneBy(array('number' => $article)); - $article->setInStock($article->getInStock() + $count); - Shopware()->Models()->persist($article); - Shopware()->Models()->flush(); - } + $this->View()->assign( + [ + 'result' => $result, + 'success' => true + ] + ); + } - /** - * Returns the article for the given id - */ - public function getArticleAction() - { - $id = $this->Request()->getParam('id'); - $data = Shopware()->Models()->getRepository('Shopware\Models\Article\Article')->getArticleBaseDataQuery($id)->getArrayResult(); - $data[0]['mainPrices'] = $this->getPrices($data[0]['mainDetail']['id'], $data[0]['tax']); - $this->View()->assign( - array( - "data" => $data[0], - "success" => true - ) - ); + /** + * Updates the given binding for the given article + * + * @param string $orderID + * @param string $articleordernumber + * @param array $bind + */ + private function updateItem($orderID, $articleordernumber, $bind) + { + if ($articleordernumber === 'shipping') { + Shopware()->Db()->update('rpay_ratepay_order_shipping', $bind, '`s_order_id`=' . $orderID); + } else { + $positionId = Shopware()->Db()->fetchOne('SELECT `id` FROM `s_order_details` WHERE `orderID`=? AND `articleordernumber`=?', [$orderID, $articleordernumber]); + Shopware()->Db()->update('rpay_ratepay_order_positions', $bind, '`s_order_details_id`=' . $positionId); } + } - /** - * Returns the Price for the given id - * - * @param string $id - * @param float $tax - * - * @return float - */ - protected function getPrices($id, $tax) - { - $prices = Shopware()->Models()->getRepository('Shopware\Models\Article\Article') - ->getPricesQuery($id) - ->getArrayResult(); - - return $this->formatPricesFromNetToGross($prices, $tax); - } + /** + * update the stock of an article + * + * @param $article + * @param $count + */ + protected function _updateArticleStock($article, $count) + { + $repository = Shopware()->Models()->getRepository('Shopware\Models\Article\Detail'); + $article = $repository->findOneBy(['number' => $article]); + $article->setInStock($article->getInStock() + $count); + Shopware()->Models()->persist($article); + Shopware()->Models()->flush(); + } - /** - * Converts the given data from netto to gross - * - * @param float $prices - * @param float $tax - * - * @return float - */ - protected function formatPricesFromNetToGross($prices, $tax) - { - foreach ($prices as $key => $price) { - $customerGroup = $price['customerGroup']; - if ($customerGroup['taxInput']) { - $price['price'] = $price['price'] / 100 * (100 + $tax['tax']); - $price['pseudoPrice'] = $price['pseudoPrice'] / 100 * (100 + $tax['tax']); - } - $prices[$key] = $price; - } + /** + * Returns the article for the given id + */ + public function getArticleAction() + { + $id = $this->Request()->getParam('id'); + $data = Shopware()->Models()->getRepository('Shopware\Models\Article\Article')->getArticleBaseDataQuery($id)->getArrayResult(); + $data[0]['mainPrices'] = $this->getPrices($data[0]['mainDetail']['id'], $data[0]['tax']); + $this->View()->assign( + [ + 'data' => $data[0], + 'success' => true + ] + ); + } - return $prices; - } + /** + * Returns the Price for the given id + * + * @param string $id + * @param float $tax + * + * @return float + */ + protected function getPrices($id, $tax) + { + $prices = Shopware()->Models()->getRepository('Shopware\Models\Article\Article') + ->getPricesQuery($id) + ->getArrayResult(); - /** - * Returns the Shipping as item for the given order - * - * @param string $orderId - * - * @return array - */ - private function getShippingFromDBAsItem($orderId) - { - $sql = "SELECT " - . "`invoice_shipping` AS `price`, " - . "(1 - `delivered` - `cancelled`) AS `quantityDeliver`, " - . "(`delivered` - `returned`) AS `quantityReturn`, " - . "`delivered`, " - . "`cancelled`, " - . "`returned`, " - . "`s_core_tax`.`tax` AS `tax_rate` " - . "FROM `s_order` " - . "LEFT JOIN `rpay_ratepay_order_shipping` ON `s_order_id`=`s_order`.`id` " - . "LEFT JOIN `s_premium_dispatch` ON `s_order`.`dispatchID`=`s_premium_dispatch`.`id` " - . "LEFT JOIN `s_core_tax` ON `s_premium_dispatch`.`tax_calculation`=`s_core_tax`.`id` " - . "WHERE `s_order`.`id` = ?"; - $shippingRow = Shopware()->Db()->fetchRow($sql, array($orderId)); - if (isset($shippingRow['quantityDeliver'])) { - if ($shippingRow['tax_rate'] == null) { - $shippingRow['tax_rate'] = Shopware()->Db()->fetchOne("SELECT MAX(`tax`) FROM `s_core_tax`"); - } - $shippingRow['quantity'] = 1; - $shippingRow['articleID'] = 0; - $shippingRow['name'] = 'shipping'; - $shippingRow['articleordernumber'] = 'shipping'; + return $this->formatPricesFromNetToGross($prices, $tax); + } - return $shippingRow; + /** + * Converts the given data from netto to gross + * + * @param float $prices + * @param float $tax + * + * @return float + */ + protected function formatPricesFromNetToGross($prices, $tax) + { + foreach ($prices as $key => $price) { + $customerGroup = $price['customerGroup']; + if ($customerGroup['taxInput']) { + $price['price'] = $price['price'] / 100 * (100 + $tax['tax']); + $price['pseudoPrice'] = $price['pseudoPrice'] / 100 * (100 + $tax['tax']); } + $prices[$key] = $price; } - /** - * Returns the whole Basket - * - * @param string $orderId - * - * @return array - */ - private function getFullBasket($orderId) - { - $sql = "SELECT " - . "`articleID`, " - . "`name`, " - . "`articleordernumber`, " - . "`price`, " - . "`quantity`, " - . "(`quantity` - `delivered` - `cancelled`) AS `quantityDeliver`, " - . "(`delivered` - `returned`) AS `quantityReturn`, " - . "`delivered`, " - . "`cancelled`, " - . "`returned`, " - . "`tax_rate` " - . "FROM `s_order_details` AS detail " - . "INNER JOIN `rpay_ratepay_order_positions` AS ratepay ON detail.`id`=ratepay.`s_order_details_id` " - . "WHERE detail.`orderId`=? " - . "ORDER BY detail.`id`;"; - - $data = Shopware()->Db()->fetchAll($sql, array($orderId)); - $shipping = $this->getShippingFromDBAsItem($orderId); - if (!is_null($shipping)) { - $data[] = $shipping; + return $prices; + } + + /** + * Returns the Shipping as item for the given order + * + * @param string $orderId + * + * @return array + */ + private function getShippingFromDBAsItem($orderId) + { + $sql = 'SELECT ' + . '`invoice_shipping` AS `price`, ' + . '(1 - `delivered` - `cancelled`) AS `quantityDeliver`, ' + . '(`delivered` - `returned`) AS `quantityReturn`, ' + . '`delivered`, ' + . '`cancelled`, ' + . '`returned`, ' + . '`s_core_tax`.`tax` AS `tax_rate` ' + . 'FROM `s_order` ' + . 'LEFT JOIN `rpay_ratepay_order_shipping` ON `s_order_id`=`s_order`.`id` ' + . 'LEFT JOIN `s_premium_dispatch` ON `s_order`.`dispatchID`=`s_premium_dispatch`.`id` ' + . 'LEFT JOIN `s_core_tax` ON `s_premium_dispatch`.`tax_calculation`=`s_core_tax`.`id` ' + . 'WHERE `s_order`.`id` = ?'; + $shippingRow = Shopware()->Db()->fetchRow($sql, [$orderId]); + if (isset($shippingRow['quantityDeliver'])) { + if ($shippingRow['tax_rate'] == null) { + $shippingRow['tax_rate'] = Shopware()->Db()->fetchOne('SELECT MAX(`tax`) FROM `s_core_tax`'); } + $shippingRow['quantity'] = 1; + $shippingRow['articleID'] = 0; + $shippingRow['name'] = 'shipping'; + $shippingRow['articleordernumber'] = 'shipping'; - return $data; + return $shippingRow; } + } - /** - * Sets the new Orderstate - * - * @param boolean $orderComplete - */ - private function setNewOrderState($orderId, $operation = null) - { - $sql = "SELECT COUNT((`quantity` - `delivered` - `cancelled`)) AS 'itemsLeft' " - . "FROM `s_order_details` " - . "JOIN `rpay_ratepay_order_positions` ON `s_order_details`.`id` = `rpay_ratepay_order_positions`.`s_order_details_id` " - . "WHERE `orderID`=? AND (`quantity` - `delivered` - `cancelled`) > 0"; - try { - $orderComplete = Shopware()->Db()->fetchOne($sql, array($orderId)); - - if($operation === 'cancellation') - { - $newState = $orderComplete == 0 ? $this->_config['RatePayPartialCancellation'] : $this->_config['RatePayFullCancellation']; - } elseif($operation === 'delivery') { - //only set if order is not partial returned / cancelled - if($orderComplete != $this->_config['RatePayPartialReturn'] && $orderComplete != $this->_config['RatePayPartialCancellation']) - { - $newState = $orderComplete == 0 ? $this->_config['RatePayFullDelivery'] : $this->_config['RatePayPartialDelivery']; - } - } elseif($operation === 'return') { - $newState = $orderComplete == 0 ? $this->_config['RatePayFullReturn']: $this->_config['RatePayFullCancellation']; - } + /** + * Returns the whole Basket + * + * @param string $orderId + * + * @return array + */ + private function getFullBasket($orderId) + { + $sql = 'SELECT ' + . '`articleID`, ' + . '`name`, ' + . '`articleordernumber`, ' + . '`price`, ' + . '`quantity`, ' + . '(`quantity` - `delivered` - `cancelled`) AS `quantityDeliver`, ' + . '(`delivered` - `returned`) AS `quantityReturn`, ' + . '`delivered`, ' + . '`cancelled`, ' + . '`returned`, ' + . '`tax_rate` ' + . 'FROM `s_order_details` AS detail ' + . 'INNER JOIN `rpay_ratepay_order_positions` AS ratepay ON detail.`id`=ratepay.`s_order_details_id` ' + . 'WHERE detail.`orderId`=? ' + . 'ORDER BY detail.`id`;'; + + $data = Shopware()->Db()->fetchAll($sql, [$orderId]); + $shipping = $this->getShippingFromDBAsItem($orderId); + if (!is_null($shipping)) { + $data[] = $shipping; + } - // return if no status update - if(null === $newState) - { - return; + return $data; + } + + /** + * Sets the new Orderstate + * + * @param boolean $orderComplete + */ + private function setNewOrderState($orderId, $operation = null) + { + $sql = "SELECT COUNT((`quantity` - `delivered` - `cancelled`)) AS 'itemsLeft' " + . 'FROM `s_order_details` ' + . 'JOIN `rpay_ratepay_order_positions` ON `s_order_details`.`id` = `rpay_ratepay_order_positions`.`s_order_details_id` ' + . 'WHERE `orderID`=? AND (`quantity` - `delivered` - `cancelled`) > 0'; + try { + $orderComplete = Shopware()->Db()->fetchOne($sql, [$orderId]); + + if ($operation === 'cancellation') { + $newState = $orderComplete == 0 ? $this->_config['RatePayPartialCancellation'] : $this->_config['RatePayFullCancellation']; + } elseif ($operation === 'delivery') { + //only set if order is not partial returned / cancelled + if ($orderComplete != $this->_config['RatePayPartialReturn'] && $orderComplete != $this->_config['RatePayPartialCancellation']) { + $newState = $orderComplete == 0 ? $this->_config['RatePayFullDelivery'] : $this->_config['RatePayPartialDelivery']; } + } elseif ($operation === 'return') { + $newState = $orderComplete == 0 ? $this->_config['RatePayFullReturn'] : $this->_config['RatePayFullCancellation']; + } - Shopware()->Db()->update('s_order', array( - 'status' => $newState - ), '`id`=' . $orderId); - } catch (Exception $exception) { - Shopware()->Pluginlogger()->error($exception->getMessage()); + // return if no status update + if (null === $newState) { + return; } - } + Shopware()->Db()->update('s_order', [ + 'status' => $newState + ], '`id`=' . $orderId); + } catch (Exception $exception) { + Logger::singleton()->error($exception->getMessage()); + } } +} diff --git a/Controller/frontend/RpayRatepay.php b/Controller/frontend/RpayRatepay.php index 6a8dc9f1..15dfc07e 100755 --- a/Controller/frontend/RpayRatepay.php +++ b/Controller/frontend/RpayRatepay.php @@ -1,27 +1,29 @@ . - * - * RpayRatepay - * - * @category RatePAY - * @copyright Copyright (c) 2013 RatePAY GmbH (http://www.ratepay.com) - */ +/** + * This program is free software; you can redistribute it and/or modify it under the terms of + * the GNU General Public License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; + * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along with this program; + * if not, see . + * + * RpayRatepay + * + * @category RatePAY + * @copyright Copyright (c) 2013 RatePAY GmbH (http://www.ratepay.com) + */ use RpayRatePay\Component\Service\SessionLoader; +use RpayRatePay\Component\Service\ShopwareUtil; use Shopware\Components\CSRFWhitelistAware; use RpayRatePay\Component\Service\PaymentProcessor; use RpayRatePay\Component\Model\ShopwareCustomerWrapper; +use RpayRatePay\Component\Service\Logger; class Shopware_Controllers_Frontend_RpayRatepay extends Shopware_Controllers_Frontend_Payment implements CSRFWhitelistAware { @@ -46,21 +48,21 @@ public function init() if (isset($Parameter['userid'])) { $customerId = $Parameter['userid']; - } else if (isset(Shopware()->Session()->sUserId)) { + } elseif (isset(Shopware()->Session()->sUserId)) { $customerId = Shopware()->Session()->sUserId; } if ($customerId === null) { - return "RatePAY frontend controller: No user set"; + return 'RatePAY frontend controller: No user set'; } $customer = Shopware()->Models()->find('Shopware\Models\Customer\Customer', $customerId); - $netPrices = Shopware_Plugins_Frontend_RpayRatePay_Component_Service_Util::customerCreatesNetOrders($customer); + $netPrices = ShopwareUtil::customerCreatesNetOrders($customer); $this->_config = Shopware()->Plugins()->Frontend()->RpayRatePay()->Config(); $this->_modelFactory = new Shopware_Plugins_Frontend_RpayRatePay_Component_Mapper_ModelFactory(null, false, $netPrices); - $this->_logging = new Shopware_Plugins_Frontend_RpayRatePay_Component_Logging(); + $this->_logging = new Shopware_Plugins_Frontend_RpayRatePay_Component_Logging(); } /** @@ -69,42 +71,42 @@ public function init() public function indexAction() { Shopware()->Session()->RatePAY['errorRatenrechner'] = 'false'; - if (preg_match("/^rpayratepay(invoice|rate|debit|rate0)$/", $this->getPaymentShortName())) { + if (preg_match('/^rpayratepay(invoice|rate|debit|rate0)$/', $this->getPaymentShortName())) { if ($this->getPaymentShortName() === 'rpayratepayrate' && !isset(Shopware()->Session()->RatePAY['ratenrechner']) ) { Shopware()->Session()->RatePAY['errorRatenrechner'] = 'true'; $this->redirect( Shopware()->Front()->Router()->assemble( - array( - 'controller' => 'checkout', - 'action' => 'confirm', + [ + 'controller' => 'checkout', + 'action' => 'confirm', 'forceSecure' => true - ) + ] ) ); } elseif ($this->getPaymentShortName() === 'rpayratepayrate0' && !isset(Shopware()->Session()->RatePAY['ratenrechner'])) { Shopware()->Session()->RatePAY['errorRatenrechner'] = 'true'; $this->redirect( Shopware()->Front()->Router()->assemble( - array( - 'controller' => 'checkout', - 'action' => 'confirm', + [ + 'controller' => 'checkout', + 'action' => 'confirm', 'forceSecure' => true - ) + ] ) ); } else { - Shopware()->Pluginlogger()->info('proceed'); + Logger::singleton()->info('proceed'); $this->_proceedPayment(); } } else { $this->redirect( Shopware()->Front()->Router()->assemble( - array( - 'controller' => 'checkout', - 'action' => 'confirm', + [ + 'controller' => 'checkout', + 'action' => 'confirm', 'forceSecure' => true - ) + ] ) ); } @@ -121,12 +123,12 @@ public function saveUserDataAction() $customerModel = Shopware()->Models()->getRepository('Shopware\Models\Customer\Customer'); /** @var Shopware\Models\Customer\Customer $userModel */ - $userModel = $customerModel->findOneBy(array('id' => Shopware()->Session()->sUserId)); - $userWrapped = new ShopwareCustomerWrapper($userModel); + $userModel = $customerModel->findOneBy(['id' => Shopware()->Session()->sUserId]); + $userWrapped = new ShopwareCustomerWrapper($userModel, Shopware()->Models()); if (isset($Parameter['checkoutBillingAddressId']) && !is_null($Parameter['checkoutBillingAddressId'])) { // From Shopware 5.2 current billing address is sent by parameter $addressModel = Shopware()->Models()->getRepository('Shopware\Models\Customer\Address'); - $customerAddressBilling = $addressModel->findOneBy(array('id' => $Parameter['checkoutBillingAddressId'])); + $customerAddressBilling = $addressModel->findOneBy(['id' => $Parameter['checkoutBillingAddressId']]); Shopware()->Session()->RatePAY['checkoutBillingAddressId'] = $Parameter['checkoutBillingAddressId']; if (isset($Parameter['checkoutShippingAddressId']) && !is_null($Parameter['checkoutShippingAddressId'])) { Shopware()->Session()->RatePAY['checkoutShippingAddressId'] = $Parameter['checkoutShippingAddressId']; @@ -138,32 +140,31 @@ public function saveUserDataAction() } $return = 'OK'; - $updateUserData = array(); - $updateAddressData = array(); + $updateUserData = []; + $updateAddressData = []; if (!is_null($customerAddressBilling)) { if (method_exists($customerAddressBilling, 'getBirthday')) { - $updateAddressData['phone'] = $Parameter['ratepay_phone'] ? : $customerAddressBilling->getPhone(); - if ($customerAddressBilling->getCompany() !== "") { - $updateAddressData['company'] = $Parameter['ratepay_company'] ? : $customerAddressBilling->getCompany(); + $updateAddressData['phone'] = $Parameter['ratepay_phone'] ?: $customerAddressBilling->getPhone(); + if ($customerAddressBilling->getCompany() !== '') { + $updateAddressData['company'] = $Parameter['ratepay_company'] ?: $customerAddressBilling->getCompany(); } else { - $updateAddressData['birthday'] = $Parameter['ratepay_dob'] ? : $customerAddressBilling->getBirthday()->format("Y-m-d"); + $updateAddressData['birthday'] = $Parameter['ratepay_dob'] ?: $customerAddressBilling->getBirthday()->format('Y-m-d'); } try { Shopware()->Db()->update('s_user_billingaddress', $updateAddressData, 'userID=' . $Parameter['userid']); // ToDo: Why parameter? - Shopware()->Pluginlogger()->info('Kundendaten aktualisiert.'); + Logger::singleton()->info('Kundendaten aktualisiert.'); } catch (Exception $exception) { - Shopware()->Pluginlogger()->error('Fehler beim Updaten der Userdaten: ' . $exception->getMessage()); + Logger::singleton()->error('Fehler beim Updaten der Userdaten: ' . $exception->getMessage()); $return = 'NOK'; } - } elseif (method_exists($userModel, 'getBirthday')) { // From Shopware 5.2 birthday is moved to customer object - $updateAddressData['phone'] = $Parameter['ratepay_phone'] ? : $customerAddressBilling->getPhone(); + $updateAddressData['phone'] = $Parameter['ratepay_phone'] ?: $customerAddressBilling->getPhone(); if (!is_null($customerAddressBilling->getCompany())) { - $updateAddressData['company'] = $Parameter['ratepay_company'] ? : $customerAddressBilling->getCompany(); + $updateAddressData['company'] = $Parameter['ratepay_company'] ?: $customerAddressBilling->getCompany(); } else { - $updateUserData['birthday'] = $Parameter['ratepay_dob'] ? : $userModel->getBirthday()->format("Y-m-d"); + $updateUserData['birthday'] = $Parameter['ratepay_dob'] ?: $userModel->getBirthday()->format('Y-m-d'); } try { @@ -173,9 +174,9 @@ public function saveUserDataAction() if (count($updateAddressData) > 0) { Shopware()->Db()->update('s_user_addresses', $updateAddressData, 'id=' . $Parameter['checkoutBillingAddressId']); } - Shopware()->Pluginlogger()->info('Kundendaten aktualisiert.'); + Logger::singleton()->info('Kundendaten aktualisiert.'); } catch (Exception $exception) { - Shopware()->Pluginlogger()->error('Fehler beim Updaten der User oder Address daten: ' . $exception->getMessage()); + Logger::singleton()->error('Fehler beim Updaten der User oder Address daten: ' . $exception->getMessage()); $return = 'NOK'; } } else { @@ -201,7 +202,6 @@ public function saveUserDataAction() */ private function _proceedPayment() { - $resultRequest = $this->_modelFactory->callPaymentRequest(); if ($resultRequest->isSuccessful()) { @@ -217,18 +217,18 @@ private function _proceedPayment() if (Shopware()->Session()->sOrderVariables['sBasket']['sShippingcosts'] > 0) { $paymentProcessor->initShipping($order); } - } catch (Exception $exception) { - Shopware()->Pluginlogger()->error($exception->getMessage()); + Logger::singleton()->error($exception->getMessage()); } try { - $paymentProcessor->setOrderAttributes($order, + $paymentProcessor->setOrderAttributes( + $order, $resultRequest, Shopware()->Plugins()->Frontend()->RpayRatePay()->Config()->get('RatePayUseFallbackShippingItem') ); } catch (Exception $exception) { - Shopware()->Pluginlogger()->error($exception->getMessage()); + Logger::singleton()->error($exception->getMessage()); } $paymentProcessor->setPaymentStatusPaid($order); @@ -248,12 +248,12 @@ private function _proceedPayment() * redirect to success page */ $this->redirect( - array( - 'controller' => 'checkout', - 'action' => 'finish', + [ + 'controller' => 'checkout', + 'action' => 'finish', 'sUniqueID' => $uniqueId, 'forceSecure' => true - ) + ] ); } else { $this->_customerMessage = $resultRequest->getCustomerMessage(); @@ -269,7 +269,7 @@ private function _proceedPayment() */ private function _error() { - $this->View()->loadTemplate("frontend/payment_rpay_part/RatePAYErrorpage.tpl"); + $this->View()->loadTemplate('frontend/payment_rpay_part/RatePAYErrorpage.tpl'); $customerMessage = $this->_customerMessage; if (!empty($customerMessage)) { @@ -279,7 +279,7 @@ private function _error() $shopId = Shopware()->Shop()->getId(); $customerModel = Shopware()->Models()->getRepository('Shopware\Models\Customer\Customer'); - $userModel = $customerModel->findOneBy(array('id' => Shopware()->Session()->sUserId)); + $userModel = $customerModel->findOneBy(['id' => Shopware()->Session()->sUserId]); $userModelWrapped = new ShopwareCustomerWrapper($userModel, Shopware()->Models()); $countryBilling = $userModelWrapped->getBillingCountry(); $config = $this->getRatePayPluginConfigByCountry($shopId, $countryBilling); @@ -295,7 +295,8 @@ private function _error() * @param $country * @return array */ - private function getRatePayPluginConfigByCountry($shopId, $country, $backend=false) { + private function getRatePayPluginConfigByCountry($shopId, $country, $backend = false) + { //fetch correct config for current shop based on user country $profileId = Shopware()->Plugins()->Frontend()->RpayRatePay()->Config()->get('RatePayProfileID' . $country->getIso()); @@ -309,9 +310,9 @@ private function getRatePayPluginConfigByCountry($shopId, $country, $backend=fal `shopId` =? AND `profileId`=? - AND + AND backend=? - ', array($shopId, $profileId, $backend)); + ', [$shopId, $profileId, $backend]); } /** @@ -347,5 +348,4 @@ public function getWhitelistedCSRFActions() 'calcRequest' ]; } - } diff --git a/README.md b/README.md index 519e1877..0a5c5f04 100755 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ |------|---------- |Author | Annegret Seufert |Shop Version | `5.0.x` `5.1.x` `5.2.x` `5.3.x` -|Version | `5.2.2` +|Version | `5.2.4` |Link | http://www.ratepay.com |Mail | integration@ratepay.com |Installation | see below @@ -24,6 +24,21 @@ ## Changelog +### Version 5.2.4 - Released 2018-09-13 +* Fix Update Function +* Update Readme +* Fix and Wrap Logging, Should use Container +* Fix Rounding Discrepancies in Shops with Net Prices +* Fix extra indents of code and PSR2 formatting +* Put util in psr4 namespace + +### Version 5.2.3 - Released 2018-08-28 +* Fix tax on shipping item in backend orders +* Improve compatibility with other (payment) modules +* Extend plugin update function to preserve backend credentials +* Fix problems with partial send/cancel/return operations +* Fix payment request error on versions of Shopware earlier than 5.2.0 + ### Version 5.2.2 - Released 2018-08-17 * hotfix cronjob install in older shopware versions fails if entry already exists @@ -35,20 +50,20 @@ * add system-wide support for customer groups with net prices ### Version 5.1.1 - Released 2018-08-08 -* hotfix plugin update function +* hotfix plugin update function ### Version 5.1.0 - Released 2018-08-02 * add compatibility to PHP-7.2 * frontend changes on checkout/payment pages * add setting to handle shipping-item with older API * manage custom attributes via CrudService -* add common getter to identify installment-elv +* add common getter to identify installment-elv ### Version 5.0.7 - Released 2018-07-03 * add complete bidirectionally * add batch processing * refactor Bootstrap -* fix alternative address option +* fix alternative address option ### Version 5.0.6 - Released 2018-05-07 * remove special company name field diff --git a/Tests/Bootstrap.php b/Tests/Bootstrap.php index 5c23deb5..47fe701b 100644 --- a/Tests/Bootstrap.php +++ b/Tests/Bootstrap.php @@ -1,12 +1,3 @@ Loader()->registerNamespace('RpayRatePay', __DIR__ . '/../../'); -Shopware()->Loader()->registerNamespace('RatePAY', __DIR__ . '/../../Component/Library/src/'); \ No newline at end of file +Shopware()->Loader()->registerNamespace('RatePAY', __DIR__ . '/../../Component/Library/src/'); diff --git a/Tests/Functional/Component/Model/ShopwareAddressWrapperTest.php b/Tests/Functional/Component/Model/ShopwareAddressWrapperTest.php index 94ebe3ec..b4b2b493 100644 --- a/Tests/Functional/Component/Model/ShopwareAddressWrapperTest.php +++ b/Tests/Functional/Component/Model/ShopwareAddressWrapperTest.php @@ -7,7 +7,6 @@ class ShopwareAddressWrapperTest extends TestCase { - public function testGetCountry() { $address = $this->getAddressMock(); @@ -41,7 +40,6 @@ private function getAddressMock() $country = Shopware()->Models()->getRepository('Shopware\Models\Country\Country') ->findOneBy(['iso' => 'DE']); - $stub = $this->createMock('Shopware\Models\Customer\Address'); $stub->method('getCountry') @@ -64,4 +62,4 @@ private function getRottenMock($billing) return $stub; } -} \ No newline at end of file +} diff --git a/Tests/Functional/Component/Model/ShopwareCustomerWrapperTest.php b/Tests/Functional/Component/Model/ShopwareCustomerWrapperTest.php index 5068f308..14b26915 100644 --- a/Tests/Functional/Component/Model/ShopwareCustomerWrapperTest.php +++ b/Tests/Functional/Component/Model/ShopwareCustomerWrapperTest.php @@ -7,7 +7,6 @@ class ShopwareCustomerWrapperTest extends TestCase { - public function testGetBilling() { $this->_testGetBilling__fresh(); @@ -64,7 +63,6 @@ private function _testGetBilling__rotten() $billing = $wrapper->getBilling(); $this->assertNotNull($billing->getCountryId()); - } private function _testGetBillingCountry__rotten() @@ -179,7 +177,6 @@ private function getCustomerRottenMock($billingTest = true) $defaultBilling = new \Shopware\Models\Customer\Billing(); $defaultBilling->setPhone('1111111111'); - $country = Shopware()->Models()->getRepository('Shopware\Models\Country\Country') ->findOneBy(['iso' => 'DE']); @@ -194,4 +191,4 @@ private function getCustomerRottenMock($billingTest = true) return $stub; } -} \ No newline at end of file +} diff --git a/Tests/Functional/Component/ValidationTest.php b/Tests/Functional/Component/ValidationTest.php index 9ef18e71..23913cba 100644 --- a/Tests/Functional/Component/ValidationTest.php +++ b/Tests/Functional/Component/ValidationTest.php @@ -1,10 +1,4 @@ markTestSKipped("Method does not have expected behavior."); + $this->markTestSKipped('Method does not have expected behavior.'); $customer = $this->getRandomCustomer(); Shopware()->Session()->sUserId = $customer->getId(); @@ -78,15 +71,14 @@ private function findTurns18Today() private function getRandomCustomer() { - $ids = Shopware()->Models()->getRepository('Shopware\Models\Customer\Customer') + $ids = Shopware()->Models()->getRepository('Shopware\Models\Customer\Customer') ->createQueryBuilder('c') ->select('c.id') ->getQuery() ->getArrayResult(); - shuffle($ids); + shuffle($ids); - return Shopware()->Models()->getRepository('Shopware\Models\Customer\Customer')->find(array_shift($ids)); + return Shopware()->Models()->getRepository('Shopware\Models\Customer\Customer')->find(array_shift($ids)); } - -} \ No newline at end of file +} diff --git a/Tests/Functional/Controller/backend/RpayRatepayLoggingTest.php b/Tests/Functional/Controller/backend/RpayRatepayLoggingTest.php index 9b5adfff..3cc14fa6 100644 --- a/Tests/Functional/Controller/backend/RpayRatepayLoggingTest.php +++ b/Tests/Functional/Controller/backend/RpayRatepayLoggingTest.php @@ -1,10 +1,4 @@ getRandomAddress(); @@ -23,7 +22,6 @@ public function testFilterPayments__returnNullWhenUserEmpty() $this->assertNull($returnNothing); } - public function testFilterPayments__allPaymentTypesTurnedOff() { Shopware()->Session()->sUserId = 1; @@ -66,13 +64,12 @@ private function getPaymentFilterSubscriberMock($configResults) { $mock = $this->getMockBuilder( 'RpayRatePay\Bootstrapping\Events\PaymentFilterSubscriber' - )->setMethods(['getRatePayPluginConfigByCountry',' getValidator']) + )->setMethods(['getRatePayPluginConfigByCountry', ' getValidator']) ->getMock(); $mock->method('getRatePayPluginConfigByCountry') ->willReturn($configResults); - $validatorStub = $this->createMock('Shopware_Plugins_Frontend_RpayRatePay_Component_Validation'); $validatorStub->method('isRatepayHidden') @@ -119,4 +116,4 @@ private function getRandomAddress() return Shopware()->Models()->getRepository($class)->find(array_shift($ids)); } -} \ No newline at end of file +} diff --git a/Tests/Unit/Component/Mapper/BasketArrayBuilderTest.php b/Tests/Unit/Component/Mapper/BasketArrayBuilderTest.php index 2bca9bfc..85635c76 100644 --- a/Tests/Unit/Component/Mapper/BasketArrayBuilderTest.php +++ b/Tests/Unit/Component/Mapper/BasketArrayBuilderTest.php @@ -1,10 +1,5 @@ */ + use RpayRatePay\Component\Service\ShopwareUtil; + $pi_calculator = new PiRatepayRateCalc(); $pi_calculator->unsetData(); @@ -18,7 +20,7 @@ $pi_firstday = $pi_calculator->getRequestFirstday(); if ($pi_config['payment_firstday'] && ! empty($pi_config['payment_firstday'])) { - $serviceUtil = new Shopware_Plugins_Frontend_RpayRatePay_Component_Service_Util(); + $serviceUtil = new ShopwareUtil(); $debitPayType = $serviceUtil->getDebitPayType($pi_config['payment_firstday']); } else { $pi_config['payment_firstday'] = 28; diff --git a/Views/responsive/frontend/payment_rpay_part/index/index.tpl b/Views/responsive/frontend/payment_rpay_part/index/index.tpl index 9c8c8919..22385539 100644 --- a/Views/responsive/frontend/payment_rpay_part/index/index.tpl +++ b/Views/responsive/frontend/payment_rpay_part/index/index.tpl @@ -22,18 +22,19 @@ var messageConsoleLogOk = '{s namespace=RatePAY name=updateUserSuccess}UserDaten erfolgreich aktualisiert.{/s}'; var messageConsoleLogError = '{s namespace=RatePAY name=updateUserSuccess}Fehler beim Aktualisieren der UserDaten. Return: {/s}'; - var ratepayAgeNotValid = false; - var isDebitPayment = false; - var isInstallmentPayment = false; - var ratepayCalcRateError = {$errorRatenrechner}; - {if $sUserData.additional.payment.name == 'rpayratepaydebit' } var isDebitPayment = true; + {else} + var isDebitPayment= false; {/if} {if $sUserData.additional.payment.name == 'rpayratepayinstallment' } var isInstallmentPayment = true; {/if} + var ratepayAgeNotValid = false; + var isInstallmentPayment = false; + var ratepayCalcRateError = isInstallmentPayment && {$errorRatenrechner}; + {if $ratepayValidateisAgeValid != 'true'} var ratepayAgeNotValid = true; {/if} diff --git a/plugin.json b/plugin.json index 1b138f9b..8928d405 100644 --- a/plugin.json +++ b/plugin.json @@ -10,7 +10,7 @@ "author": "RatePAY GmbH", "supplier": "RatePAY GmbH", "description": "

RatePAY Payment plugin for Shopware Community Edition Version 5

  • RatePAY Payment Module
  • Payment means: Invoice, Direct Debit (ELV), Rate
  • Cancellations, Returns, etc. can be created from an additional tab in the order detail view
  • Integrated support for multishops
  • Improved payment form with visual feedback for your customers
  • Supported Languages: German, English
  • Backend Log with custom View accessible from your shop backend
", - "currentVersion": "5.2.3", + "currentVersion": "5.2.4", "payment_confirm": true, "compatibility": { "minimumVersion": "5.0.0",