diff --git a/.github/workflows/codesniffer.yml b/.github/workflows/codesniffer.yml new file mode 100755 index 0000000..675d9de --- /dev/null +++ b/.github/workflows/codesniffer.yml @@ -0,0 +1,15 @@ +name: Codesniffer with the Magento Coding standard +on: [push, pull_request] + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + + - name: Run codesniffer + run: + docker run + --volume $(pwd)/:/app/workdir + michielgerritsen/magento-coding-standard:latest + --severity=6 diff --git a/.github/workflows/linting.yml b/.github/workflows/linting.yml new file mode 100755 index 0000000..fcfafed --- /dev/null +++ b/.github/workflows/linting.yml @@ -0,0 +1,45 @@ +name: Lint PHP files +on: [push, pull_request] + +jobs: + php-71: + runs-on: ubuntu-latest + steps: + - uses: StephaneBour/actions-php-lint@7.1 + with: + dir: './' + + php-72: + runs-on: ubuntu-latest + steps: + - uses: StephaneBour/actions-php-lint@7.2 + with: + dir: './' + + php-73: + runs-on: ubuntu-latest + steps: + - uses: StephaneBour/actions-php-lint@7.3 + with: + dir: './' + + php-74: + runs-on: ubuntu-latest + steps: + - uses: StephaneBour/actions-php-lint@7.4 + with: + dir: './' + + php-80: + runs-on: ubuntu-latest + steps: + - uses: StephaneBour/actions-php-lint@8.0 + with: + dir: './' + + php-81: + runs-on: ubuntu-latest + steps: + - uses: StephaneBour/actions-php-lint@8.1 + with: + dir: './' diff --git a/.github/workflows/phpstan.yml b/.github/workflows/phpstan.yml new file mode 100755 index 0000000..edeaf80 --- /dev/null +++ b/.github/workflows/phpstan.yml @@ -0,0 +1,32 @@ +name: phpstan +on: [pull_request] + +jobs: + build: + strategy: + matrix: + include: + - PHP_VERSION: php81-fpm + MAGENTO_VERSION: 2.4.4 + + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v1 + + - name: Start Docker + run: docker run --detach --name magento-project-community-edition michielgerritsen/magento-project-community-edition:${{ matrix.PHP_VERSION }}-magento${{ matrix.MAGENTO_VERSION }} + + - name: Create branch for Composer and remove version from composer.json + run: git checkout -b continuous-integration-test-branch && sed -i '/version/d' ./composer.json + + - name: Upload our code into the docker container + run: docker cp $(pwd) magento-project-community-edition:/data/extensions/ + + - name: Install the extensions in Magento + run: docker exec magento-project-community-edition composer require magmodules/magento2-bewustbezorgd:dev-continuous-integration-test-branch + + - name: Activate the extension + run: docker exec magento-project-community-edition bash -c "php bin/magento module:enable Thuiswinkel_BewustBezorgd && php bin/magento setup:upgrade && php bin/magento setup:di:compile" + + - name: Run PHPStan + run: docker exec magento-project-community-edition /bin/bash -c "./vendor/bin/phpstan analyse --no-progress -c /data/extensions/*/phpstan.neon /data/extensions" \ No newline at end of file diff --git a/.github/workflows/setup-di-compile.yml b/.github/workflows/setup-di-compile.yml new file mode 100755 index 0000000..8565509 --- /dev/null +++ b/.github/workflows/setup-di-compile.yml @@ -0,0 +1,27 @@ +name: Run setup:upgrade and setup:di:compile +on: [pull_request] + +jobs: + build: + strategy: + matrix: + include: + - PHP_VERSION: php73-fpm + MAGENTO_VERSION: 2.3.7 + - PHP_VERSION: php81-fpm + MAGENTO_VERSION: 2.4.4 + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + + - name: Start Docker + run: PHP_VERSION=${{ matrix.PHP_VERSION }} MAGENTO_VERSION=magento${{ matrix.MAGENTO_VERSION }} docker-compose -f .github/workflows/templates/docker-compose.yml up -d + + - name: Create branch for Composer and remove version from composer.json + run: git checkout -b continuous-integration-test-branch && sed -i '/version/d' ./composer.json + + - name: Upload the code into the docker container + run: docker cp $(pwd) magento-project-community-edition:/data/extensions/ && docker exec magento-project-community-edition composer require magmodules/magento2-bewustbezorgd:dev-continuous-integration-test-branch + + - name: Activate the extension and run setup:upgrade and setup:di:compile + run: docker exec magento-project-community-edition bash -c "php bin/magento module:enable Thuiswinkel_BewustBezorgd && php bin/magento setup:upgrade && php bin/magento setup:di:compile" diff --git a/.github/workflows/templates/docker-compose.yml b/.github/workflows/templates/docker-compose.yml new file mode 100644 index 0000000..bd555ba --- /dev/null +++ b/.github/workflows/templates/docker-compose.yml @@ -0,0 +1,18 @@ +version: '3' + +services: + db: + image: mysql:5.7 + environment: + MYSQL_ROOT_PASSWORD: root_password + MYSQL_DATABASE: magento-test + MYSQL_USER: magento + MYSQL_PASSWORD: magento + MYSQL_SQL_TO_RUN: 'GRANT ALL ON *.* TO "root"@"%";' + web: + image: michielgerritsen/magento-project-community-edition:${PHP_VERSION}-${MAGENTO_VERSION} + container_name: magento-project-community-edition + depends_on: + - db + volumes: + - ./:/data/extensions/workdir \ No newline at end of file diff --git a/.gitignore b/.gitignore old mode 100644 new mode 100755 diff --git a/Api/Config/RepositoryInterface.php b/Api/Config/RepositoryInterface.php new file mode 100755 index 0000000..627139d --- /dev/null +++ b/Api/Config/RepositoryInterface.php @@ -0,0 +1,139 @@ +allowedMethod = $allowedMethod; } diff --git a/Block/Adminhtml/Config/Form/Field/ServiceTypeMapping.php b/Block/Adminhtml/Config/Form/Field/ServiceTypeMapping.php old mode 100644 new mode 100755 index 761a173..d5aba64 --- a/Block/Adminhtml/Config/Form/Field/ServiceTypeMapping.php +++ b/Block/Adminhtml/Config/Form/Field/ServiceTypeMapping.php @@ -3,6 +3,7 @@ * Copyright © Thuiswinkel.org. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Thuiswinkel\BewustBezorgd\Block\Adminhtml\Config\Form\Field; @@ -16,6 +17,13 @@ class ServiceTypeMapping extends AbstractFieldArray { + private const RENDERER_DATA = [ + 'data' => [ + 'is_render_to_js_template' => true, + 'class' => 'input-text required-entry validate-no-empty', + ], + ]; + /** @var AllowedMethods */ private $allowedMethodRenderer; @@ -81,12 +89,7 @@ private function getAllowedMethodRenderer() $this->allowedMethodRenderer = $this->getLayout()->createBlock( AllowedMethods::class, '', - [ - 'data' => [ - 'is_render_to_js_template' => true, - 'class' => 'input-text required-entry validate-no-empty', - ], - ] + self::RENDERER_DATA ); } @@ -105,12 +108,7 @@ private function getServiceTypeRenderer() $this->serviceTypeRenderer = $this->getLayout()->createBlock( ServiceTypes::class, '', - [ - 'data' => [ - 'is_render_to_js_template' => true, - 'class' => 'input-text required-entry validate-no-empty', - ], - ] + self::RENDERER_DATA ); } diff --git a/Block/Adminhtml/Config/Form/Field/ServiceTypes.php b/Block/Adminhtml/Config/Form/Field/ServiceTypes.php old mode 100644 new mode 100755 index 9d3912c..6c0b86b --- a/Block/Adminhtml/Config/Form/Field/ServiceTypes.php +++ b/Block/Adminhtml/Config/Form/Field/ServiceTypes.php @@ -3,6 +3,7 @@ * Copyright © Thuiswinkel.org. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Thuiswinkel\BewustBezorgd\Block\Adminhtml\Config\Form\Field; @@ -23,8 +24,11 @@ class ServiceTypes extends Select * @param ServiceType $serviceType * @param array $data */ - public function __construct(Context $context, ServiceType $serviceType, array $data = []) - { + public function __construct( + Context $context, + ServiceType $serviceType, + array $data = [] + ) { parent::__construct($context, $data); $this->serviceType = $serviceType; } diff --git a/Block/Adminhtml/Render/Header.php b/Block/Adminhtml/Render/Header.php old mode 100644 new mode 100755 index fbd0b41..a3298f3 --- a/Block/Adminhtml/Render/Header.php +++ b/Block/Adminhtml/Render/Header.php @@ -3,6 +3,7 @@ * Copyright © Thuiswinkel.org. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Thuiswinkel\BewustBezorgd\Block\Adminhtml\Render; diff --git a/Block/Adminhtml/System/Config/ValidatePermissions.php b/Block/Adminhtml/System/Config/ValidatePermissions.php old mode 100644 new mode 100755 index 5f5aac5..844ca5a --- a/Block/Adminhtml/System/Config/ValidatePermissions.php +++ b/Block/Adminhtml/System/Config/ValidatePermissions.php @@ -1,10 +1,10 @@ + * Copyright © Thuiswinkel.org. All rights reserved. + * See COPYING.txt for license details. */ +declare(strict_types=1); + namespace Thuiswinkel\BewustBezorgd\Block\Adminhtml\System\Config; use Magento\Config\Block\System\Config\Form\Field; @@ -17,21 +17,21 @@ class ValidatePermissions extends Field * * @var string */ - protected $_apiShopId = 'bewust_bezorgd_api_settings_api_shopid'; + private $_apiShopId = 'bewust_bezorgd_api_settings_api_shopid'; /** * API-Password Field Name * * @var string */ - protected $_apiPassword = 'bewust_bezorgd_api_settings_api_password'; + private $_apiPassword = 'bewust_bezorgd_api_settings_api_password'; /** * Validate VAT Button Label * * @var string */ - protected $_buttonLabel = 'Check Permissions'; + private $_buttonLabel = 'Check Permissions'; /** * Set API-ShopID Field Name diff --git a/COPYING.txt b/COPYING.txt old mode 100644 new mode 100755 diff --git a/Controller/Adminhtml/System/Config/ApiPermissions/Validate.php b/Controller/Adminhtml/System/Config/ApiPermissions/Validate.php old mode 100644 new mode 100755 index 52e8d1f..daf6871 --- a/Controller/Adminhtml/System/Config/ApiPermissions/Validate.php +++ b/Controller/Adminhtml/System/Config/ApiPermissions/Validate.php @@ -1,13 +1,17 @@ getMessage(); } catch (WrongApiCredentialsException $exception) { $result['message'] = $exception->getMessage(); - } catch (ApiAuthenticationFailedException $exception) { - $result['message'] = $exception->getMessage(); } catch (Throwable $exception) { $result['message'] = $exception->getMessage(); } diff --git a/HTTP/Client/Curl.php b/HTTP/Client/Curl.php deleted file mode 100644 index 84ccf49..0000000 --- a/HTTP/Client/Curl.php +++ /dev/null @@ -1,95 +0,0 @@ -sslVersion = $sslVersion; - - parent::__construct($sslVersion); - } - - /** - * @inheritDoc - */ - protected function makeRequest($method, $uri, $params = []) - { - if (!(is_array($params) && isset($params['uploadedFile']))) { - parent::makeRequest($method, $uri, $params); - - return; - } - // @codingStandardsIgnoreStart - $this->_ch = curl_init(); - $this->curlOption(CURLOPT_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS | CURLPROTO_FTP | CURLPROTO_FTPS); - $this->curlOption(CURLOPT_URL, $uri); - $this->curlOption(CURLOPT_POST, 1); - $params['uploadedFile'] = new CURLFile($params['uploadedFile'], 'text/csv'); - $this->curlOption(CURLOPT_POSTFIELDS, $params); - if (count($this->_headers)) { - $heads = []; - foreach ($this->_headers as $k => $v) { - $heads[] = $k . ': ' . $v; - } - $this->curlOption(CURLOPT_HTTPHEADER, $heads); - } - - if (count($this->_cookies)) { - $cookies = []; - foreach ($this->_cookies as $k => $v) { - $cookies[] = "{$k}={$v}"; - } - $this->curlOption(CURLOPT_COOKIE, implode(";", $cookies)); - } - if ($this->_timeout) { - $this->curlOption(CURLOPT_TIMEOUT, $this->_timeout); - } - if ($this->_port != 80) { - $this->curlOption(CURLOPT_PORT, $this->_port); - } - $this->curlOption(CURLOPT_RETURNTRANSFER, 1); - $this->curlOption(CURLOPT_HEADERFUNCTION, [$this, 'parseHeaders']); - - if ($this->sslVersion !== null) { - $this->curlOption(CURLOPT_SSLVERSION, $this->sslVersion); - } - if (count($this->_curlUserOptions)) { - foreach ($this->_curlUserOptions as $k => $v) { - $this->curlOption($k, $v); - } - } - $this->_headerCount = 0; - $this->_responseHeaders = []; - $this->_responseBody = curl_exec($this->_ch); - $err = curl_errno($this->_ch); - - if ($err) { - $this->doError(curl_error($this->_ch)); - } - curl_close($this->_ch); - // @codingStandardsIgnoreEnd - } -} diff --git a/Helper/Data.php b/Helper/Data.php deleted file mode 100644 index 220b2bd..0000000 --- a/Helper/Data.php +++ /dev/null @@ -1,142 +0,0 @@ -configModel = $configModel; - $this->attributeCollectionFactory = $attributeCollectionFactory; - $this->eavConfig = $eavConfig; - $this->shippingConfig = $shippingConfig; - $this->apiLogger = $apiLogger; - $this->dataLogger = $dataLogger; - parent::__construct($context); - } - - /** - * Retrieves attribute IDs from configuration group "Attributes" - * - * @return array - */ - public function getDimensionsAttributeIds() - { - $attributeCodes = $this->configModel->getConfigDimensionsAttributes(); - return $this->attributeCollectionFactory->create() - ->addFieldToFilter(AttributeSet::KEY_ENTITY_TYPE_ID, 4) - ->addFieldToFilter('attribute_code', ['in' => $attributeCodes]) - ->getAllIds(); - } - - /** - * Retrieves default value of attribute "bewustbezorgd_legs" - * - * @return string|null - * @throws \Magento\Framework\Exception\LocalizedException - */ - public function getDefaultBewustbezorgdLegs() - { - /** @var Attribute $attribute */ - $attribute = $this->eavConfig->getAttribute( - Product::ENTITY, - self::ATTRIBUTE_CODE_BEWUSTBEZORGD_LEGS - ); - - return $attribute->getDefaultValue(); - } - - /** - * Retrieves all carriers - * - * @return CarrierInterface[] - */ - public function getCarriers() - { - if (!$this->carriers) { - $carriers = $this->shippingConfig->getAllCarriers(); - - $this->carriers = $carriers; - } - - return $this->carriers; - } - - /** - * Logs data - * - * @param Throwable|array|string $data - * @param string $entity - * @return void - */ - public function log($data, $entity = 'api') - { - if ($entity === 'api') { - $this->apiLogger->add($data->getMessage()); - } elseif ($this->configModel->isDebugMode()) { - $this->dataLogger->add($entity, $data); - } - } -} diff --git a/Logger/Api.php b/Logger/Api.php old mode 100644 new mode 100755 index fb87dff..2b8d313 --- a/Logger/Api.php +++ b/Logger/Api.php @@ -11,13 +11,13 @@ /** * ApiLogger */ -class Api extends Logger implements ApiLoggerInterface +class Api extends Logger { /** - * {@inheritDoc} + * @inheritDoc */ public function add($message) { - $this->addError($message . PHP_EOL . '--------------------' . PHP_EOL); + $this->error($message . PHP_EOL . '--------------------' . PHP_EOL); } } diff --git a/Logger/ApiLoggerInterface.php b/Logger/ApiLoggerInterface.php deleted file mode 100644 index 0fc6bdc..0000000 --- a/Logger/ApiLoggerInterface.php +++ /dev/null @@ -1,19 +0,0 @@ -addInfo($type . ':' . PHP_EOL . json_encode($data) . PHP_EOL . '--------------------' . PHP_EOL); + $this->info($type . ':' . PHP_EOL . json_encode($data) . PHP_EOL . '--------------------' . PHP_EOL); } else { - $this->addInfo($type . ':' . PHP_EOL . $data . PHP_EOL . '--------------------' . PHP_EOL); + $this->info($type . ':' . PHP_EOL . $data . PHP_EOL . '--------------------' . PHP_EOL); } } } diff --git a/Logger/DataLoggerInterface.php b/Logger/DataLoggerInterface.php deleted file mode 100644 index 179b215..0000000 --- a/Logger/DataLoggerInterface.php +++ /dev/null @@ -1,20 +0,0 @@ - 'value1', 'key2' => 'value2', ... 'keyN' => 'valueN'], - * ['key1' => 'value1', 'key2' => 'value2', ... 'keyN' => 'valueN'], - * ... - * ['key1' => 'value1', 'key2' => 'value2', ... 'keyN' => 'valueN'] - * ] - * - * Example output array - * ['key1' => 'value1', 'calculatedKey' => SUM('value'), ... 'keyN' => 'valueN'] - * - * @param array $array - * @param $calculatedKey - * @return array - */ - public function calculateFieldSumByKey(array $array, $calculatedKey); -} diff --git a/Model/CheckoutConfigProvider.php b/Model/CheckoutConfigProvider.php old mode 100644 new mode 100755 index 6180029..dceb199 --- a/Model/CheckoutConfigProvider.php +++ b/Model/CheckoutConfigProvider.php @@ -3,11 +3,13 @@ * Copyright © Thuiswinkel.org. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Thuiswinkel\BewustBezorgd\Model; use Magento\Checkout\Model\ConfigProviderInterface; use Magento\Framework\View\Asset\Repository as AssetRepository; +use Thuiswinkel\BewustBezorgd\Api\Config\RepositoryInterface as Config; class CheckoutConfigProvider implements ConfigProviderInterface { @@ -34,7 +36,7 @@ public function __construct(AssetRepository $assetRepo, Config $modelConfig) */ public function getConfig() { - $config = [ + return [ 'thuiswinkelBewustBezorgd' => [ 'shippingMethods' => [ 'emission_logo_url_svg' => $this->assetRepo @@ -45,7 +47,5 @@ public function getConfig() ] ] ]; - - return $config; } } diff --git a/Model/Config/Backend/ServiceTypeMapping.php b/Model/Config/Backend/ServiceTypeMapping.php old mode 100644 new mode 100755 diff --git a/Model/Config.php b/Model/Config/Repository.php similarity index 67% rename from Model/Config.php rename to Model/Config/Repository.php index 3de12e6..6807f20 100644 --- a/Model/Config.php +++ b/Model/Config/Repository.php @@ -3,70 +3,55 @@ * Copyright © Thuiswinkel.org. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); -namespace Thuiswinkel\BewustBezorgd\Model; +namespace Thuiswinkel\BewustBezorgd\Model\Config; -use Magento\Framework\Serialize\SerializerInterface; -use Magento\Store\Model\ScopeInterface; -use Magento\Framework\App\Config\ScopeConfigInterface; -use Magento\Store\Model\StoreManagerInterface; use Magento\Directory\Helper\Data as DirectoryHelper; +use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Framework\App\State as AppState; +use Magento\Framework\Serialize\SerializerInterface; use Magento\Quote\Model\Quote; -use Thuiswinkel\BewustBezorgd\Logger\DataLoggerInterface - as DataLoggerInterface; +use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\StoreManagerInterface; +use Thuiswinkel\BewustBezorgd\Api\Log\RepositoryInterface as LogRepositoryInterface; +use Thuiswinkel\BewustBezorgd\Api\Config\RepositoryInterface as ConfigRepositoryInterface; /** - * Class Config + * Config repo class */ -class Config +class Repository implements ConfigRepositoryInterface { - /**#@+ - * System configuration path constants - */ - const CONFIG_XML_PATH_ACTIVE = 'bewust_bezorgd/general/active'; - const CONFIG_XML_PATH_GATEWAY_URL = 'bewust_bezorgd/api_settings/gateway_url'; - const CONFIG_XML_PATH_SHOP_ID = 'bewust_bezorgd/api_settings/api_shopid'; - const CONFIG_XML_PATH_PASSWORD = 'bewust_bezorgd/api_settings/api_password'; - const CONFIG_XML_PATH_DEBUG_ENABLED = 'bewust_bezorgd/api_settings/debug'; - const CONFIG_XML_PATH_ALLOWED_COUNTRIES = 'bewust_bezorgd/api_settings/allowed_countries'; - const CONFIG_XML_PATH_CAN_SHOW_LOGO = 'bewust_bezorgd/display_settings/can_show_logo'; - const CONFIG_XML_PATH_SAVE_TO_ORDER = 'bewust_bezorgd/order_settings/save_to_order'; - const CONFIG_XML_PATH_DEFAULT_WEIGHT = 'bewust_bezorgd/default_values/default_weight'; - const CONFIG_XML_PATH_DEFAULT_VOLUME = 'bewust_bezorgd/default_values/default_volume'; - const CONFIG_XML_PATH_SERVICE_TYPES = 'bewust_bezorgd/data_mapping/service_type_mapping'; - const CONFIG_XML_PATH_GROUP_ATTRIBUTES = 'bewust_bezorgd/attributes'; - /**#@-*/ /** @var ScopeConfigInterface */ - protected $scopeConfig; + private $scopeConfig; /** @var StoreManagerInterface */ - protected $storeManager; + private $storeManager; /** @var DirectoryHelper */ - protected $directoryHelper; + private $directoryHelper; /** @var SerializerInterface */ - protected $serializer; + private $serializer; /** @var int */ - protected $storeId; + private $storeId; /** * @var AppState */ - protected $appState; + private $appState; /** * @var Quote */ - protected $quote; + private $quote; /** - * @var DataLoggerInterface + * @var LogRepositoryInterface */ - private $dataLogger; + private $logRepository; /** * Config constructor. @@ -76,7 +61,7 @@ class Config * @param SerializerInterface $serializer * @param AppState $appState * @param Quote $quote - * @param DataLoggerInterface $dataLogger + * @param LogRepositoryInterface $logRepository */ public function __construct( ScopeConfigInterface $scopeConfig, @@ -85,7 +70,7 @@ public function __construct( SerializerInterface $serializer, AppState $appState, Quote $quote, - DataLoggerInterface $dataLogger + LogRepositoryInterface $logRepository ) { $this->scopeConfig = $scopeConfig; $this->storeManager = $storeManager; @@ -93,14 +78,11 @@ public function __construct( $this->serializer = $serializer; $this->appState = $appState; $this->quote = $quote; - $this->dataLogger = $dataLogger; + $this->logRepository = $logRepository; } /** - * Set a specified store ID value - * - * @param int $store - * @return $this + * @inheritDoc */ public function setStoreId($store) { @@ -109,9 +91,7 @@ public function setStoreId($store) } /** - * Validate parameters for correct mass calculation - * - * @return bool + * @inheritDoc */ public function validateMass() { @@ -129,13 +109,13 @@ public function validateMass() if ($length === null || $width === null || $height === null - ){ + ) { return false; } elseif ($length == 0 || $width == 0 || $height == 0 ) { - $this->dataLogger->add('data', "Product volume is null"); + $this->logRepository->addDataLog('data', "Product volume is null"); return false; } } @@ -143,10 +123,7 @@ public function validateMass() } /** - * Check if module is enabled - * - * @return bool - * @api + * @inheritDoc */ public function isEnabled() { @@ -163,9 +140,7 @@ public function isEnabled() } /** - * Retrieves configuration of group "Attributes" - * - * @return array + * @inheritDoc */ public function getConfigDimensionsAttributes() { @@ -177,9 +152,7 @@ public function getConfigDimensionsAttributes() } /** - * Retrieves API gateway URL - * - * @return string + * @inheritDoc */ public function getConfigGatewayUrl() { @@ -191,9 +164,7 @@ public function getConfigGatewayUrl() } /** - * Retrieves API Shop ID - * - * @return string + * @inheritDoc */ public function getConfigApiShopId() { @@ -205,9 +176,7 @@ public function getConfigApiShopId() } /** - * Retrieves API Password - * - * @return string + * @inheritDoc */ public function getConfigApiPassword() { @@ -219,9 +188,7 @@ public function getConfigApiPassword() } /** - * Retrieves default weight from configuration - * - * @return string + * @inheritDoc */ public function getDefaultWeight() { @@ -233,9 +200,7 @@ public function getDefaultWeight() } /** - * Retrieves default volume from configuration - * - * @return string + * @inheritDoc */ public function getDefaultVolume() { @@ -247,9 +212,7 @@ public function getDefaultVolume() } /** - * Retrieves allowed countries from configuration - * - * @return string + * @inheritDoc */ public function getAllowedCountries() { @@ -261,9 +224,7 @@ public function getAllowedCountries() } /** - * Retrieves service types from configuration - * - * @return array + * @inheritDoc */ public function getServiceTypes() { @@ -277,9 +238,7 @@ public function getServiceTypes() } /** - * Retrieves setting "Show BewustBezorgd Icon on Shippingmethods" from configuration - * - * @return bool + * @inheritDoc */ public function canShowLogo() { @@ -291,9 +250,7 @@ public function canShowLogo() } /** - * Retrieves save to order configuration setting - * - * @return bool + * @inheritDoc */ public function saveToOrder() { @@ -305,9 +262,7 @@ public function saveToOrder() } /** - * Retrieves dimensions unit according to selected weight unit - * - * @return string + * @inheritDoc */ public function getDimensionsUnit() { @@ -320,9 +275,7 @@ public function getDimensionsUnit() } /** - * Check if debug mode is enabled - * - * @return bool + * @inheritDoc */ public function isDebugMode() { diff --git a/Model/Config/Source/AllowedMethod.php b/Model/Config/Source/AllowedMethod.php old mode 100644 new mode 100755 index 5f0e70b..26e96c6 --- a/Model/Config/Source/AllowedMethod.php +++ b/Model/Config/Source/AllowedMethod.php @@ -8,6 +8,7 @@ use Magento\Framework\Data\OptionSourceInterface; use Magento\Shipping\Model\Carrier\CarrierInterface; +use Magento\Shipping\Model\Config as ShippingConfig; use Thuiswinkel\BewustBezorgd\Helper\Data as DataHelper; /** @@ -21,12 +22,15 @@ class AllowedMethod implements OptionSourceInterface /** @var array */ private $options = []; + /** @var ShippingConfig */ + private $shippingConfig; + /** - * @param DataHelper $helper + * @param ShippingConfig $shippingConfig */ - public function __construct(DataHelper $helper) + public function __construct(ShippingConfig $shippingConfig) { - $this->helper = $helper; + $this->shippingConfig = $shippingConfig; } /** @@ -37,7 +41,7 @@ public function __construct(DataHelper $helper) public function toOptionArray() { if (!$this->options) { - $carriers = $this->helper->getCarriers(); + $carriers = $this->shippingConfig->getAllCarriers(); $options = []; /** @var CarrierInterface $carrierModel */ diff --git a/Model/Converter.php b/Model/Converter.php deleted file mode 100644 index 42f5d6f..0000000 --- a/Model/Converter.php +++ /dev/null @@ -1,57 +0,0 @@ - 453.59237, - 'kgs' => 1000 - ]; - - /** - * Map for dimension converting - * - * @var array - */ - protected $volumeConvertMap = [ - 'in' => 0.0163871, - 'cm' => 0.001 - ]; - - /** - * Retrieves converted value from the requested unit to kilograms - * - * @param $value - * @param $unit - * @return float|int - */ - public function convertWeightToGrams($value, $unit) - { - return $value * $this->weightConvertMap[$unit]; - } - - /** - * Retrieves converted value from the requested unit to liters - * - * @param $value - * @param $unit - * @return float|int - */ - public function convertVolumeToLiters($value, $unit) - { - return $value * $this->volumeConvertMap[$unit]; - } -} diff --git a/Model/Data/OrderEmission.php b/Model/Data/OrderEmission.php deleted file mode 100644 index 56c0cd2..0000000 --- a/Model/Data/OrderEmission.php +++ /dev/null @@ -1,166 +0,0 @@ -_get(self::ORDER_EMISSION_ID); - } - - /** - * Set Order Emission ID - * - * @param string $orderEmissionId - * @return OrderEmissionInterface - */ - public function setOrderEmissionId($orderEmissionId) - { - return $this->setData(self::ORDER_EMISSION_ID, $orderEmissionId); - } - - /** - * Get Order ID - * - * @return string|null - */ - public function getOrderId() - { - return $this->_get(self::ORDER_ID); - } - - /** - * Set Order ID - * - * @param string $orderId - * @return OrderEmissionInterface - */ - public function setOrderId($orderId) - { - return $this->setData(self::ORDER_ID, $orderId); - } - - /** - * Retrieves existing extension attributes object or create a new one. - * - * @return ExtensionAttributesInterface|OrderEmissionExtensionInterface|null - */ - public function getExtensionAttributes() - { - return $this->_getExtensionAttributes(); - } - - /** - * Set an extension attributes object. - * - * @param OrderEmissionExtensionInterface $extensionAttributes - * @return $this - */ - public function setExtensionAttributes(OrderEmissionExtensionInterface $extensionAttributes) - { - return $this->_setExtensionAttributes($extensionAttributes); - } - - /** - * Get Service Type - * - * @return string|null - */ - public function getServiceType() - { - return $this->_get(self::SERVICE_TYPE); - } - - /** - * Set Service Type - * - * @param string $serviceType - * @return OrderEmissionInterface - */ - public function setServiceType($serviceType) - { - return $this->setData(self::SERVICE_TYPE, $serviceType); - } - - /** - * Get Emission - * - * @return string|null - */ - public function getEmission() - { - return $this->_get(self::EMISSION); - } - - /** - * Set Emission - * - * @param string $emission - * @return OrderEmissionInterface - */ - public function setEmission($emission) - { - return $this->setData(self::EMISSION, $emission); - } - - /** - * Get Meters Diesel - * - * @return string|null - */ - public function getMetersDiesel() - { - return $this->_get(self::METERS_DIESEL); - } - - /** - * Set Meters Diesel - * - * @param string $metersDiesel - * @return OrderEmissionInterface - */ - public function setMetersDiesel($metersDiesel) - { - return $this->setData(self::METERS_DIESEL, $metersDiesel); - } - - /** - * Get Meters Gasoline - * - * @return string|null - */ - public function getMetersGasoline() - { - return $this->_get(self::METERS_GASOLINE); - } - - /** - * Set Meters Gasoline - * - * @param string $metersGasoline - * @return OrderEmissionInterface - */ - public function setMetersGasoline($metersGasoline) - { - return $this->setData(self::METERS_GASOLINE, $metersGasoline); - } -} diff --git a/Model/Emission/CollectorInterface.php b/Model/Emission/CollectorInterface.php deleted file mode 100644 index e5d419d..0000000 --- a/Model/Emission/CollectorInterface.php +++ /dev/null @@ -1,32 +0,0 @@ -data = $data; + $this->api = $api; + } + + /** + * @inheritDoc + */ + public function addApiLog(string $message) + { + $this->api->add($message); + } + + /** + * @inheritDoc + */ + public function addDataLog(string $type, $data) + { + $this->data->add($type, $data); + } +} diff --git a/Model/OrderEmission.php b/Model/OrderEmission.php deleted file mode 100644 index c05c2d0..0000000 --- a/Model/OrderEmission.php +++ /dev/null @@ -1,79 +0,0 @@ -orderEmissionDataFactory = $orderEmissionDataFactory; - $this->dataObjectHelper = $dataObjectHelper; - - parent::__construct($context, $registry, $resource, $resourceCollection, $data); - } - - /** - * Retrieves Order Emission model with Order Emission data - * - * @return OrderEmissionInterface - */ - public function getDataModel() - { - $orderEmissionData = $this->getData(); - - $orderEmissionDataObject = $this->orderEmissionDataFactory->create(); - $this->dataObjectHelper->populateWithArray( - $orderEmissionDataObject, - $orderEmissionData, - OrderEmissionInterface::class - ); - - return $orderEmissionDataObject; - } -} diff --git a/Model/ResourceModel/OrderEmission/Collection.php b/Model/OrderEmission/Collection.php old mode 100644 new mode 100755 similarity index 59% rename from Model/ResourceModel/OrderEmission/Collection.php rename to Model/OrderEmission/Collection.php index e0deeaa..f3d01f1 --- a/Model/ResourceModel/OrderEmission/Collection.php +++ b/Model/OrderEmission/Collection.php @@ -3,12 +3,11 @@ * Copyright © Thuiswinkel.org. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); -namespace Thuiswinkel\BewustBezorgd\Model\ResourceModel\OrderEmission; +namespace Thuiswinkel\BewustBezorgd\Model\OrderEmission; use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection; -use Thuiswinkel\BewustBezorgd\Model\OrderEmission; -use Thuiswinkel\BewustBezorgd\Model\ResourceModel\OrderEmission as ResourceModel; /** * Order Emission Collection @@ -23,6 +22,6 @@ class Collection extends AbstractCollection */ protected function _construct() { - $this->_init(OrderEmission::class, ResourceModel::class); + $this->_init(DataModel::class, ResourceModel::class); } } diff --git a/Model/OrderEmission/DataModel.php b/Model/OrderEmission/DataModel.php new file mode 100755 index 0000000..36ffaff --- /dev/null +++ b/Model/OrderEmission/DataModel.php @@ -0,0 +1,133 @@ +_init(ResourceModel::class); + } + + /** + * @inheritDoc + */ + public function getOrderEmissionId() + { + return $this->getData(self::ORDER_EMISSION_ID); + } + + /** + * @inheritDoc + */ + public function setOrderEmissionId($orderEmissionId) + { + return $this->setData(self::ORDER_EMISSION_ID, $orderEmissionId); + } + + /** + * @inheritDoc + */ + public function getOrderId() + { + return $this->getData(self::ORDER_ID); + } + + /** + * @inheritDoc + */ + public function setOrderId($orderId) + { + return $this->setData(self::ORDER_ID, $orderId); + } + + /** + * @inheritDoc + */ + public function getServiceType() + { + return $this->getData(self::SERVICE_TYPE); + } + + /** + * @inheritDoc + */ + public function setServiceType($serviceType) + { + return $this->setData(self::SERVICE_TYPE, $serviceType); + } + + /** + * @inheritDoc + */ + public function getEmission() + { + return $this->getData(self::EMISSION); + } + + /** + * @inheritDoc + */ + public function setEmission($emission) + { + return $this->setData(self::EMISSION, $emission); + } + + /** + * @inheritDoc + */ + public function getMetersDiesel() + { + return $this->getData(self::METERS_DIESEL); + } + + /** + * @inheritDoc + */ + public function setMetersDiesel($metersDiesel) + { + return $this->setData(self::METERS_DIESEL, $metersDiesel); + } + + /** + * Get Meters Gasoline + * + * @return string|null + */ + public function getMetersGasoline() + { + return $this->getData(self::METERS_GASOLINE); + } + + /** + * @inheritDoc + */ + public function setMetersGasoline($metersGasoline) + { + return $this->setData(self::METERS_GASOLINE, $metersGasoline); + } +} diff --git a/Model/OrderEmission/Repository.php b/Model/OrderEmission/Repository.php new file mode 100755 index 0000000..18fa52d --- /dev/null +++ b/Model/OrderEmission/Repository.php @@ -0,0 +1,156 @@ +searchResultFactory = $searchResultFactory; + $this->collectionFactory = $collectionFactory; + $this->resource = $resource; + $this->dataFactory = $dataFactory; + $this->logger = $logger; + } + + /** + * @inheritDoc + */ + public function create(): DataInterface + { + return $this->dataFactory->create(); + } + + /** + * @inheritDoc + */ + public function getList(SearchCriteriaInterface $searchCriteria): SearchResultsInterface + { + /* @var Collection $collection */ + $collection = $this->collectionFactory->create(); + return $this->searchResultFactory->create() + ->setSearchCriteria($searchCriteria) + ->setItems($collection->getItems()) + ->setTotalCount($collection->getSize()); + } + + /** + * @inheritDoc + */ + public function deleteById(int $entityId): bool + { + $entity = $this->get((int)$entityId); + return $this->delete($entity); + } + + /** + * @inheritDoc + */ + public function get(int $entityId): DataInterface + { + if (!$entityId) { + $exceptionMsg = static::INPUT_EXCEPTION; + throw new InputException(__($exceptionMsg)); + } elseif (!$this->resource->isExists($entityId)) { + $exceptionMsg = self::NO_SUCH_ENTITY_EXCEPTION; + throw new NoSuchEntityException(__($exceptionMsg, $entityId)); + } + return $this->dataFactory->create() + ->load($entityId); + } + + /** + * @inheritDoc + */ + public function delete(DataInterface $entity): bool + { + try { + $this->resource->delete($entity); + } catch (\Exception $exception) { + $this->logger->addDataLog('Delete order emission entity', $exception->getMessage()); + $exceptionMsg = self::COULD_NOT_DELETE_EXCEPTION; + throw new CouldNotDeleteException(__( + $exceptionMsg, + $exception->getMessage() + )); + } + return true; + } + + /** + * @inheritDoc + */ + public function save(DataInterface $entity): DataInterface + { + try { + $this->resource->save($entity); + } catch (\Exception $exception) { + $this->logger->addDataLog('Save order emission entity', $exception->getMessage()); + $exceptionMsg = self::COULD_NOT_SAVE_EXCEPTION; + throw new CouldNotSaveException(__( + $exceptionMsg, + $exception->getMessage() + )); + } + return $entity; + } +} diff --git a/Model/ResourceModel/OrderEmission.php b/Model/OrderEmission/ResourceModel.php old mode 100644 new mode 100755 similarity index 63% rename from Model/ResourceModel/OrderEmission.php rename to Model/OrderEmission/ResourceModel.php index b4e6329..abe17a7 --- a/Model/ResourceModel/OrderEmission.php +++ b/Model/OrderEmission/ResourceModel.php @@ -3,18 +3,19 @@ * Copyright © Thuiswinkel.org. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); -namespace Thuiswinkel\BewustBezorgd\Model\ResourceModel; +namespace Thuiswinkel\BewustBezorgd\Model\OrderEmission; use Magento\Framework\Model\ResourceModel\Db\AbstractDb; /** * Order Emission entity resource model */ -class OrderEmission extends AbstractDb +class ResourceModel extends AbstractDb { - const MAIN_TABLE = 'thuiswinkel_order_emission'; - const ID_FIELD_NAME = 'order_emission_id'; + public const MAIN_TABLE = 'thuiswinkel_order_emission'; + public const ID_FIELD_NAME = 'order_emission_id'; /** * Define resource model diff --git a/Model/OrderEmissionRepository.php b/Model/OrderEmissionRepository.php deleted file mode 100644 index de977c2..0000000 --- a/Model/OrderEmissionRepository.php +++ /dev/null @@ -1,196 +0,0 @@ -resource = $resource; - $this->orderEmissionFactory = $orderEmissionFactory; - $this->orderEmissionCollectionFactory = $orderEmissionCollectionFactory; - $this->searchResultsFactory = $searchResultsFactory; - $this->dataObjectHelper = $dataObjectHelper; - $this->dataOrderEmissionFactory = $dataOrderEmissionFactory; - $this->dataObjectProcessor = $dataObjectProcessor; - $this->storeManager = $storeManager; - $this->collectionProcessor = $collectionProcessor; - $this->extensionAttributesJoinProcessor = $extensionAttributesJoinProcessor; - $this->extensibleDataObjectConverter = $extensibleDataObjectConverter; - } - - /** - * {@inheritdoc} - */ - public function save(OrderEmissionInterface $orderEmission) - { - $orderEmissionData = $this->extensibleDataObjectConverter->toNestedArray( - $orderEmission, - [], - OrderEmissionInterface::class - ); - - $orderEmissionModel = $this->orderEmissionFactory->create()->setData($orderEmissionData); - - try { - $this->resource->save($orderEmissionModel); - } catch (Exception $exception) { - throw new CouldNotSaveException(__( - 'Could not save the orderEmission: %1', - $exception->getMessage() - )); - } - return $orderEmissionModel->getDataModel(); - } - - /** - * {@inheritdoc} - */ - public function getById($orderEmissionId) - { - $orderEmission = $this->orderEmissionFactory->create(); - $this->resource->load($orderEmission, $orderEmissionId); - if (!$orderEmission->getId()) { - throw new NoSuchEntityException(__('OrderEmission with id "%1" does not exist.', $orderEmissionId)); - } - return $orderEmission->getDataModel(); - } - - /** - * {@inheritdoc} - */ - public function getList(SearchCriteriaInterface $criteria) - { - $collection = $this->orderEmissionCollectionFactory->create(); - - $this->extensionAttributesJoinProcessor->process( - $collection, - OrderEmissionInterface::class - ); - - $this->collectionProcessor->process($criteria, $collection); - - $searchResults = $this->searchResultsFactory->create(); - $searchResults->setSearchCriteria($criteria); - - $items = []; - foreach ($collection as $model) { - $items[] = $model->getDataModel(); - } - - $searchResults->setItems($items); - $searchResults->setTotalCount($collection->getSize()); - return $searchResults; - } - - /** - * {@inheritdoc} - */ - public function delete(OrderEmissionInterface $orderEmission) - { - try { - $orderEmissionModel = $this->orderEmissionFactory->create(); - $this->resource->load($orderEmissionModel, $orderEmission->getOrderEmissionId()); - $this->resource->delete($orderEmissionModel); - } catch (Exception $exception) { - throw new CouldNotDeleteException(__( - 'Could not delete the OrderEmission: %1', - $exception->getMessage() - )); - } - return true; - } - - /** - * {@inheritdoc} - */ - public function deleteById($orderEmissionId) - { - return $this->delete($this->getById($orderEmissionId)); - } -} diff --git a/Model/Product/Attribute/Source/BewustbezorgdLegs.php b/Model/Product/Attribute/Source/BewustbezorgdLegs.php old mode 100644 new mode 100755 index dc93a5d..b5b7596 --- a/Model/Product/Attribute/Source/BewustbezorgdLegs.php +++ b/Model/Product/Attribute/Source/BewustbezorgdLegs.php @@ -3,6 +3,7 @@ * Copyright © Thuiswinkel.org. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Thuiswinkel\BewustBezorgd\Model\Product\Attribute\Source; @@ -16,8 +17,8 @@ class BewustbezorgdLegs extends AbstractSource /**#@+ * Constants */ - const TWO_LEGS_OPTION_ID = 1; - const THREE_LEGS_OPTION_ID = 2; + public const TWO_LEGS_OPTION_ID = 1; + public const THREE_LEGS_OPTION_ID = 2; /**#@-*/ /** @@ -37,12 +38,13 @@ class BewustbezorgdLegs extends AbstractSource */ public function getAllOptions() { - $this->_options = [ - ['value' => '', 'label' => __('-- Please select --')], - ['value' => self::TWO_LEGS_OPTION_ID, 'label' => __('2 man delivery | big package')], - ['value' => self::THREE_LEGS_OPTION_ID, 'label' => __('Regular Package')] - ]; - + if (!$this->_options) { + $this->_options = [ + ['value' => '', 'label' => __('-- Please select --')], + ['value' => self::TWO_LEGS_OPTION_ID, 'label' => __('2 man delivery | big package')], + ['value' => self::THREE_LEGS_OPTION_ID, 'label' => __('Regular Package')] + ]; + } return $this->_options; } diff --git a/Model/Data/ShippingEmission.php b/Model/ShippingEmission/Data.php old mode 100644 new mode 100755 similarity index 83% rename from Model/Data/ShippingEmission.php rename to Model/ShippingEmission/Data.php index a700b1c..e41de8a --- a/Model/Data/ShippingEmission.php +++ b/Model/ShippingEmission/Data.php @@ -3,17 +3,18 @@ * Copyright © Thuiswinkel.org. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); -namespace Thuiswinkel\BewustBezorgd\Model\Data; +namespace Thuiswinkel\BewustBezorgd\Model\ShippingEmission; use Magento\Framework\Api\AbstractExtensibleObject; -use Thuiswinkel\BewustBezorgd\Api\Data\ShippingEmissionInterface; -use Thuiswinkel\BewustBezorgd\Api\Data\ShippingEmissionExtensionInterface; +use Magento\Framework\Api\ExtensionAttributesInterface; +use Thuiswinkel\BewustBezorgd\Api\ShippingEmission\DataInterface; /** * Shipping Emission Data Model */ -class ShippingEmission extends AbstractExtensibleObject implements ShippingEmissionInterface +class Data extends AbstractExtensibleObject implements DataInterface { /** * {@inheritDoc} @@ -106,7 +107,7 @@ public function getExtensionAttributes() /** * {@inheritDoc} */ - public function setExtensionAttributes(ShippingEmissionExtensionInterface $extensionAttributes) + public function setExtensionAttributes(ExtensionAttributesInterface $extensionAttributes) { return $this->_setExtensionAttributes($extensionAttributes); } diff --git a/Plugin/Magento/Catalog/Ui/DataProvider/CatalogEavValidationRules.php b/Plugin/Magento/Catalog/Ui/DataProvider/CatalogEavValidationRules.php old mode 100644 new mode 100755 index 21b9a27..4c02437 --- a/Plugin/Magento/Catalog/Ui/DataProvider/CatalogEavValidationRules.php +++ b/Plugin/Magento/Catalog/Ui/DataProvider/CatalogEavValidationRules.php @@ -3,32 +3,51 @@ * Copyright © Thuiswinkel.org. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Thuiswinkel\BewustBezorgd\Plugin\Magento\Catalog\Ui\DataProvider; use Magento\Catalog\Ui\DataProvider\CatalogEavValidationRules as OriginClass; use Magento\Catalog\Api\Data\ProductAttributeInterface; +use Magento\Eav\Model\Entity\Attribute\Set as AttributeSet; use Magento\Shipping\Model\Carrier\CarrierInterface; -use Thuiswinkel\BewustBezorgd\Helper\Data as DataHelper; +use Magento\Shipping\Model\Config as ShippingConfig; +use Thuiswinkel\BewustBezorgd\Api\Config\RepositoryInterface as ConfigModel; +use Magento\Eav\Model\ResourceModel\Entity\Attribute\CollectionFactory as AttributeCollectionFactory; /** * Plugin for Magento\Catalog\Ui\DataProvider\CatalogEavValidationRules */ class CatalogEavValidationRules { - const DIMENSIONS_ATTRIBUTE_ADDITIONAL_VALIDATION_RULE = 'required-entry-if-bewust-bezorgen-three-legs'; + public const DIMENSIONS_ATTRIBUTE_ADDITIONAL_VALIDATION_RULE = 'required-entry-if-bewust-bezorgen-three-legs'; - /** @var DataHelper */ - protected $helper; + /** @var ShippingConfig */ + private $shippingConfig; + /** + * @var ConfigModel + */ + private $configModel; + /** + * @var AttributeCollectionFactory + */ + private $attributeCollectionFactory; /** * Constructor. * - * @param DataHelper $helper + * @param ConfigModel $configModel + * @param ShippingConfig $shippingConfig + * @param AttributeCollectionFactory $attributeCollectionFactory */ - public function __construct(DataHelper $helper) - { - $this->helper = $helper; + public function __construct( + ConfigModel $configModel, + ShippingConfig $shippingConfig, + AttributeCollectionFactory $attributeCollectionFactory + ) { + $this->configModel = $configModel; + $this->shippingConfig = $shippingConfig; + $this->attributeCollectionFactory = $attributeCollectionFactory; } /** @@ -42,10 +61,10 @@ public function __construct(DataHelper $helper) */ public function afterBuild(OriginClass $subject, $result, ProductAttributeInterface $attribute, $data) { - $dimensionsAttributeIds = $this->helper->getDimensionsAttributeIds(); + $dimensionsAttributeIds = $this->getDimensionsAttributeIds(); if (in_array($attribute->getAttributeId(), $dimensionsAttributeIds)) { - $carriers = $this->helper->getCarriers(); + $carriers = $this->shippingConfig->getAllCarriers(); $methods = []; /** @var CarrierInterface $carrierModel */ @@ -57,4 +76,18 @@ public function afterBuild(OriginClass $subject, $result, ProductAttributeInterf return $result; } + + /** + * Retrieves attribute IDs from configuration group "Attributes" + * + * @return array + */ + private function getDimensionsAttributeIds() + { + $attributeCodes = $this->configModel->getConfigDimensionsAttributes(); + return $this->attributeCollectionFactory->create() + ->addFieldToFilter(AttributeSet::KEY_ENTITY_TYPE_ID, 4) + ->addFieldToFilter('attribute_code', ['in' => $attributeCodes]) + ->getAllIds(); + } } diff --git a/Plugin/Magento/Checkout/Model/GuestPaymentInformationManagement.php b/Plugin/Magento/Checkout/Model/GuestPaymentInformationManagement.php old mode 100644 new mode 100755 index be842ed..296b2ce --- a/Plugin/Magento/Checkout/Model/GuestPaymentInformationManagement.php +++ b/Plugin/Magento/Checkout/Model/GuestPaymentInformationManagement.php @@ -3,20 +3,20 @@ * Copyright © Thuiswinkel.org. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Thuiswinkel\BewustBezorgd\Plugin\Magento\Checkout\Model; use Magento\Checkout\Model\GuestPaymentInformationManagement as OriginClass; +use Magento\Checkout\Model\Session; use Magento\Framework\Exception\LocalizedException; -use Magento\Quote\Api\Data\PaymentInterface; +use Magento\Framework\Serialize\SerializerInterface; use Magento\Quote\Api\Data\AddressInterface; +use Magento\Quote\Api\Data\PaymentInterface; use Magento\Sales\Api\OrderRepositoryInterface; -use Magento\Framework\Serialize\SerializerInterface; -use Magento\Checkout\Model\Session; -use Thuiswinkel\BewustBezorgd\Model\OrderEmissionFactory; -use Thuiswinkel\BewustBezorgd\Model\OrderEmissionRepository; -use Thuiswinkel\BewustBezorgd\Model\Config as ConfigModel; -use Thuiswinkel\BewustBezorgd\Helper\Data as DataHelper; +use Thuiswinkel\BewustBezorgd\Api\Config\RepositoryInterface as ConfigModel; +use Thuiswinkel\BewustBezorgd\Api\Log\RepositoryInterface as LogRepository; +use Thuiswinkel\BewustBezorgd\Api\OrderEmission\RepositoryInterface as OrderEmissionRepository; /** * Plugin for Magento\Quote\Model\ShippingMethodManagement @@ -24,25 +24,22 @@ class GuestPaymentInformationManagement { /** @var ConfigModel */ - protected $configModel; + private $configModel; /** @var OrderRepositoryInterface */ - protected $orderRepository; - - /** @var OrderEmissionFactory */ - protected $orderEmissionFactory; + private $orderRepository; /** @var OrderEmissionRepository */ - protected $orderEmissionRepository; + private $orderEmissionRepository; /** @var SerializerInterface */ - protected $serializer; + private $serializer; /** @var Session */ - protected $session; + private $session; - /** @var DataHelper */ - private $dataHelper; + /** @var LogRepository */ + private $logRepository; /** * Constructor @@ -50,28 +47,25 @@ class GuestPaymentInformationManagement * PaymentInformationManagement constructor. * @param ConfigModel $configModel * @param OrderRepositoryInterface $orderRepository - * @param OrderEmissionFactory $orderEmissionFactory * @param OrderEmissionRepository $orderEmissionRepository * @param SerializerInterface $serializer * @param Session $session - * @param DataHelper $dataHelper + * @param LogRepository $logRepository */ public function __construct( ConfigModel $configModel, OrderRepositoryInterface $orderRepository, - OrderEmissionFactory $orderEmissionFactory, OrderEmissionRepository $orderEmissionRepository, SerializerInterface $serializer, Session $session, - DataHelper $dataHelper + LogRepository $logRepository ) { $this->configModel = $configModel; $this->orderRepository = $orderRepository; - $this->orderEmissionFactory = $orderEmissionFactory; $this->orderEmissionRepository = $orderEmissionRepository; $this->serializer = $serializer; $this->session = $session; - $this->dataHelper = $dataHelper; + $this->logRepository = $logRepository; } /** @@ -104,13 +98,13 @@ public function afterSavePaymentInformationAndPlaceOrder( } $order = $this->orderRepository->get($result); $shippingMethod = $order->getShippingMethod(); + $this->logRepository->addDataLog($emissionSessionData, 'SessionData for Guest'); $emissionSessionData = $this->serializer->unserialize($emissionSessionData); - $this->dataHelper->log($emissionSessionData, 'SessionData for Guest'); if (!isset($emissionSessionData[$shippingMethod])) { return $result; } - $orderEmission = $this->orderEmissionFactory->create(); + $orderEmission = $this->orderEmissionRepository->create(); $orderEmission->addData([ 'order_id' => $result, 'service_type' => $emissionSessionData[$shippingMethod]['service_type'], @@ -118,7 +112,7 @@ public function afterSavePaymentInformationAndPlaceOrder( 'meters_diesel' => $emissionSessionData[$shippingMethod]['meters_diesel'], 'meters_gasoline' => $emissionSessionData[$shippingMethod]['meters_gasoline'] ]); - $this->orderEmissionRepository->save($orderEmission->getDataModel()); + $this->orderEmissionRepository->save($orderEmission); return $result; } diff --git a/Plugin/Magento/Checkout/Model/PaymentInformationManagement.php b/Plugin/Magento/Checkout/Model/PaymentInformationManagement.php old mode 100644 new mode 100755 index a9abc42..9546f00 --- a/Plugin/Magento/Checkout/Model/PaymentInformationManagement.php +++ b/Plugin/Magento/Checkout/Model/PaymentInformationManagement.php @@ -3,20 +3,20 @@ * Copyright © Thuiswinkel.org. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Thuiswinkel\BewustBezorgd\Plugin\Magento\Checkout\Model; use Magento\Checkout\Model\PaymentInformationManagement as OriginClass; +use Magento\Checkout\Model\Session; use Magento\Framework\Exception\LocalizedException; -use Magento\Quote\Api\Data\PaymentInterface; +use Magento\Framework\Serialize\SerializerInterface; use Magento\Quote\Api\Data\AddressInterface; +use Magento\Quote\Api\Data\PaymentInterface; use Magento\Sales\Api\OrderRepositoryInterface; -use Magento\Framework\Serialize\SerializerInterface; -use Magento\Checkout\Model\Session; -use Thuiswinkel\BewustBezorgd\Model\OrderEmissionFactory; -use Thuiswinkel\BewustBezorgd\Model\OrderEmissionRepository; -use Thuiswinkel\BewustBezorgd\Model\Config as ConfigModel; -use Thuiswinkel\BewustBezorgd\Helper\Data as DataHelper; +use Thuiswinkel\BewustBezorgd\Api\Config\RepositoryInterface as ConfigModel; +use Thuiswinkel\BewustBezorgd\Api\Log\RepositoryInterface as LogRepository; +use Thuiswinkel\BewustBezorgd\Api\OrderEmission\RepositoryInterface as OrderEmissionRepository; /** * Plugin for Magento\Quote\Model\ShippingMethodManagement @@ -29,9 +29,6 @@ class PaymentInformationManagement /** @var OrderRepositoryInterface */ protected $orderRepository; - /** @var OrderEmissionFactory */ - protected $orderEmissionFactory; - /** @var OrderEmissionRepository */ protected $orderEmissionRepository; @@ -41,8 +38,8 @@ class PaymentInformationManagement /** @var Session */ protected $session; - /** @var DataHelper */ - private $dataHelper; + /** @var LogRepository */ + private $logRepository; /** * Constructor @@ -50,28 +47,25 @@ class PaymentInformationManagement * PaymentInformationManagement constructor. * @param ConfigModel $configModel * @param OrderRepositoryInterface $orderRepository - * @param OrderEmissionFactory $orderEmissionFactory * @param OrderEmissionRepository $orderEmissionRepository * @param SerializerInterface $serializer * @param Session $session - * @param DataHelper $dataHelper + * @param LogRepository $logRepository */ public function __construct( ConfigModel $configModel, OrderRepositoryInterface $orderRepository, - OrderEmissionFactory $orderEmissionFactory, OrderEmissionRepository $orderEmissionRepository, SerializerInterface $serializer, Session $session, - DataHelper $dataHelper + LogRepository $logRepository ) { $this->configModel = $configModel; $this->orderRepository = $orderRepository; - $this->orderEmissionFactory = $orderEmissionFactory; $this->orderEmissionRepository = $orderEmissionRepository; $this->serializer = $serializer; $this->session = $session; - $this->dataHelper = $dataHelper; + $this->logRepository = $logRepository; } /** @@ -101,13 +95,13 @@ public function afterSavePaymentInformationAndPlaceOrder( } $order = $this->orderRepository->get($result); $shippingMethod = $order->getShippingMethod(); + $this->logRepository->addDataLog($emissionSessionData, 'SessionData for registered customer'); $emissionSessionData = $this->serializer->unserialize($emissionSessionData); - $this->dataHelper->log($emissionSessionData, 'SessionData for registered customer'); if (!isset($emissionSessionData[$shippingMethod])) { return $result; } - $orderEmission = $this->orderEmissionFactory->create(); + $orderEmission = $this->orderEmissionRepository->create(); $orderEmission->addData([ 'order_id' => $result, 'service_type' => $emissionSessionData[$shippingMethod]['service_type'], @@ -115,7 +109,7 @@ public function afterSavePaymentInformationAndPlaceOrder( 'meters_diesel' => $emissionSessionData[$shippingMethod]['meters_diesel'], 'meters_gasoline' => $emissionSessionData[$shippingMethod]['meters_gasoline'] ]); - $this->orderEmissionRepository->save($orderEmission->getDataModel()); + $this->orderEmissionRepository->save($orderEmission); return $result; } diff --git a/Plugin/Magento/Framework/View/Element/UiComponent/DataProvider/CollectionFactory.php b/Plugin/Magento/Framework/View/Element/UiComponent/DataProvider/CollectionFactory.php old mode 100644 new mode 100755 index ba33687..46a7c27 --- a/Plugin/Magento/Framework/View/Element/UiComponent/DataProvider/CollectionFactory.php +++ b/Plugin/Magento/Framework/View/Element/UiComponent/DataProvider/CollectionFactory.php @@ -3,13 +3,14 @@ * Copyright © Thuiswinkel.org. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Thuiswinkel\BewustBezorgd\Plugin\Magento\Framework\View\Element\UiComponent\DataProvider; use Magento\Framework\View\Element\UiComponent\DataProvider\CollectionFactory as OriginClass; use Magento\Sales\Model\ResourceModel\Order\Grid\Collection as OrderGridCollection; -use Thuiswinkel\BewustBezorgd\Model\Config as ConfigModel; -use Thuiswinkel\BewustBezorgd\Model\ResourceModel\OrderEmission as EmissionResourceModel; +use Thuiswinkel\BewustBezorgd\Api\Config\RepositoryInterface as ConfigModel; +use Thuiswinkel\BewustBezorgd\Model\OrderEmission\ResourceModel as EmissionResourceModel; /** * Plugin for Magento\Framework\View\Element\UiComponent\DataProvider\CollectionFactory diff --git a/Plugin/Magento/Quote/Model/GuestCart/GuestShippingMethodManagement.php b/Plugin/Magento/Quote/Model/GuestCart/GuestShippingMethodManagement.php old mode 100644 new mode 100755 index 58aa8a3..6ed01bb --- a/Plugin/Magento/Quote/Model/GuestCart/GuestShippingMethodManagement.php +++ b/Plugin/Magento/Quote/Model/GuestCart/GuestShippingMethodManagement.php @@ -3,16 +3,17 @@ * Copyright © Thuiswinkel.org. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Thuiswinkel\BewustBezorgd\Plugin\Magento\Quote\Model\GuestCart; +use Magento\Framework\Exception\FileSystemException; +use Magento\Framework\Exception\NoSuchEntityException; use Magento\Quote\Model\Cart\ShippingMethod; -use Magento\Quote\Model\GuestCart\GuestShippingMethodManagement as OriginClass; use Magento\Quote\Model\GuestCart\GuestCartRepository; -use Magento\Framework\Exception\NoSuchEntityException; -use Magento\Framework\Exception\FileSystemException; +use Magento\Quote\Model\GuestCart\GuestShippingMethodManagement as OriginClass; +use Thuiswinkel\BewustBezorgd\Api\Config\RepositoryInterface as ConfigModel; use Thuiswinkel\BewustBezorgd\Model\Exception\WrongApiConfigurationException; -use Thuiswinkel\BewustBezorgd\Model\Config as ConfigModel; use Thuiswinkel\BewustBezorgd\Plugin\Magento\Quote\Model\ShippingMethodManagement as ShippingMethodManagementPlugin; /** diff --git a/Plugin/Magento/Quote/Model/Quote/Config.php b/Plugin/Magento/Quote/Model/Quote/Config.php old mode 100644 new mode 100755 index 3005b2b..c4f2cd4 --- a/Plugin/Magento/Quote/Model/Quote/Config.php +++ b/Plugin/Magento/Quote/Model/Quote/Config.php @@ -3,11 +3,12 @@ * Copyright © Thuiswinkel.org. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Thuiswinkel\BewustBezorgd\Plugin\Magento\Quote\Model\Quote; use Magento\Quote\Model\Quote\Config as OriginClass; -use Thuiswinkel\BewustBezorgd\Model\Config as ConfigModel; +use Thuiswinkel\BewustBezorgd\Api\Config\RepositoryInterface as ConfigModel; /** * Plugin for Magento\Quote\Model\Quote\Config diff --git a/Plugin/Magento/Quote/Model/ShippingMethodManagement.php b/Plugin/Magento/Quote/Model/ShippingMethodManagement.php old mode 100644 new mode 100755 index 81448b0..522397d --- a/Plugin/Magento/Quote/Model/ShippingMethodManagement.php +++ b/Plugin/Magento/Quote/Model/ShippingMethodManagement.php @@ -3,20 +3,21 @@ * Copyright © Thuiswinkel.org. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Thuiswinkel\BewustBezorgd\Plugin\Magento\Quote\Model; -use Magento\Quote\Model\Cart\ShippingMethod; -use Magento\Quote\Model\ShippingMethodManagement as OriginClass; -use Magento\Quote\Api\CartRepositoryInterface; -use Magento\Quote\Api\Data\CartInterface; use Magento\Customer\Api\AddressRepositoryInterface; -use Magento\Framework\Exception\NoSuchEntityException; -use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Exception\FileSystemException; -use Thuiswinkel\BewustBezorgd\Model\Emission\CollectorInterface; -use Thuiswinkel\BewustBezorgd\Model\Config as ConfigModel; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Quote\Api\CartRepositoryInterface; +use Magento\Quote\Api\Data\CartInterface; +use Magento\Quote\Model\Cart\ShippingMethod; +use Magento\Quote\Model\ShippingMethodManagement as OriginClass; +use Thuiswinkel\BewustBezorgd\Api\Config\RepositoryInterface as ConfigModel; use Thuiswinkel\BewustBezorgd\Model\Exception\WrongApiConfigurationException; +use Thuiswinkel\BewustBezorgd\Service\CollectEmission; /** * Plugin for Magento\Quote\Model\ShippingMethodManagement @@ -36,7 +37,7 @@ class ShippingMethodManagement */ protected $addressRepository; - /** @var CollectorInterface */ + /** @var CollectEmission */ protected $emissionCollector; /** @@ -45,13 +46,13 @@ class ShippingMethodManagement * @param CartRepositoryInterface $quoteRepository * @param ConfigModel $configModel * @param AddressRepositoryInterface $addressRepository - * @param CollectorInterface $emissionCollector + * @param CollectEmission $emissionCollector */ public function __construct( CartRepositoryInterface $quoteRepository, ConfigModel $configModel, AddressRepositoryInterface $addressRepository, - CollectorInterface $emissionCollector + CollectEmission $emissionCollector ) { $this->quoteRepository = $quoteRepository; $this->configModel = $configModel; @@ -70,7 +71,7 @@ public function __construct( * @throws NoSuchEntityException * @throws LocalizedException */ - public function afterEstimateByExtendedAddress(OriginClass $subject, $result, $cartId, $address) + public function afterEstimateByExtendedAddress(OriginClass $subject, $result, $cartId, $address): array { // no change result if module is disabled if (!$this->configModel->isEnabled()) { @@ -97,7 +98,7 @@ public function afterEstimateByExtendedAddress(OriginClass $subject, $result, $c * @throws NoSuchEntityException * @throws LocalizedException */ - public function afterEstimateByAddressId(OriginClass $subject, $result, $cartId, $addressId) + public function afterEstimateByAddressId(OriginClass $subject, $result, $cartId, $addressId): array { $quote = $this->quoteRepository->getActive($cartId); @@ -121,13 +122,11 @@ public function afterEstimateByAddressId(OriginClass $subject, $result, $cartId, * @throws FileSystemException * @throws WrongApiConfigurationException */ - public function afterEstimateProcess(array $result, CartInterface $quote, $address) + public function afterEstimateProcess(array $result, CartInterface $quote, $address): array { // Check if country in address is allowed - if (!in_array($address->getCountryId(), explode(',', $this->configModel->getAllowedCountries()))) { - return $result; - } - $this->emissionCollector->collect($quote, $address, $result); + + $this->emissionCollector->execute($quote, $address, $result); return $result; } diff --git a/Model/ApiConnection.php b/Service/ApiConnection.php old mode 100644 new mode 100755 similarity index 65% rename from Model/ApiConnection.php rename to Service/ApiConnection.php index 2b7a098..4bb7ab4 --- a/Model/ApiConnection.php +++ b/Service/ApiConnection.php @@ -3,23 +3,22 @@ * Copyright © Thuiswinkel.org. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); -namespace Thuiswinkel\BewustBezorgd\Model; +namespace Thuiswinkel\BewustBezorgd\Service; -use Throwable; -use Zend_Date; -use Magento\Framework\App\Filesystem\DirectoryList; use Magento\Framework\HTTP\ClientInterface; -use Magento\Framework\Session\SessionManagerInterface; use Magento\Framework\Serialize\SerializerInterface; +use Magento\Framework\Session\SessionManagerInterface; use Magento\Framework\Stdlib\DateTime\TimezoneInterface; -use Magento\Framework\Filesystem; -use Thuiswinkel\BewustBezorgd\Model\Config as ConfigModel; +use Throwable; +use Thuiswinkel\BewustBezorgd\Api\Log\RepositoryInterface as LogRepository; +use Magento\Framework\HTTP\Client\Curl; +use Thuiswinkel\BewustBezorgd\Api\Config\RepositoryInterface as ConfigModel; +use Thuiswinkel\BewustBezorgd\Model\Exception\ApiAuthenticationFailedException; use Thuiswinkel\BewustBezorgd\Model\Exception\WrongApiConfigurationException; use Thuiswinkel\BewustBezorgd\Model\Exception\WrongApiCredentialsException; -use Thuiswinkel\BewustBezorgd\Model\Exception\ApiAuthenticationFailedException; -use Thuiswinkel\BewustBezorgd\HTTP\Client\Curl; -use Thuiswinkel\BewustBezorgd\Helper\Data as DataHelper; +use Zend_Date; /** * Class ApiConnection @@ -43,21 +42,21 @@ class ApiConnection private $availablePostEndpoints = [ '/api/Account/Token', '/api/Account/Refresh', - '/api/bulk-emission-calculation/two-legs', - '/api/bulk-emission-calculation/three-legs' + '/api/emission-calculation/two-legs', + '/api/emission-calculation/three-legs' ]; /** @var ClientInterface|Curl */ - protected $curlClient; + private $curlClient; /** @var SessionManagerInterface */ - protected $session; + private $session; /** @var SerializerInterface */ - protected $serializer; + private $serializer; /** @var ConfigModel */ - protected $configModel; + private $configModel; /** @var TimezoneInterface */ private $timezone; @@ -68,16 +67,16 @@ class ApiConnection /** @var string|null */ private $bearerTokenExpiry = null; - /** @var Filesystem */ - protected $filesystem; - - protected $helper; + /** + * @var LogRepository + */ + private $logRepository; /** @var string|null */ - protected $apiShopId = null; + private $apiShopId = null; /** @var string|null */ - protected $apiPassword = null; + private $apiPassword = null; /** * Constructor. @@ -87,8 +86,7 @@ class ApiConnection * @param SerializerInterface $serializer * @param ConfigModel $configModel * @param TimezoneInterface $timezone - * @param Filesystem $filesystem - * @param DataHelper $helper + * @param LogRepository $logRepository */ public function __construct( Curl $curlClient, @@ -96,16 +94,14 @@ public function __construct( SerializerInterface $serializer, ConfigModel $configModel, TimezoneInterface $timezone, - Filesystem $filesystem, - DataHelper $helper + LogRepository $logRepository ) { $this->curlClient = $curlClient; $this->session = $session; $this->serializer = $serializer; $this->configModel = $configModel; $this->timezone = $timezone; - $this->filesystem = $filesystem; - $this->helper = $helper; + $this->logRepository = $logRepository; } /** @@ -136,77 +132,65 @@ public function auth() { try { $authEndpoint = $this->getApiEndpoint('/api/Account/Token'); - $this->curlClient->setHeaders($this->headers); - $this->curlClient->addHeader('Content-Type', 'application/json'); - $this->curlClient->post( - $authEndpoint, - $this->serializer->serialize([ + } catch (WrongApiConfigurationException $exception) { + $this->logRepository->addApiLog($exception->getMessage()); + throw $exception; + } + $this->curlClient->setHeaders($this->headers); + $this->curlClient->addHeader('Content-Type', 'application/json'); + $this->curlClient->post( + $authEndpoint, + $this->serializer->serialize([ "id" => $this->getApiShopId(), "password" => $this->getApiPassword() ]) - ); - $response = $this->serializer->unserialize($this->curlClient->getBody()); - - if (count($response['errors'])) { - if ($response['errors'][0]['code'] == 'C0006') { - throw new WrongApiCredentialsException(); - } - throw new ApiAuthenticationFailedException(); + ); + $response = $this->serializer->unserialize($this->curlClient->getBody()); + + if (count($response['errors'])) { + if ($response['errors'][0]['code'] == 'C0006') { + $exception = new WrongApiCredentialsException(); + $this->logRepository->addApiLog($exception->getMessage()); + throw $exception; } - $accessToken = $response['accessToken']; - $accessTokenExpiry = $response['expireDateTimeAccesToken']; - $this->session->setData('thuiswinkel_bewustbezorgd_bearer_token', $accessToken); - $this->bearerToken = $accessToken; - $this->session->setData('thuiswinkel_bewustbezorgd_bearer_token_expiry', $accessTokenExpiry); - $this->bearerTokenExpiry = $accessTokenExpiry; - - return $this->getBearerToken(); - // @codingStandardsIgnoreStart - } catch (WrongApiConfigurationException $exception) { - $this->helper->log($exception); - throw $exception; - } catch (WrongApiCredentialsException $exception) { - $this->helper->log($exception); - throw $exception; - } catch (ApiAuthenticationFailedException $exception) { - $this->helper->log($exception); - } catch (Throwable $exception) { - $this->helper->log($exception); + $exception = new ApiAuthenticationFailedException(); + $this->logRepository->addApiLog($exception->getMessage()); throw $exception; } - // @codingStandardsIgnoreEnd - - return false; + $accessToken = $response['accessToken']; + $accessTokenExpiry = $response['expireDateTimeAccesToken']; + $this->session->setData('thuiswinkel_bewustbezorgd_bearer_token', $accessToken); + $this->bearerToken = $accessToken; + $this->session->setData('thuiswinkel_bewustbezorgd_bearer_token_expiry', $accessTokenExpiry); + $this->bearerTokenExpiry = $accessTokenExpiry; + + return $this->getBearerToken(); } /** * Sends request to Api and retrieves responded data * - * @param $filePath + * @param $data * @param string $endpoint * @return string * @throws Throwable * @throws WrongApiConfigurationException * @throws WrongApiCredentialsException */ - public function getBulkEmission($filePath, $endpoint = 'three-legs') + public function getEmission($data, $endpoint = 'three-legs') { if (!($bearerToken = $this->getBearerToken()) || $this->isBearerTokenExpired()) { $bearerToken = $this->auth(); } - $bulkEndpoint = $this->getApiEndpoint('/api/bulk-emission-calculation/' . $endpoint); - $uploadedFile = $this->filesystem->getDirectoryRead(DirectoryList::VAR_DIR) - ->getAbsolutePath($filePath); - $postData = [ - 'uploadedFile' => $uploadedFile - ]; - $this->curlClient->setHeaders($this->headers); + $endpoint = $this->getApiEndpoint('/api/emission-calculation/' . $endpoint); + $query = '?'; + foreach (reset($data) as $key => $val) { + $query .= str_replace(' ', '', $key) . "=" . $val . '&'; + } $this->curlClient->addHeader('Authorization', 'Bearer ' . $bearerToken); - $this->curlClient->addHeader('Content-Type', 'multipart/form-data'); - $this->curlClient->post($bulkEndpoint, $postData); - $this->helper->log($this->curlClient->getBody(), 'ResponseData'); - - return $this->curlClient->getBody(); + $this->curlClient->get($endpoint . $query); + $this->logRepository->addDataLog($this->curlClient->getBody(), 'ResponseData'); + return $this->serializer->unserialize($this->curlClient->getBody()); } /** diff --git a/Model/Emission/Collector.php b/Service/CollectEmission.php old mode 100644 new mode 100755 similarity index 67% rename from Model/Emission/Collector.php rename to Service/CollectEmission.php index 716b7bf..dcfacaf --- a/Model/Emission/Collector.php +++ b/Service/CollectEmission.php @@ -3,60 +3,83 @@ * Copyright © Thuiswinkel.org. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); -namespace Thuiswinkel\BewustBezorgd\Model\Emission; +namespace Thuiswinkel\BewustBezorgd\Service; -use RuntimeException; -use Throwable; -use Magento\Framework\App\Filesystem\DirectoryList; -use Magento\Quote\Api\Data\CartInterface; -use Magento\Quote\Api\Data\CartItemInterface; +use Magento\Catalog\Model\Product; +use Magento\Catalog\Model\ResourceModel\Eav\Attribute; +use Magento\Checkout\Model\Session; use Magento\Directory\Helper\Data as DirectoryHelper; -use Magento\Framework\Filesystem; +use Magento\Eav\Model\Config as EavConfig; use Magento\Framework\App\Config\ScopeConfigInterface; -use Magento\Store\Model\StoreManagerInterface; -use Magento\Shipping\Model\Config as ShippingConfig; -use Magento\Store\Model\ScopeInterface; -use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Framework\App\Filesystem\DirectoryList; use Magento\Framework\Exception\FileSystemException; use Magento\Framework\Exception\LocalizedException; -use Magento\Quote\Api\Data\ShippingMethodExtensionFactory; -use Magento\Quote\Model\Cart\ShippingMethod; -use Magento\Quote\Api\Data\ShippingMethodExtensionInterface; -use Magento\Checkout\Model\Session; -use Magento\Framework\Serialize\SerializerInterface; +use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Framework\Filesystem; use Magento\Framework\Filter\FilterManager; use Magento\Framework\Filter\TruncateFilter\Result; -use Thuiswinkel\BewustBezorgd\Helper\Data as DataHelper; -use Thuiswinkel\BewustBezorgd\Model\Config as ConfigModel; -use Thuiswinkel\BewustBezorgd\Model\Exception\ApiAuthenticationFailedException; +use Magento\Framework\Serialize\SerializerInterface; +use Magento\Quote\Api\Data\CartInterface; +use Magento\Quote\Api\Data\CartItemInterface; +use Magento\Quote\Api\Data\ShippingMethodExtensionFactory; +use Magento\Quote\Api\Data\ShippingMethodExtensionInterface; +use Magento\Quote\Model\Cart\ShippingMethod; +use Magento\Shipping\Model\Config as ShippingConfig; +use Magento\Store\Model\ScopeInterface; +use Magento\Store\Model\StoreManagerInterface; +use RuntimeException; +use Throwable; +use Thuiswinkel\BewustBezorgd\Api\Log\RepositoryInterface as LogRepository; +use Thuiswinkel\BewustBezorgd\Service\ApiConnection; +use Thuiswinkel\BewustBezorgd\Api\Config\RepositoryInterface as ConfigModel; use Thuiswinkel\BewustBezorgd\Model\Exception\WrongApiConfigurationException; use Thuiswinkel\BewustBezorgd\Model\Exception\WrongApiCredentialsException; use Thuiswinkel\BewustBezorgd\Model\Product\Attribute\Source\BewustbezorgdLegs as BewustbezorgdLegsAttributeSource; -use Thuiswinkel\BewustBezorgd\Model\ApiConnection; -use Thuiswinkel\BewustBezorgd\Model\Converter; -use Thuiswinkel\BewustBezorgd\Model\ArrayCalculatorInterface; /** - * Class Collector + * Emission collector service class */ -class Collector implements CollectorInterface +class CollectEmission { + /**#@+ * Constants */ - const CALCULATED_FIELD_KEYS = [ + private const CALCULATED_FIELD_KEYS = [ 'two-legs' => 'Weight', 'three-legs' => 'Mass' ]; + private const ATTRIBUTE_CODE_BEWUSTBEZORGD_LEGS = 'bewustbezorgd_legs'; /**#@-*/ + /** + * Map for weight converting + * + * @var array + */ + private const WEIGHT_CONVERT_MAP = [ + 'lbs' => 453.59237, + 'kgs' => 1000 + ]; + + /** + * Map for dimension converting + * + * @var array + */ + private const VOLUME_CONVERT_MAP = [ + 'in' => 0.0163871, + 'cm' => 0.001 + ]; + /** * Headers for CSV files * * @var array */ - protected $csvHeader = [ + private const CSV_HEADER = [ 'two-legs' => [ 'postcode_from' => 'From Postal Code', 'country_from' => 'From Country', @@ -80,112 +103,105 @@ class Collector implements CollectorInterface */ private $truncateResult = null; - /** @var DataHelper */ - private $dataHelper; - /** @var ConfigModel */ private $configModel; /** @var DirectoryHelper */ - protected $directoryHelper; - - /** @var Filesystem */ - private $filesystem; + private $directoryHelper; /** @var ApiConnection */ private $apiConnection; - /** @var Converter */ - protected $converter; - /** @var ShippingMethodExtensionFactory */ - protected $extensionFactory; + private $extensionFactory; /** @var Session */ - protected $session; + private $session; /** @var SerializerInterface */ - protected $serializer; + private $serializer; - /** @var ArrayCalculatorInterface */ - protected $arrayCalculator; + /** @var EavConfig */ + protected $eavConfig; /** * Store Information Country ID * * @var string */ - protected $storeCountryId; + private $storeCountryId; /** * Store Information Postcode * * @var string */ - protected $storePostcode; + private $storePostcode; /** * Filter manager * * @var FilterManager */ - protected $filterManager; + private $filterManager; /** * Option map for attribute "bewustbezorgdLegs" * * @var array */ - protected $bewustbezorgdLegsMap; + private $bewustbezorgdLegsMap; + + /** + * @var LogRepository + */ + private $logRepository; - protected $shippingMethodKeys = []; + /** + * @var array + */ + private $shippingMethodKeys = []; /** * Constructor. * - * @param DataHelper $dataHelper * @param ConfigModel $configModel * @param DirectoryHelper $directoryHelper - * @param Filesystem $filesystem * @param ApiConnection $apiConnection - * @param Converter $converter * @param ShippingMethodExtensionFactory $extensionFactory * @param Session $session * @param SerializerInterface $serializer - * @param ArrayCalculatorInterface $arrayCalculator * @param StoreManagerInterface $storeManager * @param ScopeConfigInterface $scopeConfig * @param FilterManager $filterManager + * @param EavConfig $eavConfig + * @param LogRepository $logRepository * @param BewustbezorgdLegsAttributeSource $bewustbezorgdLegsSource * @throws NoSuchEntityException */ public function __construct( - DataHelper $dataHelper, ConfigModel $configModel, DirectoryHelper $directoryHelper, - Filesystem $filesystem, ApiConnection $apiConnection, - Converter $converter, ShippingMethodExtensionFactory $extensionFactory, Session $session, SerializerInterface $serializer, - ArrayCalculatorInterface $arrayCalculator, StoreManagerInterface $storeManager, ScopeConfigInterface $scopeConfig, FilterManager $filterManager, + EavConfig $eavConfig, + LogRepository $logRepository, BewustbezorgdLegsAttributeSource $bewustbezorgdLegsSource ) { - $this->dataHelper = $dataHelper; $this->configModel = $configModel; $this->directoryHelper = $directoryHelper; - $this->filesystem = $filesystem; $this->apiConnection = $apiConnection; - $this->converter = $converter; $this->extensionFactory = $extensionFactory; $this->session = $session; $this->serializer = $serializer; - $this->arrayCalculator = $arrayCalculator; $this->filterManager = $filterManager; + $this->eavConfig = $eavConfig; + $this->logRepository = $logRepository; $this->storeCountryId = $scopeConfig->getValue( ShippingConfig::XML_PATH_ORIGIN_COUNTRY_ID, ScopeInterface::SCOPE_STORE, @@ -202,9 +218,17 @@ public function __construct( } /** - * {@inheritdoc} + * Emission Collect Method + * + * @param CartInterface $quote + * @param $address + * @param array $shippingMethods + * @return ShippingMethod[]|array + * @throws NoSuchEntityException + * @throws FileSystemException + * @throws WrongApiConfigurationException */ - public function collect(CartInterface $quote, $address, $shippingMethods) + public function execute(CartInterface $quote, $address, $shippingMethods) { // Check if country in store information is allowed if (!in_array($this->storeCountryId, explode(',', $this->configModel->getAllowedCountries()))) { @@ -242,38 +266,33 @@ public function collect(CartInterface $quote, $address, $shippingMethods) $this->shippingMethodKeys[$key] = $collectedMethodCode; } $efficiency = []; - try { - foreach ($requestData as $filename => $requestDatum) { - $file = $this->prepareCsv($filename, $suffix, $requestDatum); - $data = $this->parseCsv($this->apiConnection->getBulkEmission($file, $filename)); - + foreach ($requestData as $endpoint => $requestDatum) { + $data = $this->apiConnection->getEmission($requestDatum, $endpoint); foreach ($shippingMethods as $key => $shippingMethod) { $collectedMethodCode = $shippingMethod->getCarrierCode() . '_' . $shippingMethod->getMethodCode(); $this->getExtensionAttributes($shippingMethod) ->setMostEfficient(0); - ; if (!isset($this->shippingMethodKeys[$key])) { continue; } - $emissionData = array_shift($data); - - if (null === $emissionData['Service Type']) { + if (!$data) { continue; } + $emissionData = $data; if (!isset($emission[$collectedMethodCode])) { $emission[$collectedMethodCode] = [ 'emission' => 0, 'meters_diesel' => 0, 'meters_gasoline' => 0, - 'service_type' => $emissionData['Service Type'] + 'service_type' => $endpoint ]; } - $emission[$collectedMethodCode]['emission'] += $emissionData['Emission']; - $emission[$collectedMethodCode]['meters_diesel'] += $emissionData['Meters Diesel']; - $emission[$collectedMethodCode]['meters_gasoline'] += $emissionData['Meters Gasoline']; + $emission[$collectedMethodCode]['emission'] += $emissionData['emission']; + $emission[$collectedMethodCode]['meters_diesel'] += $emissionData['metersDiesel']; + $emission[$collectedMethodCode]['meters_gasoline'] += $emissionData['metersGasoline']; $efficiency[$key] = [ 'emission' => $emission[$collectedMethodCode]['emission'], 'shipping_method' => $shippingMethod @@ -289,11 +308,13 @@ public function collect(CartInterface $quote, $address, $shippingMethods) $this->getExtensionAttributes($mostEfficient['shipping_method']) ->setMostEfficient(1); } - // @codingStandardsIgnoreStart + // @codingStandardsIgnoreStart } catch (WrongApiConfigurationException $exception) { + $this->logRepository->addApiLog($exception->getMessage()); } catch (WrongApiCredentialsException $exception) { - } catch (ApiAuthenticationFailedException $exception) { + $this->logRepository->addApiLog($exception->getMessage()); } catch (Throwable $exception) { + $this->logRepository->addApiLog($exception->getMessage()); } // @codingStandardsIgnoreEnd return $shippingMethods; @@ -308,7 +329,7 @@ public function collect(CartInterface $quote, $address, $shippingMethods) * @return array * @throws LocalizedException */ - protected function prepareEmissionData(CartInterface $quote, $address, $serviceType) + private function prepareEmissionData(CartInterface $quote, $address, $serviceType) { $data = []; $result = []; @@ -318,7 +339,7 @@ protected function prepareEmissionData(CartInterface $quote, $address, $serviceT } foreach ($data as $endpoint => $items) { - $result[$endpoint][] = $this->arrayCalculator->calculateFieldSumByKey( + $result[$endpoint][] = $this->calculateFieldSumByKey( $data[$endpoint], self::CALCULATED_FIELD_KEYS[$endpoint] ); @@ -327,6 +348,39 @@ protected function prepareEmissionData(CartInterface $quote, $address, $serviceT return $result; } + /** + * Calculates sum array field by key + * + * Input array should be like + * [ + * ['key1' => 'value1', 'key2' => 'value2', ... 'keyN' => 'valueN'], + * ['key1' => 'value1', 'key2' => 'value2', ... 'keyN' => 'valueN'], + * ... + * ['key1' => 'value1', 'key2' => 'value2', ... 'keyN' => 'valueN'] + * ] + * + * Example output array + * ['key1' => 'value1', 'calculatedKey' => SUM('value'), ... 'keyN' => 'valueN'] + * + * @param array $array + * @param $calculatedKey + * @return array + */ + private function calculateFieldSumByKey(array $array, $calculatedKey) + { + if (!count($array)) { + return $array; + } + $result = array_shift($array); + + while (count($array)) { + $item = array_shift($array); + $result[$calculatedKey] += $item[$calculatedKey]; + } + + return $result; + } + /** * Prepares request emission data from quote item * @@ -336,7 +390,7 @@ protected function prepareEmissionData(CartInterface $quote, $address, $serviceT * @return array * @throws LocalizedException */ - protected function prepareItemData(CartItemInterface $quoteItem, $address, $serviceType) + private function prepareItemData(CartItemInterface $quoteItem, $address, $serviceType) { $bewustbezorgdLegs = $this->getBewustbezorgdLegs($quoteItem); @@ -352,82 +406,23 @@ protected function prepareItemData(CartItemInterface $quoteItem, $address, $serv return [ $itemEndpoint => [[ - $this->csvHeader[$itemEndpoint]['postcode_from'] => $this->storePostcode, - $this->csvHeader[$itemEndpoint]['country_from'] => $this->storeCountryId, - $this->csvHeader[$itemEndpoint]['postcode_to'] => $this->truncateString($address->getPostcode()), - $this->csvHeader[$itemEndpoint]['country_to'] => $address->getCountryId(), - $this->csvHeader[$itemEndpoint]['weight_mass'] => $weightOrVolume, - $this->csvHeader[$itemEndpoint]['service_type'] => $serviceType + self::CSV_HEADER[$itemEndpoint]['postcode_from'] => $this->storePostcode, + self::CSV_HEADER[$itemEndpoint]['country_from'] => $this->storeCountryId, + self::CSV_HEADER[$itemEndpoint]['postcode_to'] => $this->truncateString($address->getPostcode()), + self::CSV_HEADER[$itemEndpoint]['country_to'] => $address->getCountryId(), + self::CSV_HEADER[$itemEndpoint]['weight_mass'] => $weightOrVolume, + self::CSV_HEADER[$itemEndpoint]['service_type'] => $serviceType ]] ]; } - /** - * Prepares CSV file to send to Api - * - * @param $filename - * @param $suffix - * @param $requestData - * @return string - * @throws FileSystemException - */ - protected function prepareCsv($filename, $suffix, $requestData) - { - $directory = $this->filesystem->getDirectoryWrite(DirectoryList::VAR_DIR); - $tmpDir = $directory->getAbsolutePath('order-emission'); - - if (!$directory->create($tmpDir)) { - throw new RuntimeException('Failed to create temporary directory'); - } - $file = $tmpDir . '/' . $filename . '-' . $suffix . '.csv'; - $stream = $directory->openFile($file, 'w+'); - $stream->lock(); - $stream->writeCsv($this->csvHeader[$filename], ';'); - - foreach ($requestData as $requestDatum) { - $stream->writeCsv($requestDatum, ';'); - } - $stream->unlock(); - $stream->close(); - - return $file; - } - - /** - * CSV parser - * - * @param $csvData - * @return array - */ - protected function parseCsv($csvData) - { - $csvStrings = explode(PHP_EOL, str_replace("\r\n", "\n", $csvData)); - $csvStrings = array_filter($csvStrings, function ($csvString) { - return !empty($csvString); - }); - $csvKeys = explode(';', array_shift($csvStrings)); - $data = []; - - while (count($csvStrings)) { - $csvData = []; - $csvStringAsArray = explode(';', array_shift($csvStrings)); - - for ($i = 0, $colsCount = count($csvStringAsArray); $i < $colsCount; $i++) { - $csvData[$csvKeys[$i]] = $csvStringAsArray[$i]; - } - $data[] = $csvData; - } - - return $data; - } - /** * Retrieves "extension_attributes" from shipping method or creates it * * @param ShippingMethod $shippingMethod * @return ShippingMethodExtensionInterface */ - protected function getExtensionAttributes(ShippingMethod $shippingMethod) + private function getExtensionAttributes(ShippingMethod $shippingMethod) { $extension = $shippingMethod->getExtensionAttributes(); if (!$extension) { @@ -445,9 +440,31 @@ protected function getExtensionAttributes(ShippingMethod $shippingMethod) * @return string|null * @throws LocalizedException */ - protected function getBewustbezorgdLegs(CartItemInterface $quoteItem) + private function getBewustbezorgdLegs(CartItemInterface $quoteItem) + { + return $quoteItem->getProduct()->getBewustbezorgdLegs() ?: $this->getDefaultBewustbezorgdLegs(); + } + + /** + * Retrieves default value of attribute "bewustbezorgd_legs" + * + * @return string|null + * @throws LocalizedException + */ + private function getDefaultBewustbezorgdLegs() { - return $quoteItem->getProduct()->getBewustbezorgdLegs() ?: $this->dataHelper->getDefaultBewustbezorgdLegs(); + try { + /** @var Attribute $attribute */ + $attribute = $this->eavConfig->getAttribute( + Product::ENTITY, + self::ATTRIBUTE_CODE_BEWUSTBEZORGD_LEGS + ); + } catch (LocalizedException $exception) { + $this->logRepository->addDataLog($exception->getMessage(), 'Get Default Bewustbezorgd Legs'); + return null; + } + + return $attribute->getDefaultValue(); } /** @@ -456,11 +473,11 @@ protected function getBewustbezorgdLegs(CartItemInterface $quoteItem) * @param CartItemInterface $quoteItem * @return float|int */ - protected function getQuoteItemWeight(CartItemInterface $quoteItem) + private function getQuoteItemWeight(CartItemInterface $quoteItem) { $itemWeight = $quoteItem->getProduct()->getWeight() ?: $this->configModel->getDefaultWeight(); - return $this->converter->convertWeightToGrams( + return $this->convertWeightToGrams( $itemWeight * $quoteItem->getQty(), $this->directoryHelper->getWeightUnit() ); @@ -472,14 +489,15 @@ protected function getQuoteItemWeight(CartItemInterface $quoteItem) * @param CartItemInterface $quoteItem * @return float|int */ - protected function getQuoteItemVolume(CartItemInterface $quoteItem) + private function getQuoteItemVolume(CartItemInterface $quoteItem) { $dimensionAttributes = $this->configModel->getConfigDimensionsAttributes(); - if (($length = $quoteItem->getProduct()->getData($dimensionAttributes['attribute_length'])) - && ($width = $quoteItem->getProduct()->getData($dimensionAttributes['attribute_width'])) - && ($height = $quoteItem->getProduct()->getData($dimensionAttributes['attribute_height'])) + $product = $quoteItem->getProduct(); + if (($length = $product->getData($dimensionAttributes['attribute_length'])) + && ($width = $product->getData($dimensionAttributes['attribute_width'])) + && ($height = $product->getData($dimensionAttributes['attribute_height'])) ) { - return $this->converter->convertVolumeToLiters( + return $this->convertVolumeToLiters( $length * $width * $height * $quoteItem->getQty(), $this->configModel->getDimensionsUnit() ); @@ -494,7 +512,7 @@ protected function getQuoteItemVolume(CartItemInterface $quoteItem) * @param array $efficiencyItem * @return float|int */ - protected function getEfficiencyEmission(array $efficiencyItem) + private function getEfficiencyEmission(array $efficiencyItem) { return $efficiencyItem['emission']; } @@ -505,7 +523,7 @@ protected function getEfficiencyEmission(array $efficiencyItem) * @param array $efficiency * @return array|bool */ - protected function getMostEfficient(array $efficiency) + private function getMostEfficient(array $efficiency) { usort($efficiency, function ($a, $b) { return $this->getEfficiencyEmission($a) <=> $this->getEfficiencyEmission($b); @@ -529,8 +547,11 @@ protected function getMostEfficient(array $efficiency) * @param bool $breakWords * @return string */ - protected function truncateString($value, $length = 4, $etc = '', &$remainder = '', $breakWords = true) + private function truncateString($value, $length = 4, $etc = '', &$remainder = '', $breakWords = true) { + if (!$value) { + $value = ""; + } $value = trim($value); $this->truncateResult = $this->filterManager->truncateFilter( $value, @@ -539,4 +560,28 @@ protected function truncateString($value, $length = 4, $etc = '', &$remainder = return $this->truncateResult->getValue(); } + + /** + * Retrieves converted value from the requested unit to kilograms + * + * @param $value + * @param $unit + * @return float|int + */ + private function convertWeightToGrams($value, $unit) + { + return $value * self::WEIGHT_CONVERT_MAP[$unit]; + } + + /** + * Retrieves converted value from the requested unit to liters + * + * @param $value + * @param $unit + * @return float|int + */ + private function convertVolumeToLiters($value, $unit) + { + return $value * self::VOLUME_CONVERT_MAP[$unit]; + } } diff --git a/Setup/SetupData.php b/Setup/Patch/Data/ProductAttributes.php old mode 100644 new mode 100755 similarity index 56% rename from Setup/SetupData.php rename to Setup/Patch/Data/ProductAttributes.php index 8d26319..87d5ce4 --- a/Setup/SetupData.php +++ b/Setup/Patch/Data/ProductAttributes.php @@ -4,26 +4,34 @@ * See COPYING.txt for license details. */ -namespace Thuiswinkel\BewustBezorgd\Setup; +namespace Thuiswinkel\BewustBezorgd\Setup\Patch\Data; -use Zend_Validate_Exception; +use Magento\Bundle\Model\Product\Type as BundleProductTypeModel; use Magento\Catalog\Model\Product; use Magento\Catalog\Model\Product\Type as CatalogProductTypeModel; -use Magento\GroupedProduct\Model\Product\Type\Grouped as GroupedProductTypeModel; -use Magento\Bundle\Model\Product\Type as BundleProductTypeModel; use Magento\ConfigurableProduct\Model\Product\Type\Configurable as ConfigurableProductTypeModel; use Magento\Eav\Setup\EavSetup; use Magento\Eav\Setup\EavSetupFactory; -use Magento\Framework\Setup\ModuleDataSetupInterface; use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Setup\ModuleDataSetupInterface; +use Magento\Framework\Setup\Patch\DataPatchInterface; +use Magento\Framework\Setup\Patch\PatchRevertableInterface; +use Magento\GroupedProduct\Model\Product\Type\Grouped as GroupedProductTypeModel; use Thuiswinkel\BewustBezorgd\Model\Product\Attribute\Source\BewustbezorgdLegs; +use Zend_Validate_Exception; /** - * Data setup for use during installation / upgrade + * Add Product Attributes */ -class SetupData +class ProductAttributes implements DataPatchInterface, PatchRevertableInterface { - const ATTRIBUTE_CODE_BEWUSTBEZORGD_LEGS = 'bewustbezorgd_legs'; + + public const ATTRIBUTE_CODE_BEWUSTBEZORGD_LEGS = 'bewustbezorgd_legs'; + + /** + * @var ModuleDataSetupInterface + */ + private $moduleDataSetup; /** * @var EavSetupFactory @@ -31,23 +39,72 @@ class SetupData private $eavSetupFactory; /** - * SetupData constructor. - * + * ProductAttributes constructor. * @param EavSetupFactory $eavSetupFactory + * @param ModuleDataSetupInterface $moduleDataSetup */ - public function __construct(EavSetupFactory $eavSetupFactory) - { + public function __construct( + EavSetupFactory $eavSetupFactory, + ModuleDataSetupInterface $moduleDataSetup + ) { $this->eavSetupFactory = $eavSetupFactory; + $this->moduleDataSetup = $moduleDataSetup; + } + + /** + * @return DataPatchInterface|void + * @throws LocalizedException + * @throws Zend_Validate_Exception + */ + public function apply() + { + $this->moduleDataSetup->getConnection()->startSetup(); + /** @var EavSetup $eavSetup */ + $eavSetup = $this->eavSetupFactory->create(['setup' => $this->moduleDataSetup]); + if (!$eavSetup->getAttributeId(Product::ENTITY, self::ATTRIBUTE_CODE_BEWUSTBEZORGD_LEGS)) { + $this->addBewustbezorgdLegsAttribute(); + } + $this->moduleDataSetup->getConnection()->endSetup(); + } + + /** + * {@inheritdoc} + */ + public static function getDependencies() + { + return []; + } + + /** + * {@inheritdoc} + */ + public function getAliases() + { + return []; + } + + /** + * @inheritDoc + */ + public function revert() + { + /** @var EavSetup $eavSetup */ + $eavSetup = $this->eavSetupFactory->create(['setup' => $this->moduleDataSetup]); + if ($eavSetup->getAttributeId(Product::ENTITY, self::ATTRIBUTE_CODE_BEWUSTBEZORGD_LEGS)) { + $eavSetup->removeAttribute( + Product::ENTITY, + self::ATTRIBUTE_CODE_BEWUSTBEZORGD_LEGS + ); + } } /** * Add bewustbezorgd_legs attributes. * - * @param ModuleDataSetupInterface $setup * @throws LocalizedException * @throws Zend_Validate_Exception */ - public function addBewustbezorgdLegsAttribute(ModuleDataSetupInterface $setup) + public function addBewustbezorgdLegsAttribute() { $applyTo = implode(',', [ CatalogProductTypeModel::TYPE_SIMPLE, @@ -56,8 +113,7 @@ public function addBewustbezorgdLegsAttribute(ModuleDataSetupInterface $setup) ConfigurableProductTypeModel::TYPE_CODE ]); /** @var EavSetup $eavSetup */ - $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]); - + $eavSetup = $this->eavSetupFactory->create(['setup' => $this->moduleDataSetup]); $eavSetup->addAttribute(Product::ENTITY, self::ATTRIBUTE_CODE_BEWUSTBEZORGD_LEGS, [ 'type' => 'int', 'label' => 'Bewustbezorgd Legs', diff --git a/Setup/SetupSchema.php b/Setup/SetupSchema.php deleted file mode 100644 index 05e32cb..0000000 --- a/Setup/SetupSchema.php +++ /dev/null @@ -1,101 +0,0 @@ -getConnection()->newTable($installer->getTable(self::TABLE_ORDER_EMISSION)); - - $table->addColumn( - 'order_emission_id', - Table::TYPE_INTEGER, - null, - ['identity' => true, 'nullable' => false, 'primary' => true, 'unsigned' => true], - 'Entity ID' - ); - - $table->addColumn( - 'order_id', - Table::TYPE_INTEGER, - 10, - ['nullable' => false, 'unsigned' => true], - 'Magento Order ID' - ); - - $table->addColumn( - 'service_type', - Table::TYPE_TEXT, - 25, - [], - 'Service Type' - ); - - $table->addColumn( - 'emission', - Table::TYPE_DECIMAL, - '12,4', - [], - 'Order Emission' - ); - - $table->addColumn( - 'meters_diesel', - Table::TYPE_DECIMAL, - '12,4', - [] - ); - - $table->addColumn( - 'meters_gasoline', - Table::TYPE_DECIMAL, - '12,4', - [] - ); - - $installer->getConnection()->createTable($table); - } - - /** - * Adds foreign key to table `thuiswinkel_order_emission` - * - * @param SchemaSetupInterface $installer - * @return void - */ - public function addFkToOrderEmissionTable(SchemaSetupInterface $installer) - { - $installer->getConnection()->addForeignKey( - $installer->getFkName( - self::TABLE_ORDER_EMISSION, - OrderEmissionInterface::ORDER_ID, - 'sales_order', - 'entity_id' - ), - $installer->getTable(self::TABLE_ORDER_EMISSION), - OrderEmissionInterface::ORDER_ID, - $installer->getTable('sales_order'), - 'entity_id' - ); - } -} diff --git a/Setup/Uninstall.php b/Setup/Uninstall.php deleted file mode 100644 index a48b0a3..0000000 --- a/Setup/Uninstall.php +++ /dev/null @@ -1,37 +0,0 @@ -getConnection(ResourceConnection::DEFAULT_CONNECTION); - $defaultConnection->dropTable(SetupSchema::TABLE_ORDER_EMISSION); - $configTable = $uninstaller->getTable('core_config_data'); - $defaultConnection->delete($configTable, "`path` LIKE 'bewust_bezorgd/%'"); - } -} diff --git a/Setup/UpgradeData.php b/Setup/UpgradeData.php deleted file mode 100644 index cc92fe6..0000000 --- a/Setup/UpgradeData.php +++ /dev/null @@ -1,49 +0,0 @@ -installer = $installer; - } - - /** - * @param ModuleDataSetupInterface $setup - * @param ModuleContextInterface $context - * @throws LocalizedException - * @throws Zend_Validate_Exception - */ - public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context) - { - $moduleVersion = $context->getVersion(); - - if (version_compare($moduleVersion, '0.9.0', '<')) { - $this->installer->addBewustbezorgdLegsAttribute($setup); - } - } -} diff --git a/Setup/UpgradeSchema.php b/Setup/UpgradeSchema.php deleted file mode 100644 index 1b98696..0000000 --- a/Setup/UpgradeSchema.php +++ /dev/null @@ -1,48 +0,0 @@ -installer = $installer; - } - - /** - * @param SchemaSetupInterface $setup - * @param ModuleContextInterface $context - * - * @return void - * @throws Zend_Db_Exception - */ - public function upgrade(SchemaSetupInterface $setup, ModuleContextInterface $context) - { - $moduleVersion = $context->getVersion(); - - if (version_compare($moduleVersion, '0.9.0', '<')) { - $this->installer->createOrderEmissionTable($setup); - $this->installer->addFkToOrderEmissionTable($setup); - } - } -} diff --git a/Ui/Component/Listing/Column/Emission.php b/Ui/Component/Listing/Column/Emission.php old mode 100644 new mode 100755 index 68d8cff..c5baddd --- a/Ui/Component/Listing/Column/Emission.php +++ b/Ui/Component/Listing/Column/Emission.php @@ -3,11 +3,10 @@ * Copyright © Thuiswinkel.org. All rights reserved. * See COPYING.txt for license details. */ +declare(strict_types=1); namespace Thuiswinkel\BewustBezorgd\Ui\Component\Listing\Column; -use Magento\Framework\View\Element\UiComponent\ContextInterface; -use Magento\Framework\View\Element\UiComponentFactory; use Magento\Ui\Component\Listing\Columns\Column; /** @@ -41,7 +40,10 @@ public function prepareDataSource(array $dataSource) */ protected function prepareItem(array $item) { - if (isset($item[$this->getData('name')]) && is_numeric($item[$this->getData('name')]) && $item[$this->getData('name')] > 0) { + if (isset($item[$this->getData('name')]) + && is_numeric($item[$this->getData('name')]) + && $item[$this->getData('name')] > 0 + ) { return '