diff --git a/App/Response/FeedContent.php b/App/Response/FeedContent.php
index caf4d81..2d6411d 100644
--- a/App/Response/FeedContent.php
+++ b/App/Response/FeedContent.php
@@ -1,4 +1,5 @@
export = $export;
$this->log = $log;
$this->type = $type;
$this->store = $store;
+ $this->driver = $driver;
}
/**
@@ -57,7 +72,7 @@ public function __construct(Export $export, Logger $log, StoreInterface $store =
*/
public function __toString()
{
- $resource = fopen('php://output', 'wb');
+ $resource = $this->driver->fileOpen('php://output', 'wb');
try {
try {
$this->export->getFeed($resource, $this->store, $this->type);
@@ -65,7 +80,7 @@ public function __toString()
$this->log->error(sprintf('Failed to get feed due to %s', $e->getMessage()));
}
} finally {
- fclose($resource);
+ $this->driver->fileClose($resource);
}
return '';
diff --git a/Block/Config/Form/Field/ExportPriceStart.php b/Block/Config/Form/Field/ExportPriceStart.php
index 404c1dc..1829664 100644
--- a/Block/Config/Form/Field/ExportPriceStart.php
+++ b/Block/Config/Form/Field/ExportPriceStart.php
@@ -1,4 +1,5 @@
getForm()->getLayout()->createBlock(Button::class);
- $button->setData([
+ $button->setData(
+ [
'label' => __('Schedule'),
'onclick' => "setLocation('{$this->getUrl('tweakwise/export/trigger/type/price')}')",
- ]);
+ ]
+ );
return $button->toHtml();
}
diff --git a/Block/Config/Form/Field/ExportStart.php b/Block/Config/Form/Field/ExportStart.php
index b34e2d4..c5f5b4e 100644
--- a/Block/Config/Form/Field/ExportStart.php
+++ b/Block/Config/Form/Field/ExportStart.php
@@ -1,4 +1,5 @@
getForm()->getLayout()->createBlock(Button::class);
- $button->setData([
+ $button->setData(
+ [
'label' => __('Schedule'),
'onclick' => "setLocation('{$this->getUrl('tweakwise/export/trigger')}')",
- ]);
+ ]
+ );
return $button->toHtml();
}
diff --git a/Block/Config/Form/Field/ExportState.php b/Block/Config/Form/Field/ExportState.php
index 1dd4973..3106dba 100644
--- a/Block/Config/Form/Field/ExportState.php
+++ b/Block/Config/Form/Field/ExportState.php
@@ -1,4 +1,5 @@
getForm()->getLayout()->createBlock(Button::class);
- $button->setData([
+ $button->setData(
+ [
'label' => __('Schedule'),
'onclick' => "setLocation('{$this->getUrl('tweakwise/export/trigger/type/stock')}')",
- ]);
+ ]
+ );
return $button->toHtml();
}
diff --git a/Console/Command/ExportCommand.php b/Console/Command/ExportCommand.php
index 8125a8b..782a29e 100644
--- a/Console/Command/ExportCommand.php
+++ b/Console/Command/ExportCommand.php
@@ -1,4 +1,5 @@
config = $config;
$this->export = $export;
$this->state = $state;
@@ -78,108 +84,135 @@ protected function configure(): void
$this->setName('tweakwise:export')
->addOption('file', 'f', InputArgument::OPTIONAL, 'Export to specific file')
->addOption('store', 's', InputArgument::OPTIONAL, 'Export specific store')
- ->addOption('type', 't', InputArgument::OPTIONAL, 'Export type [stock] for stock only export, [price] for price export only')
+ ->addOption(
+ 'type',
+ 't',
+ InputArgument::OPTIONAL,
+ 'Export type [stock] for stock only export, [price] for price export only'
+ )
->addOption(
'validate',
'c',
- InputOption::VALUE_OPTIONAL, 'Validate feed and rollback if fails [y/n].'
+ InputOption::VALUE_OPTIONAL,
+ 'Validate feed and rollback if fails [y/n].'
+ )
+ ->addOption(
+ 'debug',
+ 'd',
+ InputOption::VALUE_NONE,
+ 'Debugging enables profiler.'
)
- ->addOption('debug', 'd', InputOption::VALUE_NONE, 'Debugging enables profiler.')
->setDescription('Export tweakwise feed');
}
/**
* {@inheritdoc}
* @throws Exception
+ * phpcs:disable Generic.Metrics.CyclomaticComplexity.TooHigh
+ * @SuppressWarnings(PHPMD.CyclomaticComplexity)
+ * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
- return $this->state->emulateAreaCode(Area::AREA_CRONTAB, function() use ($input, $output) {
- if ($input->getOption('debug')) {
- Profiler::enable();
- Profiler::add(new ConsoleDriver($output));
- }
-
- $isStoreLevelExportEnabled = $this->config->isStoreLevelExportEnabled();
- $storeCode = (string) $input->getOption('store');
- $store = null;
-
- $type = (string)$input->getOption('type');
-
- if (!empty($this->type)) {
- $type = $this->type;
- }
-
- if ($type !== "stock" && $type !== "" && $type !== "price") {
- $output->writeln('Type option should be stock, price or not set');
-
- return -1;
- } elseif(empty($type)) {
- $type = null;
- }
-
- $validate = (string)$input->getOption('validate');
- if ($validate !== 'y' && $validate !== 'n' && $validate !== "") {
- $output->writeln('Validate option can only contain y or n');
-
- return -1;
- }
-
- $validate = $validate === "" ? $this->config->isValidate() : $validate === 'y';
- $startTime = microtime(true);
- $feedFile = (string)$input->getOption('file');
-
- if ($isStoreLevelExportEnabled) {
- if (!$storeCode) {
- $output->writeln('Store level export enabled please provide --store ');
-
- return -1;
+ return $this->state->emulateAreaCode(
+ Area::AREA_CRONTAB,
+ function () use ($input, $output) {
+ if ($input->getOption('debug')) {
+ Profiler::enable();
+ Profiler::add(new ConsoleDriver($output));
}
- try {
- $store = $this->storeManager->getStore($storeCode);
- } catch (NoSuchEntityException $exception) {
- $output->writeln('Store does not exist');
+ $isStoreLevelExportEnabled = $this->config->isStoreLevelExportEnabled();
+ $storeCode = (string) $input->getOption('store');
+ $store = null;
- return -1;
+ $type = (string)$input->getOption('type');
+
+ if (!empty($this->type)) {
+ $type = $this->type;
}
- if (!$this->config->isEnabled($store)) {
- $output->writeln('Tweakwise export does not enabled in this store');
+ if ($type !== "stock" && $type !== "" && $type !== "price") {
+ $output->writeln('Type option should be stock, price or not set');
return -1;
+ } elseif (empty($type)) {
+ $type = null;
}
- if (!$feedFile) {
- $feedFile = $this->config->getDefaultFeedFile($store, $type);
- }
+ $validate = (string)$input->getOption('validate');
+ if ($validate !== 'y' && $validate !== 'n' && $validate !== "") {
+ $output->writeln('Validate option can only contain y or n');
- $output->writeln("generatig feed for {$store->getCode()}");
- $this->export->generateToFile($feedFile, $validate, $store, $type);
- $output->writeln("feed file: {$feedFile}");
- } else {
- if ($storeCode) {
- $output->writeln('Store level export disabled, remove --store parameter');
return -1;
}
- if (!$feedFile) {
- $feedFile = $this->config->getDefaultFeedFile(null, $type);
+ $validate = $validate === "" ? $this->config->isValidate() : $validate === 'y';
+ $startTime = microtime(true);
+ $feedFile = (string)$input->getOption('file');
+
+ if ($isStoreLevelExportEnabled) {
+ if (!$storeCode) {
+ $output->writeln(
+ 'Store level export enabled please provide --store '
+ );
+
+ return -1;
+ }
+
+ try {
+ $store = $this->storeManager->getStore($storeCode);
+ } catch (NoSuchEntityException $exception) {
+ $output->writeln('Store does not exist');
+
+ return -1;
+ }
+
+ if (!$this->config->isEnabled($store)) {
+ $output->writeln('Tweakwise export does not enabled in this store');
+
+ return -1;
+ }
+
+ if (!$feedFile) {
+ $feedFile = $this->config->getDefaultFeedFile($store, $type);
+ }
+
+ $output->writeln("generatig feed for {$store->getCode()}");
+ $this->export->generateToFile($feedFile, $validate, $store, $type);
+ $output->writeln("feed file: {$feedFile}");
+ } else {
+ if ($storeCode) {
+ $output->writeln('Store level export disabled, remove --store parameter');
+ return -1;
+ }
+
+ if (!$feedFile) {
+ $feedFile = $this->config->getDefaultFeedFile(null, $type);
+ }
+
+ $output->writeln("generating single feed for export enabled stores");
+ $this->export->generateToFile($feedFile, $validate, null, $type);
+ $output->writeln("feed file: {$feedFile}");
}
- $output->writeln("generating single feed for export enabled stores");
- $this->export->generateToFile($feedFile, $validate, null, $type);
- $output->writeln("feed file: {$feedFile}");
+ $generateTime = round(microtime(true) - $startTime, 2);
+ $memoryUsage = round(
+ memory_get_peak_usage(true) / 1024 / 1024,
+ 2
+ );
+ $output->writeln(
+ sprintf(
+ 'Feed written to %s in %ss using %sMb memory',
+ $feedFile,
+ $generateTime,
+ $memoryUsage
+ )
+ );
+
+ return 0;
}
-
- $generateTime = round(microtime(true) - $startTime, 2);
- $memoryUsage = round(memory_get_peak_usage(true) / 1024 / 1024,
- 2);
- $output->writeln(sprintf('Feed written to %s in %ss using %sMb memory',
- $feedFile, $generateTime, $memoryUsage));
-
- return 0;
- });
+ );
}
public function executeStock(InputInterface $input, OutputInterface $output)
diff --git a/Controller/Cache/Flush.php b/Controller/Cache/Flush.php
index f5c6a30..f3b67db 100644
--- a/Controller/Cache/Flush.php
+++ b/Controller/Cache/Flush.php
@@ -14,8 +14,6 @@
/**
* Class Flush, handle cache flush request from tweakwise platform
- *
- * @package Tweakwise\Magento2TweakwiseExport\Controller\Cache
*/
class Flush implements ActionInterface
{
@@ -84,6 +82,7 @@ public function execute(): ResponseInterface
if (!$this->config->isAllowCacheFlush()) {
return $this->createOkResponse('Cache flush not enabled in settings');
}
+
// Clear caches
$this->cacheHandler->clear();
@@ -91,7 +90,7 @@ public function execute(): ResponseInterface
}
/**
- * @param string $body Message
+ * @param string $body
* @return Http
*/
protected function createOkResponse(string $body): Http
diff --git a/Controller/Feed/Export.php b/Controller/Feed/Export.php
index a001cb4..085275e 100644
--- a/Controller/Feed/Export.php
+++ b/Controller/Feed/Export.php
@@ -1,4 +1,5 @@
context->getRequest();
- if (!$this->requestValidator->validateRequestKey($request) || (!$this->requestValidator->validateStoreKey($request)) || (!$this->requestValidator->validateType($request))) {
+ if (
+ !$this->requestValidator->validateRequestKey($request) ||
+ (!$this->requestValidator->validateStoreKey($request)) ||
+ (!$this->requestValidator->validateType($request))
+ ) {
throw new NotFoundException(__('Page not found.'));
}
$store = null;
$storeId = $request->getParam('store');
- if(!empty($storeId)) {
+ if (!empty($storeId)) {
$store = $this->storeManager->getStore($storeId);
}
diff --git a/Cron/Export.php b/Cron/Export.php
index 7da0901..2aaeef0 100644
--- a/Cron/Export.php
+++ b/Cron/Export.php
@@ -1,4 +1,5 @@
config->isValidate();
- if ($this->config->isStoreLevelExportEnabled()){
+ if ($this->config->isStoreLevelExportEnabled()) {
foreach ($this->storeManager->getStores() as $store) {
if ($this->config->isEnabled($store)) {
$feedFile = $this->config->getDefaultFeedFile($store, $type);
$this->export->generateToFile($feedFile, $validate, $store, $type);
}
}
+
return;
}
+
$feedFile = $this->config->getDefaultFeedFile($store = null, $type);
$this->export->generateToFile($feedFile, $validate, $store = null, $type);
}
diff --git a/Exception/ExportException.php b/Exception/ExportExceptionInterface.php
similarity index 90%
rename from Exception/ExportException.php
rename to Exception/ExportExceptionInterface.php
index 3b361a9..abd7069 100644
--- a/Exception/ExportException.php
+++ b/Exception/ExportExceptionInterface.php
@@ -1,4 +1,5 @@
config = $config;
$this->directoryList = $directoryList;
$this->deployConfig = $deployConfig;
+ $this->driver = $driver;
}
/**
@@ -89,7 +100,6 @@ public function isEnabled($store = null): bool
}
/**
- * @param Store|int|string|null $store
* @return bool
*/
public function isStoreLevelExportEnabled(): bool
@@ -122,7 +132,7 @@ public function isValidate(): bool
*/
public function getMaxArchiveFiles(): int
{
- return (integer) $this->config->getValue(self::PATH_ARCHIVE);
+ return (int) $this->config->getValue(self::PATH_ARCHIVE);
}
/**
@@ -131,8 +141,13 @@ public function getMaxArchiveFiles(): int
public function getApiImportUrl($store = null, $type = null): string
{
if ($type === 'stock') {
- return (string) $this->config->getValue(self::PATH_API_IMPORT_URL_STOCK, ScopeInterface::SCOPE_STORE, $store);
+ return (string) $this->config->getValue(
+ self::PATH_API_IMPORT_URL_STOCK,
+ ScopeInterface::SCOPE_STORE,
+ $store
+ );
}
+
return (string) $this->config->getValue(self::PATH_API_IMPORT_URL, ScopeInterface::SCOPE_STORE, $store);
}
@@ -167,14 +182,17 @@ public function isAllowCacheFlush(): bool
*/
public function getPriceFields($store = null): array
{
- $data = (array) explode(',', $this->config->getValue(self::PATH_PRICE_FIELD, ScopeInterface::SCOPE_STORE, $store));
+ $data = (array) explode(
+ ',',
+ $this->config->getValue(self::PATH_PRICE_FIELD, ScopeInterface::SCOPE_STORE, $store)
+ );
return array_filter($data);
}
/**
- * @param Store|int|string|null $store
* @param string|null $attribute
- * @return bool|string[]
+ * @param Store|int|string|null $store
+ * @return bool|int[]|string[]
*/
public function getSkipChildAttribute($attribute = null, $store = null)
{
@@ -192,19 +210,29 @@ public function getSkipChildAttribute($attribute = null, $store = null)
}
/**
+ * @param StoreInterface|null $store
+ * @param string|null $type
* @return string
+ * @throws FileSystemException
+ * @throws RuntimeException
*/
public function getDefaultFeedFile(StoreInterface $store = null, $type = null): string
{
$dir = $this->directoryList->getPath('var') . DIRECTORY_SEPARATOR . 'feeds';
- if (!is_dir($dir) && !mkdir($dir) && !is_dir($dir)) {
+ if (
+ !$this->driver->isDirectory($dir) &&
+ !$this->driver->createDirectory($dir) &&
+ !$this->driver->isDirectory($dir)
+ ) {
throw new RuntimeException(sprintf('Directory "%s" was not created', $dir));
}
- $storeCode = $store && $this->isStoreLevelExportEnabled() ? '-'.$store->getCode() : '';
- $filename = sprintf(self::FEED_FILE_NAME , $storeCode);
+
+ $storeCode = $store && $this->isStoreLevelExportEnabled() ? '-' . $store->getCode() : '';
+ $filename = sprintf(self::FEED_FILE_NAME, $storeCode);
if (!empty($type)) {
- $filename = sprintf(self::FEED_FILE_NAME , ($storeCode . '_' . $type));
+ $filename = sprintf(self::FEED_FILE_NAME, ($storeCode . '_' . $type));
}
+
return $dir . DIRECTORY_SEPARATOR . $filename;
}
diff --git a/Model/Config/Source/PriceField.php b/Model/Config/Source/PriceField.php
index c553223..b56a628 100644
--- a/Model/Config/Source/PriceField.php
+++ b/Model/Config/Source/PriceField.php
@@ -1,4 +1,5 @@
combineArrayPermutations($priceFields);
return array_map(
- function($option) {
+ function ($option) {
$value = implode(',', array_keys($option));
$label = implode(' -> ', array_values($option));
return ['value' => $value, 'label' => $label];
@@ -44,11 +45,12 @@ function($option) {
* @param array $input
* @param array $processed
* @return array
+ * phpcs:disable Magento2.Performance.ForeachArrayMerge.ForeachArrayMerge
*/
protected function combineArrayPermutations(array $input, array $processed = null): array
{
$permutations = [];
- foreach($input as $key => $value) {
+ foreach ($input as $key => $value) {
$copy = $processed ?? [];
$copy[$key] = $value;
$tmp = \array_diff_key($input, $copy);
@@ -59,6 +61,7 @@ protected function combineArrayPermutations(array $input, array $processed = nul
$permutations = array_merge($permutations, $this->combineArrayPermutations($tmp, $copy));
}
}
+
return $permutations;
}
}
diff --git a/Model/Config/Source/ProductAttributes.php b/Model/Config/Source/ProductAttributes.php
index 66852af..ec3f7a2 100644
--- a/Model/Config/Source/ProductAttributes.php
+++ b/Model/Config/Source/ProductAttributes.php
@@ -1,4 +1,5 @@
productAttributesHelper->getAttributesToExport() as $attribute) {
-
$attributeCode = $attribute->getAttributeCode();
$result[] = [
'value' => $attributeCode,
diff --git a/Model/DefaultStockProviderInterfaceFactory.php b/Model/DefaultStockProviderInterfaceFactory.php
index 1337cc1..eeea95a 100644
--- a/Model/DefaultStockProviderInterfaceFactory.php
+++ b/Model/DefaultStockProviderInterfaceFactory.php
@@ -11,7 +11,6 @@
* setup:di:compile fails when there is a reference to a non existing Interface or Class in the constructor
*
* Class StockResolverFactory
- * @package Tweakwise\Magento2TweakwiseExport\Model
*/
class DefaultStockProviderInterfaceFactory
{
diff --git a/Model/Export.php b/Model/Export.php
index 6b15dea..1301744 100644
--- a/Model/Export.php
+++ b/Model/Export.php
@@ -1,4 +1,5 @@
config = $config;
$this->validator = $validator;
$this->writer = $writer;
$this->log = $log;
$this->storeManager = $storeManager;
+ $this->driver = $driver;
}
/**
* @param callable $action
- * @param StoreInterface $store
+ * @param StoreInterface|null $store
+ * @param null $type
* @throws Exception
+ * phpcs:disable Generic.PHP.NoSilencedErrors.Discouraged
+ * phpcs:disable Magento2.Functions.DiscouragedFunction.Discouraged
+ * phpcs:disable Magento2.Functions.DiscouragedFunction.DiscouragedWithAlternative
+ * @SuppressWarnings(PHPMD.ErrorControlOperator)
*/
protected function executeLocked(callable $action, StoreInterface $store = null, $type = null): void
{
@@ -88,15 +106,17 @@ protected function executeLocked(callable $action, StoreInterface $store = null,
try {
$lockHandle = @fopen($lockFile, 'wb');
if (!$lockHandle) {
- $this->log->throwException(new LockException(sprintf('Could not lock feed export on lockfile "%s"', $lockFile)));
+ $this->log->throwException(
+ new LockException(sprintf('Could not lock feed export on lockfile "%s"', $lockFile))
+ );
}
- if (flock($lockHandle, LOCK_EX)) {
+ if ($this->driver->fileLock($lockHandle)) {
try {
$action();
} finally {
- flock($lockHandle, LOCK_UN);
- fclose($lockHandle);
+ $this->driver->fileLock($lockHandle, LOCK_UN);
+ $this->driver->fileClose($lockHandle);
}
} else {
$this->log->throwException(new LockException(sprintf('Unable to obtain lock on %s', $lockFile)));
@@ -105,6 +125,7 @@ protected function executeLocked(callable $action, StoreInterface $store = null,
if (file_exists($lockFile)) {
unlink($lockFile);
}
+
Profiler::stop('tweakwise::export');
}
}
@@ -120,10 +141,14 @@ protected function executeLocked(callable $action, StoreInterface $store = null,
public function generateFeed($targetHandle, $store = null, $type = null): void
{
header('Content-type: text/xml');
- $this->executeLocked(function () use ($targetHandle, $store, $type) {
- $this->writer->write($targetHandle, $store, $type);
- $this->touchFeedGenerateDate($store, $type);
- }, $store, $type);
+ $this->executeLocked(
+ function () use ($targetHandle, $store, $type) {
+ $this->writer->write($targetHandle, $store, $type);
+ $this->touchFeedGenerateDate($store, $type);
+ },
+ $store,
+ $type
+ );
}
/**
@@ -133,6 +158,10 @@ public function generateFeed($targetHandle, $store = null, $type = null): void
* @param null|StoreInterface $store
* @param null|string $type
* @throws Exception
+ * phpcs:disable Generic.PHP.NoSilencedErrors.Discouraged
+ * phpcs:disable Magento2.Functions.DiscouragedFunction.Discouraged
+ * phpcs:disable Magento2.Functions.DiscouragedFunction.DiscouragedWithAlternative
+ * @SuppressWarnings(PHPMD.ErrorControlOperator)
*/
public function getFeed($targetHandle, StoreInterface $store = null, $type = null): void
{
@@ -144,16 +173,19 @@ public function getFeed($targetHandle, StoreInterface $store = null, $type = nul
if (file_exists($feedFile)) {
$sourceHandle = @fopen($feedFile, 'rb');
if (!$sourceHandle) {
- $this->log->throwException(new FeedException(sprintf('Could not open feed path "%s" for reading', $feedFile)));
+ $this->log->throwException(
+ new FeedException(sprintf('Could not open feed path "%s" for reading', $feedFile))
+ );
}
header('Content-type: text/xml');
header('Cache-Control: no-cache');
- while (!feof($sourceHandle)) {
- fwrite($targetHandle, fread($sourceHandle, self::FEED_COPY_BUFFER_SIZE));
+ while (!$this->driver->endOfFile($sourceHandle)) {
+ $this->driver->fileWrite($targetHandle, fread($sourceHandle, self::FEED_COPY_BUFFER_SIZE));
}
- fclose($sourceHandle);
+
+ $this->driver->fileClose($sourceHandle);
} else {
$this->generateToFile($feedFile, $this->config->isValidate(), $store, $type);
$this->getFeed($targetHandle, $store, $type);
@@ -165,64 +197,72 @@ public function getFeed($targetHandle, StoreInterface $store = null, $type = nul
* @param bool $validate
* @param null|StoreInterface $store
* @throws Exception
+ * @SuppressWarnings(PHPMD.ErrorControlOperator)
*/
public function generateToFile($feedFile, $validate, $store = null, $type = null): void
{
- $this->executeLocked(function () use ($feedFile, $validate, $store, $type) {
- $tmpFeedFile = $this->config->getFeedTmpFile($feedFile, $store);
- $sourceHandle = @fopen($tmpFeedFile, 'wb');
+ $this->executeLocked(
+ function () use ($feedFile, $validate, $store, $type) {
+ $tmpFeedFile = $this->config->getFeedTmpFile($feedFile, $store);
+ $sourceHandle = @fopen($tmpFeedFile, 'wb');
- if (!$sourceHandle) {
- $this->log->throwException(new FeedException(sprintf('Could not open feed path "%s" for writing', $feedFile)));
- }
+ if (!$sourceHandle) {
+ $this->log->throwException(
+ new FeedException(sprintf('Could not open feed path "%s" for writing', $feedFile))
+ );
+ }
- try {
- // Write
try {
- $this->writer->write($sourceHandle, $store, $type);
- $this->log->debug('Feed exported to ' . $tmpFeedFile);
- } finally {
- fclose($sourceHandle);
- }
+ // Write
+ try {
+ $this->writer->write($sourceHandle, $store, $type);
+ $this->log->debug('Feed exported to ' . $tmpFeedFile);
+ } finally {
+ fclose($sourceHandle);
+ }
- // Validate
- if ($validate) {
- $this->validator->validate($tmpFeedFile);
- $this->log->debug('Feed validated ' . $tmpFeedFile);
- }
+ // Validate
+ if ($validate) {
+ $this->validator->validate($tmpFeedFile);
+ $this->log->debug('Feed validated ' . $tmpFeedFile);
+ }
+
+ // Archive
+ $maxSuffix = $this->config->getMaxArchiveFiles();
+ for ($suffix = $maxSuffix; $suffix > 0; $suffix--) {
+ $source = $feedFile . ($suffix > 1 ? '.' . ($suffix - 1) : '');
+ if (!file_exists($source)) {
+ continue;
+ }
- // Archive
- $maxSuffix = $this->config->getMaxArchiveFiles();
- for ($suffix = $maxSuffix; $suffix > 0; $suffix--) {
- $source = $feedFile . ($suffix > 1 ? '.' . ($suffix - 1) : '');
- if (!file_exists($source)) {
- continue;
+ $target = $feedFile . '.' . $suffix;
+ // Move
+ if (!rename($source, $target)) {
+ $this->log->debug('Archive feed rename failed (' . $source . ' to ' . $target . ')');
+ } else {
+ $this->log->debug('Archive feed renamed (' . $source . ' to ' . $target . ')');
+ }
}
- $target = $feedFile . '.' . $suffix;
- // Move
- if (!rename($source, $target)) {
- $this->log->debug('Archive feed rename failed (' . $source . ' to ' . $target . ')');
+
+ // Rename
+ if (!rename($tmpFeedFile, $feedFile)) {
+ $this->log->debug('Feed rename failed (' . $tmpFeedFile . ' to ' . $feedFile . ')');
} else {
- $this->log->debug('Archive feed renamed (' . $source . ' to ' . $target . ')');
+ $this->log->debug('Feed renamed (' . $tmpFeedFile . ' to ' . $feedFile . ')');
+ }
+ } finally {
+ // Remove temporary file
+ if (file_exists($tmpFeedFile)) {
+ unlink($tmpFeedFile);
}
}
- // Rename
- if (!rename($tmpFeedFile, $feedFile)) {
- $this->log->debug('Feed rename failed (' . $tmpFeedFile . ' to ' . $feedFile . ')');
- } else {
- $this->log->debug('Feed renamed (' . $tmpFeedFile . ' to ' . $feedFile . ')');
- }
- } finally {
- // Remove temporary file
- if (file_exists($tmpFeedFile)) {
- unlink($tmpFeedFile);
- }
- }
-
- $this->touchFeedGenerateDate($store, $type);
- $this->triggerTweakwiseImport($store, $type);
- }, $store, $type);
+ $this->touchFeedGenerateDate($store, $type);
+ $this->triggerTweakwiseImport($store, $type);
+ },
+ $store,
+ $type
+ );
}
/**
diff --git a/Model/Helper.php b/Model/Helper.php
index d1c73b9..46aeefd 100644
--- a/Model/Helper.php
+++ b/Model/Helper.php
@@ -1,4 +1,5 @@
getParam('store');
- if (!$this->config->isStoreLevelExportEnabled() && ($store !== null)){
+ if (!$this->config->isStoreLevelExportEnabled() && ($store !== null)) {
return false;
}
@@ -47,7 +47,7 @@ public function validateStoreKey(RequestInterface $request): bool
public function validateType(RequestInterface $request): bool
{
$type = $request->getParam('type');
- if ($type === 'stock' || $type === 'price' || empty($type)){
+ if ($type === 'stock' || $type === 'price' || empty($type)) {
return true;
}
diff --git a/Model/Review/MagentoReviewProvider.php b/Model/Review/MagentoReviewProvider.php
index 4af310b..578a86a 100644
--- a/Model/Review/MagentoReviewProvider.php
+++ b/Model/Review/MagentoReviewProvider.php
@@ -6,10 +6,6 @@
use Magento\Review\Model\ResourceModel\Review\Summary\CollectionFactory as SummaryCollectionFactory;
use Magento\Review\Model\Review\Summary;
-/**
- * Class MagentoReviewProvider
- * @package Tweakwise\Magento2TweakwiseExport\Model\Review
- */
class MagentoReviewProvider implements ReviewProviderInterface
{
/**
@@ -28,7 +24,7 @@ public function __construct(
}
/**
- * @param Collection $collection Tweakwise product collection
+ * @param Collection $collection
* @return ProductReviewSummary[]
*/
public function getProductReviews(Collection $collection): array
diff --git a/Model/Review/ProductReviewSummary.php b/Model/Review/ProductReviewSummary.php
index 86df70f..d012248 100644
--- a/Model/Review/ProductReviewSummary.php
+++ b/Model/Review/ProductReviewSummary.php
@@ -5,7 +5,6 @@
/**
* Class ProductSummary
* There is no Magento native review interface or summary interface, hence this class
- * @package Tweakwise\Magento2TweakwiseExport\Model\Review
*/
class ProductReviewSummary
{
diff --git a/Model/Review/ReviewProviderInterface.php b/Model/Review/ReviewProviderInterface.php
index 2702f68..fe5064e 100644
--- a/Model/Review/ReviewProviderInterface.php
+++ b/Model/Review/ReviewProviderInterface.php
@@ -6,12 +6,11 @@
/**
* Interface ReviewProviderInterface
- * @package Tweakwise\Magento2TweakwiseExport\Model\Review
*/
interface ReviewProviderInterface
{
/**
- * @param Collection $collection Tweakwise product collection
+ * @param Collection $collection
* @return ProductReviewSummary[]
*/
public function getProductReviews(Collection $collection): array;
diff --git a/Model/Scheduler.php b/Model/Scheduler.php
index 433ddb8..21f82f1 100644
--- a/Model/Scheduler.php
+++ b/Model/Scheduler.php
@@ -1,4 +1,5 @@
= 0) {
return $this->dateTime->gmtTimestamp();
}
+
return $this->timezone->scopeTimeStamp();
}
}
diff --git a/Model/StockItem.php b/Model/StockItem.php
index cad6717..f4b9ba0 100644
--- a/Model/StockItem.php
+++ b/Model/StockItem.php
@@ -2,7 +2,6 @@
namespace Tweakwise\Magento2TweakwiseExport\Model;
-
class StockItem
{
/**
@@ -24,7 +23,7 @@ public function getQty(): int
}
/**
- * @param int
+ * @param int $qty
*/
public function setQty(int $qty): void
{
diff --git a/Model/StockResolverFactory.php b/Model/StockResolverFactory.php
index 3aaf716..cc478d3 100644
--- a/Model/StockResolverFactory.php
+++ b/Model/StockResolverFactory.php
@@ -11,7 +11,6 @@
* setup:di:compile fails when there is a reference to a non existing Interface or Class in the constructor
*
* Class StockResolverFactory
- * @package Tweakwise\Magento2TweakwiseExport\Model
*/
class StockResolverFactory
{
diff --git a/Model/StockSourceProviderFactory.php b/Model/StockSourceProviderFactory.php
index 941803a..a653e62 100644
--- a/Model/StockSourceProviderFactory.php
+++ b/Model/StockSourceProviderFactory.php
@@ -11,7 +11,6 @@
* setup:di:compile fails when there is a reference to a non existing Interface or Class in the constructor
*
* Class StockSourceProviderFactory
- * @package Tweakwise\Magento2TweakwiseExport\Model
*/
class StockSourceProviderFactory
{
@@ -35,6 +34,9 @@ public function __construct(ObjectManagerInterface $objectManager)
*/
public function create($sourceData = null)
{
- return $this->_objectManager->create(GetSourcesAssignedToStockOrderedByPriorityInterface::class, ['sourceData' => $sourceData]);
+ return $this->_objectManager->create(
+ GetSourcesAssignedToStockOrderedByPriorityInterface::class,
+ ['sourceData' => $sourceData]
+ );
}
}
diff --git a/Model/Validate/Validator.php b/Model/Validate/Validator.php
index c1d0b13..092b6dd 100644
--- a/Model/Validate/Validator.php
+++ b/Model/Validate/Validator.php
@@ -1,4 +1,5 @@
message;
}
+
throw new ValidationException(join(PHP_EOL, $errors));
}
+
$this->validateCategoryLinks($xml);
} finally {
libxml_use_internal_errors($internalXmlErrors);
@@ -48,10 +53,11 @@ public function validate($file)
protected function validateCategoryLinks(SimpleXMLElement $xml)
{
$categoryIdElements = $xml->xpath('/tweakwise/categories/category/categoryid');
- $categoryIds = array();
+ $categoryIds = [];
foreach ($categoryIdElements as $id) {
$categoryIds[] = (string) $id;
}
+
$categoryIds = array_flip($categoryIds);
foreach ($xml->xpath('/tweakwise/categories/category/parents/categoryid') as $categoryIdElement) {
diff --git a/Model/Write/Categories.php b/Model/Write/Categories.php
index 254744f..6522b6a 100644
--- a/Model/Write/Categories.php
+++ b/Model/Write/Categories.php
@@ -1,4 +1,5 @@
writeCategory($xml, 0, ['entity_id' => 1, 'name' => 'Root', 'position' => 0]);
$stores = [];
- if ($store){
+ if ($store) {
$stores[] = $store;
} else {
$stores = $this->storeManager->getStores();
}
+
/** @var Store $store */
foreach ($stores as $store) {
if ($this->config->isEnabled($store)) {
@@ -111,6 +113,7 @@ public function write(Writer $writer, XMLWriter $xml, StoreInterface $store = n
* @param XMLWriter $xml
* @param Store $store
* @param int[] $entityIds
+ * @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
public function exportStore(Writer $writer, XMLWriter $xml, Store $store, array $entityIds = []): void
{
@@ -158,6 +161,7 @@ public function exportStore(Writer $writer, XMLWriter $xml, Store $store, array
$writer->flush();
}
}
+
// Flush any remaining categories
$writer->flush();
}
@@ -184,6 +188,7 @@ protected function writeCategory(XMLWriter $xml, int $storeId, array $data): voi
if ($parentId !== 1) {
$parentId = $this->helper->getTweakwiseId($storeId, $parentId);
}
+
$xml->writeElement('categoryid', $parentId);
$xml->endElement(); //
diff --git a/Model/Write/Categories/Iterator.php b/Model/Write/Categories/Iterator.php
index c0f2a96..4bbc60a 100644
--- a/Model/Write/Categories/Iterator.php
+++ b/Model/Write/Categories/Iterator.php
@@ -1,4 +1,5 @@
getEntityBatch()) {
try {
@@ -267,7 +276,10 @@ public function getIterator() : \Traversable
Profiler::start('loop');
try {
- $this->eventManager->dispatch('tweakwise_iterator_processbatch', ['batch_size' => count($entityIds), 'entity_code' => $this->entityCode]);
+ $this->eventManager->dispatch(
+ 'tweakwise_iterator_processbatch',
+ ['batch_size' => count($entityIds), 'entity_code' => $this->entityCode]
+ );
// Loop over all rows and combine them to one array for entity
foreach ($this->loopUnionRows($stmt) as $result) {
$result = array_merge($result, $this->entityData[$result['entity_id']]);
@@ -284,6 +296,7 @@ public function getIterator() : \Traversable
/**
* @return int[]|null
+ * @SuppressWarnings(PHPMD.MissingImport)
*/
protected function getEntityBatch(): ?array
{
@@ -365,6 +378,7 @@ protected function getEntityType(): Type
/**
* @param AbstractAttribute[] $attributes
* @return Select[]
+ * phpcs:disable Squiz.Arrays.ArrayDeclaration.KeySpecified
*/
protected function getStaticAttributeSelect(array $attributes): array
{
@@ -407,7 +421,7 @@ protected function getAttributeSelectCommunity(string $table, array $attributes)
$storeId = $this->store->getId();
if ($storeId) {
- $select->where('store_id = 0 OR store_id = ?',$storeId);
+ $select->where('store_id = 0 OR store_id = ?', $storeId);
} else {
$select->where('store_id = 0');
}
@@ -429,13 +443,19 @@ protected function getAttributeSelectEnterprise(string $table, array $attributes
$connection = $this->getConnection();
$select = $connection->select()
->from(['attribute_table' => $table], [])
- ->join(['main_table' => $this->getEntityType()->getEntityTable()], 'attribute_table.row_id = main_table.row_id', [])
- ->columns([
+ ->join(
+ ['main_table' => $this->getEntityType()->getEntityTable()],
+ 'attribute_table.row_id = main_table.row_id',
+ []
+ )
+ ->columns(
+ [
'entity_id' => 'main_table.entity_id',
'store_id' => 'attribute_table.store_id',
'attribute_id' => 'attribute_table.attribute_id',
'value' => 'attribute_table.value'
- ])
+ ]
+ )
->where('attribute_id IN (?)', array_keys($attributes));
$storeId = $this->store->getId();
@@ -467,8 +487,10 @@ protected function getAttributeGroups(): array
if (!isset($attributeGroups[$table])) {
$attributeGroups[$table] = [];
}
+
$attributeGroups[$table][$attributeId] = $attribute;
}
+
return $attributeGroups;
}
diff --git a/Model/Write/Price.php b/Model/Write/Price.php
index d52fef5..1bac3ea 100644
--- a/Model/Write/Price.php
+++ b/Model/Write/Price.php
@@ -1,4 +1,5 @@
storeManager->getStores();
}
+
/** @var Store $store */
foreach ($stores as $store) {
if ($this->config->isEnabled($store)) {
@@ -145,7 +147,6 @@ public function exportStore(Writer $writer, XMLWriter $xml, Store $store, array
$writer->flush();
}
-
/**
* @param XMLWriter $xml
* @param int $storeId
@@ -173,6 +174,7 @@ protected function writeProduct(XMLWriter $xml, $storeId, array $data): void
* @param mixed $value
*
* @return string|array
+ * phpcs:disable Magento2.Functions.DiscouragedFunction.Discouraged
*/
protected function scalarValue($value)
{
@@ -188,7 +190,7 @@ protected function scalarValue($value)
if (is_object($value)) {
if (method_exists($value, 'toString')) {
$value = $value->toString();
- } else if (method_exists($value, '__toString')) {
+ } elseif (method_exists($value, '__toString')) {
$value = (string)$value;
} else {
$value = spl_object_hash($value);
diff --git a/Model/Write/Price/Collection.php b/Model/Write/Price/Collection.php
index b01f5a8..ad9a419 100644
--- a/Model/Write/Price/Collection.php
+++ b/Model/Write/Price/Collection.php
@@ -50,7 +50,7 @@ public function add(ExportEntity $entity): void
/**
* @return ExportEntity[]|ArrayIterator
*/
- public function getIterator() : \Traversable
+ public function getIterator(): \Traversable
{
return new ArrayIterator($this->entities);
}
@@ -82,6 +82,7 @@ public function getIds(): array
/**
* @param int $id
* @return ExportEntity
+ * @throws InvalidArgumentException
*/
public function get(int $id): ExportEntity
{
@@ -114,6 +115,7 @@ public function getExported(): array
$result[$entity->getId()] = $entity;
}
+
return $result;
}
@@ -143,6 +145,7 @@ protected function ensureIdsAndSkus(): void
}
}
}
+
// Make unique
$this->ids = array_flip($ids);
$this->skus = array_flip($skus);
@@ -178,6 +181,8 @@ public function getAllSkus(): array
* Allow for removal of export entities
*
* @param int $id
+ * phpcs:disable Magento2.CodeAnalysis.EmptyBlock.DetectedCatch
+ * phpcs:disable Generic.CodeAnalysis.EmptyStatement.DetectedCatch
*/
public function remove(int $id): void
{
@@ -187,6 +192,7 @@ public function remove(int $id): void
if (!$entity) {
return;
}
+
try {
/** @var string|array $sku */
$sku = $entity->getAttribute('sku', false);
@@ -198,6 +204,7 @@ public function remove(int $id): void
*/
$sku = reset($sku);
}
+
/** @var string $sku */
unset($this->skus[$sku]);
} catch (InvalidArgumentException $e) {
diff --git a/Model/Write/Price/ExportEntity.php b/Model/Write/Price/ExportEntity.php
index 8ee6b26..55edae7 100644
--- a/Model/Write/Price/ExportEntity.php
+++ b/Model/Write/Price/ExportEntity.php
@@ -223,7 +223,7 @@ public function getCategories(): array
/**
* @param string $attribute
- * @param $value
+ * @param mixed $value
*/
public function addAttribute(string $attribute, $value): void
{
diff --git a/Model/Write/Price/ExportEntityFactory.php b/Model/Write/Price/ExportEntityFactory.php
index 0c28e85..9c1eb56 100644
--- a/Model/Write/Price/ExportEntityFactory.php
+++ b/Model/Write/Price/ExportEntityFactory.php
@@ -55,6 +55,7 @@ public function create(array $data = []): ExportEntity
if (!$typeId) {
$this->_objectManager->create(ExportEntity::class, $data);
}
+
return $this->_objectManager->create($this->getInstanceType($typeId), $data);
}
diff --git a/Model/Write/Price/Iterator.php b/Model/Write/Price/Iterator.php
index 9595841..015defe 100644
--- a/Model/Write/Price/Iterator.php
+++ b/Model/Write/Price/Iterator.php
@@ -1,4 +1,5 @@
collectionFactory->create(['store' => $this->store]);
foreach (parent::getIterator() as $entityData) {
@@ -105,6 +102,7 @@ public function getIterator() : \Traversable
foreach ($this->processBatch($batch) as $processedEntity) {
yield $processedEntity;
}
+
$batch = $this->collectionFactory->create(['store' => $this->store]);
}
}
diff --git a/Model/Write/Price/IteratorInitializer.php b/Model/Write/Price/IteratorInitializer.php
index 0cbec79..af25a32 100644
--- a/Model/Write/Price/IteratorInitializer.php
+++ b/Model/Write/Price/IteratorInitializer.php
@@ -5,10 +5,6 @@
use Tweakwise\Magento2TweakwiseExport\Model\ProductAttributes;
use Tweakwise\Magento2TweakwiseExport\Model\Write\EavIterator;
-/**
- * Class IteratorInitializer
- * @package Tweakwise\Magento2TweakwiseExport\Model\Write\Products
- */
class IteratorInitializer
{
/**
diff --git a/Model/Write/Products.php b/Model/Write/Products.php
index c71644e..f790b82 100644
--- a/Model/Write/Products.php
+++ b/Model/Write/Products.php
@@ -1,4 +1,5 @@
storeManager->getStores();
}
+
/** @var Store $store */
foreach ($stores as $store) {
if ($this->config->isEnabled($store)) {
@@ -145,7 +147,6 @@ public function exportStore(Writer $writer, XMLWriter $xml, Store $store, array
$writer->flush();
}
-
/**
* @param XMLWriter $xml
* @param int $storeId
@@ -174,6 +175,7 @@ protected function writeProduct(XMLWriter $xml, $storeId, array $data): void
);
}
}
+
$xml->endElement(); // categories
// Write product attributes
@@ -189,7 +191,6 @@ protected function writeProduct(XMLWriter $xml, $storeId, array $data): void
$this->log->debug(sprintf('Export product [%s] %s', $tweakwiseId, $data['name']));
}
-
/**
* @param XMLWriter $xml
* @param int $storeId
@@ -201,8 +202,7 @@ public function writeAttribute(
$storeId,
$name,
$attributeValue
- ): void
- {
+ ): void {
$values = $this->normalizeAttributeValue($storeId, $name, $attributeValue);
$values = array_unique($values);
@@ -249,6 +249,7 @@ protected function getAttributeOptionMap($storeId, AbstractAttribute $attribute)
* @param mixed $value
*
* @return string|array
+ * phpcs:disable Magento2.Functions.DiscouragedFunction.Discouraged
*/
protected function scalarValue($value)
{
@@ -264,7 +265,7 @@ protected function scalarValue($value)
if (is_object($value)) {
if (method_exists($value, 'toString')) {
$value = $value->toString();
- } else if (method_exists($value, '__toString')) {
+ } elseif (method_exists($value, '__toString')) {
$value = (string)$value;
} else {
$value = spl_object_hash($value);
@@ -322,6 +323,7 @@ protected function explodeValues(array $data, string $delimiter = ','): array
foreach ($data as $value) {
$result[] = explode($delimiter, $value) ?: [];
}
+
return !empty($result) ? array_merge([], ...$result) : [];
}
@@ -349,6 +351,7 @@ function ($value) {
$this->log->error($e->getMessage());
return $values;
}
+
// Attribute does not exists so just return value
if (!$attribute || !$attribute->getId()) {
return $values;
@@ -367,6 +370,7 @@ function ($value) {
$this->log->error($e->getMessage());
return $values;
}
+
if (!$attributeSource instanceof SourceInterface) {
return $values;
}
diff --git a/Model/Write/Products/Collection.php b/Model/Write/Products/Collection.php
index 8f47e58..4be6180 100644
--- a/Model/Write/Products/Collection.php
+++ b/Model/Write/Products/Collection.php
@@ -50,7 +50,7 @@ public function add(ExportEntity $entity): void
/**
* @return ExportEntity[]|ArrayIterator
*/
- public function getIterator() : \Traversable
+ public function getIterator(): \Traversable
{
return new ArrayIterator($this->entities);
}
@@ -82,6 +82,7 @@ public function getIds(): array
/**
* @param int $id
* @return ExportEntity
+ * @throws InvalidArgumentException
*/
public function get(int $id): ExportEntity
{
@@ -114,6 +115,7 @@ public function getExported(): array
$result[$entity->getId()] = $entity;
}
+
return $result;
}
@@ -143,6 +145,7 @@ protected function ensureIdsAndSkus(): void
}
}
}
+
// Make unique
$this->ids = array_flip($ids);
$this->skus = array_flip($skus);
@@ -178,6 +181,8 @@ public function getAllSkus(): array
* Allow for removal of export entities
*
* @param int $id
+ * phpcs:disable Magento2.CodeAnalysis.EmptyBlock.DetectedCatch
+ * phpcs:disable Generic.CodeAnalysis.EmptyStatement.DetectedCatch
*/
public function remove(int $id): void
{
@@ -187,6 +192,7 @@ public function remove(int $id): void
if (!$entity) {
return;
}
+
try {
/** @var string|array $sku */
$sku = $entity->getAttribute('sku', false);
@@ -198,6 +204,7 @@ public function remove(int $id): void
*/
$sku = reset($sku);
}
+
/** @var string $sku */
unset($this->skus[$sku]);
} catch (InvalidArgumentException $e) {
diff --git a/Model/Write/Products/CollectionDecorator/Children.php b/Model/Write/Products/CollectionDecorator/Children.php
index 97f3851..590032f 100644
--- a/Model/Write/Products/CollectionDecorator/Children.php
+++ b/Model/Write/Products/CollectionDecorator/Children.php
@@ -25,10 +25,6 @@
use Tweakwise\Magento2TweakwiseExport\Model\Write\Stock\Collection as StockCollection;
use Tweakwise\Magento2TweakwiseExport\Model\Write\Price\Collection as PriceCollection;
-/**
- * Class Children
- * @package Tweakwise\Magento2TweakwiseExport\Model\Write\Products\CollectionDecorator
- */
class Children implements DecoratorInterface
{
/**
@@ -86,7 +82,6 @@ class Children implements DecoratorInterface
* @param CollectionFactory $collectionFactory
* @param Helper $helper
* @param DbResourceHelper $dbResource
- * @param int $batchSize
* @param TweakwiseConfig $config
*/
public function __construct(
@@ -193,6 +188,7 @@ protected function addBundleChildren(Collection|StockCollection|PriceCollection
->columns(['product_id', 'parent_product_id'])
->where('parent_product_id IN (?)', $parentIds);
}
+
// Add Required bundle option data
$select->join(
['bundle_option' => $this->dbResource->getTableName('catalog_product_bundle_option')],
@@ -220,8 +216,11 @@ protected function addBundleChildren(Collection|StockCollection|PriceCollection
* @param int[] $parentIds
* @param int $typeId
*/
- protected function addLinkChildren(Collection|StockCollection|PriceCollection $collection, array $parentIds, $typeId): void
- {
+ protected function addLinkChildren(
+ Collection|StockCollection|PriceCollection $collection,
+ array $parentIds,
+ $typeId
+ ): void {
$connection = $this->dbResource->getConnection();
$select = $connection->select();
@@ -244,7 +243,6 @@ protected function addLinkChildren(Collection|StockCollection|PriceCollection $c
->where('product_id IN (?)', $parentIds);
}
-
$query = $select->query();
while ($row = $query->fetch()) {
$this->addChild($collection, (int) $row['product_id'], (int) $row['linked_product_id']);
@@ -255,12 +253,13 @@ protected function addLinkChildren(Collection|StockCollection|PriceCollection $c
* @param Collection|StockCollection|PriceCollection $collection
* @param int[] $parentIds
*/
- protected function addConfigurableChildren(Collection|StockCollection|PriceCollection $collection, array $parentIds): void
- {
+ protected function addConfigurableChildren(
+ Collection|StockCollection|PriceCollection $collection,
+ array $parentIds
+ ): void {
$connection = $this->dbResource->getConnection();
$select = $connection->select();
-
if ($this->helper->isEnterprise()) {
$select
->from(['product_table' => $this->dbResource->getTableName('catalog_product_entity')])
@@ -279,7 +278,6 @@ protected function addConfigurableChildren(Collection|StockCollection|PriceColle
->where('parent_id IN (?)', $parentIds);
}
-
$query = $select->query();
while ($row = $query->fetch()) {
$this->addChild($collection, (int) $row['parent_id'], (int) $row['product_id']);
@@ -291,14 +289,15 @@ protected function addConfigurableChildren(Collection|StockCollection|PriceColle
* @param int $parentId
* @param int $childId
* @param ChildOptions|null $childOptions
+ * phpcs:disable Magento2.CodeAnalysis.EmptyBlock.DetectedCatch
+ * phpcs:disable Generic.CodeAnalysis.EmptyStatement.DetectedCatch
*/
protected function addChild(
Collection|StockCollection|PriceCollection $collection,
int $parentId,
int $childId,
ChildOptions $childOptions = null
- ): void
- {
+ ): void {
if (!$this->childEntities->has($childId)) {
$child = $this->entityChildFactory->createChild(
[
@@ -310,6 +309,7 @@ protected function addChild(
} else {
$child = $this->childEntities->get($childId);
}
+
/** @var ExportEntityChild $child */
if ($childOptions) {
$child->setChildOptions($childOptions);
diff --git a/Model/Write/Products/CollectionDecorator/Price.php b/Model/Write/Products/CollectionDecorator/Price.php
index 5be5c1a..c5f705e 100644
--- a/Model/Write/Products/CollectionDecorator/Price.php
+++ b/Model/Write/Products/CollectionDecorator/Price.php
@@ -2,6 +2,7 @@
namespace Tweakwise\Magento2TweakwiseExport\Model\Write\Products\CollectionDecorator;
+// phpcs:disable Magento2.Legacy.RestrictedCode.ZendDbSelect
use Tweakwise\Magento2TweakwiseExport\Model\Config;
use Tweakwise\Magento2TweakwiseExport\Model\Write\Products\Collection;
use Magento\Catalog\Model\ResourceModel\Product\Collection as ProductCollection;
@@ -56,7 +57,7 @@ public function decorate(Collection|PriceCollection $collection): void
$currency = $collection->getStore()->getCurrentCurrency();
$exchangeRate = 1;
- if ($collection->getStore()->getCurrentCurrencyRate() > 0.00001){
+ if ($collection->getStore()->getCurrentCurrencyRate() > 0.00001) {
$exchangeRate = (float)$collection->getStore()->getCurrentCurrencyRate();
}
@@ -68,7 +69,7 @@ public function decorate(Collection|PriceCollection $collection): void
$row['price'] = $this->getPriceValue($row, $priceFields);
//do all prices * exchange rate
- foreach($priceFields as $priceField) {
+ foreach ($priceFields as $priceField) {
$row[$priceField] = (float) ($row[$priceField] * $exchangeRate);
}
@@ -80,6 +81,7 @@ public function decorate(Collection|PriceCollection $collection): void
* @param array $ids
* @param int $websiteId
* @return ProductCollection
+ * phpcs:disable Squiz.Arrays.ArrayDeclaration.KeySpecified
*/
protected function createPriceSelect(array $ids, int $websiteId): ProductCollection
{
diff --git a/Model/Write/Products/CollectionDecorator/Review.php b/Model/Write/Products/CollectionDecorator/Review.php
index ce6eaae..ab66cce 100644
--- a/Model/Write/Products/CollectionDecorator/Review.php
+++ b/Model/Write/Products/CollectionDecorator/Review.php
@@ -10,7 +10,6 @@
/**
* Class Review
* Add product reviews to feed
- * @package Tweakwise\Magento2TweakwiseExport\Model\Write\Products\CollectionDecorator
*/
class Review implements DecoratorInterface
{
diff --git a/Model/Write/Products/CollectionDecorator/StockData.php b/Model/Write/Products/CollectionDecorator/StockData.php
index b491de1..ecbab4c 100644
--- a/Model/Write/Products/CollectionDecorator/StockData.php
+++ b/Model/Write/Products/CollectionDecorator/StockData.php
@@ -177,8 +177,12 @@ protected function resolveStockMapProvider(): StockMapProviderInterface
if (version_compare($version, '2.3.0', '<')) {
return $this->stockMapProviders['stockItemMapProvider'];
}
+
// If 2.3.X but MSI is disabled also use stock items
- if (!$this->moduleManager->isEnabled('Magento_Inventory') || !$this->moduleManager->isEnabled('Magento_InventoryApi')) {
+ if (
+ !$this->moduleManager->isEnabled('Magento_Inventory') ||
+ !$this->moduleManager->isEnabled('Magento_InventoryApi')
+ ) {
return $this->stockMapProviders['stockItemMapProvider'];
}
diff --git a/Model/Write/Products/CollectionDecorator/StockData/SourceItemMapProvider.php b/Model/Write/Products/CollectionDecorator/StockData/SourceItemMapProvider.php
index 6c91ad6..30651a3 100644
--- a/Model/Write/Products/CollectionDecorator/StockData/SourceItemMapProvider.php
+++ b/Model/Write/Products/CollectionDecorator/StockData/SourceItemMapProvider.php
@@ -21,7 +21,6 @@
/**
* Class DefaultImplementation
- * @package Tweakwise\Magento2TweakwiseExport\Model\Write\Products\CollectionDecorator\StockData
*/
class SourceItemMapProvider implements StockMapProviderInterface
{
@@ -104,6 +103,8 @@ public function __construct(
* @return StockItem[]
* @throws LocalizedException
* @throws \Zend_Db_Statement_Exception
+ * phpcs:disable Squiz.Arrays.ArrayDeclaration.KeySpecified
+ * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function getStockItemMap(Collection|StockCollection $collection): array
{
@@ -237,7 +238,7 @@ protected function getSourceCodesForStore(Store $store): array
$sourceModels = $this->getStockSourceProvider()->execute($stockId);
//don't get stock for disabled stock sources
- foreach($sourceModels as $key => $sourceModel) {
+ foreach ($sourceModels as $key => $sourceModel) {
if (!$sourceModel->isEnabled()) {
unset($sourceModels[$key]);
}
diff --git a/Model/Write/Products/CollectionDecorator/StockData/StockItemMapProvider.php b/Model/Write/Products/CollectionDecorator/StockData/StockItemMapProvider.php
index 2f43531..4f3bde1 100644
--- a/Model/Write/Products/CollectionDecorator/StockData/StockItemMapProvider.php
+++ b/Model/Write/Products/CollectionDecorator/StockData/StockItemMapProvider.php
@@ -70,6 +70,7 @@ public function getStockItemMap(Collection|StockCollection $collection): array
$tweakwiseStockItem = $this->getTweakwiseStockItem($item);
$map[$productId] = $tweakwiseStockItem;
}
+
return $map;
}
diff --git a/Model/Write/Products/CollectionDecorator/StockData/StockMapProviderInterface.php b/Model/Write/Products/CollectionDecorator/StockData/StockMapProviderInterface.php
index 25ec9ec..31e9a94 100644
--- a/Model/Write/Products/CollectionDecorator/StockData/StockMapProviderInterface.php
+++ b/Model/Write/Products/CollectionDecorator/StockData/StockMapProviderInterface.php
@@ -8,7 +8,6 @@
/**
* Interface StockMapProviderInterface
- * @package Tweakwise\Magento2TweakwiseExport\Model\Write\Products\CollectionDecorator\StockData
*/
interface StockMapProviderInterface
{
diff --git a/Model/Write/Products/CompositeExportEntity.php b/Model/Write/Products/CompositeExportEntity.php
index b5d7bce..5640841 100644
--- a/Model/Write/Products/CompositeExportEntity.php
+++ b/Model/Write/Products/CompositeExportEntity.php
@@ -2,10 +2,6 @@
namespace Tweakwise\Magento2TweakwiseExport\Model\Write\Products;
-/**
- * Class CompositeExportEntity
- * @package Tweakwise\Magento2TweakwiseExport\Model\Write\Products
- */
class CompositeExportEntity extends ExportEntity implements CompositeExportEntityInterface
{
/**
diff --git a/Model/Write/Products/ExportEntity.php b/Model/Write/Products/ExportEntity.php
index e3bca1c..ccbed23 100644
--- a/Model/Write/Products/ExportEntity.php
+++ b/Model/Write/Products/ExportEntity.php
@@ -10,6 +10,9 @@
use Magento\Store\Model\StoreManagerInterface;
use Magento\Store\Model\Store;
+/**
+ * @SuppressWarnings(PHPMD.ExcessiveClassComplexity)
+ */
class ExportEntity
{
/**
@@ -248,7 +251,7 @@ public function getCategories(): array
/**
* @param string $attribute
- * @param $value
+ * @param mixed $value
*/
public function addAttribute(string $attribute, $value): void
{
diff --git a/Model/Write/Products/ExportEntityBundle.php b/Model/Write/Products/ExportEntityBundle.php
index 568c020..fbb8876 100644
--- a/Model/Write/Products/ExportEntityBundle.php
+++ b/Model/Write/Products/ExportEntityBundle.php
@@ -5,10 +5,6 @@
use Tweakwise\Magento2TweakwiseExport\Model\StockItem;
use Magento\Catalog\Model\Product\Attribute\Source\Status;
-/**
- * Class ExportEntityBundle
- * @package Tweakwise\Magento2TweakwiseExport\Model\Write\Products
- */
class ExportEntityBundle extends CompositeExportEntity
{
/**
@@ -18,6 +14,8 @@ class ExportEntityBundle extends CompositeExportEntity
/**
* @return StockItem
+ * @SuppressWarnings(PHPMD.CyclomaticComplexity)
+ * @SuppressWarnings(PHPMD.NPathComplexity)
*/
public function getStockItem(): ?StockItem
{
@@ -82,14 +80,17 @@ protected function shouldExportByChildStatus(): bool
if (!$childOptions) {
continue;
}
+
$optionId = $childOptions->getOptionId();
if (!$childOptions->isRequired()) {
$optionGroupStatus[$optionId] = 1;
continue;
}
+
if (isset($optionGroupStatus[$optionId]) && $optionGroupStatus[$optionId]) {
continue;
}
+
$childStatus = $child->getStatus() === Status::STATUS_ENABLED ? 1 : 0;
$optionGroupStatus[$optionId] = $childStatus;
}
diff --git a/Model/Write/Products/ExportEntityConfigurable.php b/Model/Write/Products/ExportEntityConfigurable.php
index f44427f..4d1b4f7 100644
--- a/Model/Write/Products/ExportEntityConfigurable.php
+++ b/Model/Write/Products/ExportEntityConfigurable.php
@@ -4,10 +4,6 @@
use Tweakwise\Magento2TweakwiseExport\Traits\Stock\HasStockThroughChildren;
-/**
- * Class ExportEntityConfigurable
- * @package Tweakwise\Magento2TweakwiseExport\Model\Write\Products
- */
class ExportEntityConfigurable extends CompositeExportEntity
{
use HasStockThroughChildren;
@@ -17,7 +13,6 @@ class ExportEntityConfigurable extends CompositeExportEntity
*/
protected $isStockCombined;
-
/**
* @param array $data
*/
diff --git a/Model/Write/Products/ExportEntityFactory.php b/Model/Write/Products/ExportEntityFactory.php
index 0a4948e..c8f302d 100644
--- a/Model/Write/Products/ExportEntityFactory.php
+++ b/Model/Write/Products/ExportEntityFactory.php
@@ -55,6 +55,7 @@ public function create(array $data = []): ExportEntity
if (!$typeId) {
$this->_objectManager->create(ExportEntity::class, $data);
}
+
return $this->_objectManager->create($this->getInstanceType($typeId), $data);
}
diff --git a/Model/Write/Products/ExportEntityGrouped.php b/Model/Write/Products/ExportEntityGrouped.php
index 25d4bc8..26e6d7f 100644
--- a/Model/Write/Products/ExportEntityGrouped.php
+++ b/Model/Write/Products/ExportEntityGrouped.php
@@ -4,10 +4,6 @@
use Tweakwise\Magento2TweakwiseExport\Traits\Stock\HasStockThroughChildren;
-/**
- * Class ExportEntityGrouped
- * @package Tweakwise\Magento2TweakwiseExport\Model\Write\Products
- */
class ExportEntityGrouped extends CompositeExportEntity
{
use HasStockThroughChildren;
diff --git a/Model/Write/Products/Iterator.php b/Model/Write/Products/Iterator.php
index 1c627b0..a354ff8 100644
--- a/Model/Write/Products/Iterator.php
+++ b/Model/Write/Products/Iterator.php
@@ -1,4 +1,5 @@
collectionFactory->create(['store' => $this->store]);
foreach (parent::getIterator() as $entityData) {
@@ -104,6 +101,7 @@ public function getIterator() : \Traversable
foreach ($this->processBatch($batch) as $processedEntity) {
yield $processedEntity;
}
+
$batch = $this->collectionFactory->create(['store' => $this->store]);
}
}
diff --git a/Model/Write/Products/IteratorInitializer.php b/Model/Write/Products/IteratorInitializer.php
index f73c6fc..2f310cf 100644
--- a/Model/Write/Products/IteratorInitializer.php
+++ b/Model/Write/Products/IteratorInitializer.php
@@ -5,10 +5,6 @@
use Tweakwise\Magento2TweakwiseExport\Model\ProductAttributes;
use Tweakwise\Magento2TweakwiseExport\Model\Write\EavIterator;
-/**
- * Class IteratorInitializer
- * @package Tweakwise\Magento2TweakwiseExport\Model\Write\Products
- */
class IteratorInitializer
{
/**
diff --git a/Model/Write/Stock.php b/Model/Write/Stock.php
index 1f474d3..3c5c09e 100644
--- a/Model/Write/Stock.php
+++ b/Model/Write/Stock.php
@@ -1,4 +1,5 @@
storeManager->getStores();
}
+
/** @var Store $store */
foreach ($stores as $store) {
if ($this->config->isEnabled($store)) {
@@ -145,7 +147,6 @@ public function exportStore(Writer $writer, XMLWriter $xml, Store $store, array
$writer->flush();
}
-
/**
* @param XMLWriter $xml
* @param int $storeId
@@ -173,6 +174,7 @@ protected function writeProduct(XMLWriter $xml, $storeId, array $data): void
* @param mixed $value
*
* @return string|array
+ * phpcs:disable Magento2.Functions.DiscouragedFunction.Discouraged
*/
protected function scalarValue($value)
{
@@ -188,7 +190,7 @@ protected function scalarValue($value)
if (is_object($value)) {
if (method_exists($value, 'toString')) {
$value = $value->toString();
- } else if (method_exists($value, '__toString')) {
+ } elseif (method_exists($value, '__toString')) {
$value = (string)$value;
} else {
$value = spl_object_hash($value);
diff --git a/Model/Write/Stock/Collection.php b/Model/Write/Stock/Collection.php
index 0697a69..54bd334 100644
--- a/Model/Write/Stock/Collection.php
+++ b/Model/Write/Stock/Collection.php
@@ -50,7 +50,7 @@ public function add(ExportEntity $entity): void
/**
* @return ExportEntity[]|ArrayIterator
*/
- public function getIterator() : \Traversable
+ public function getIterator(): \Traversable
{
return new ArrayIterator($this->entities);
}
@@ -82,6 +82,7 @@ public function getIds(): array
/**
* @param int $id
* @return ExportEntity
+ * @throws InvalidArgumentException
*/
public function get(int $id): ExportEntity
{
@@ -114,6 +115,7 @@ public function getExported(): array
$result[$entity->getId()] = $entity;
}
+
return $result;
}
@@ -143,6 +145,7 @@ protected function ensureIdsAndSkus(): void
}
}
}
+
// Make unique
$this->ids = array_flip($ids);
$this->skus = array_flip($skus);
@@ -178,6 +181,8 @@ public function getAllSkus(): array
* Allow for removal of export entities
*
* @param int $id
+ * phpcs:disable Magento2.CodeAnalysis.EmptyBlock.DetectedCatch
+ * phpcs:disable Generic.CodeAnalysis.EmptyStatement.DetectedCatch
*/
public function remove(int $id): void
{
@@ -187,6 +192,7 @@ public function remove(int $id): void
if (!$entity) {
return;
}
+
try {
/** @var string|array $sku */
$sku = $entity->getAttribute('sku', false);
@@ -198,6 +204,7 @@ public function remove(int $id): void
*/
$sku = reset($sku);
}
+
/** @var string $sku */
unset($this->skus[$sku]);
} catch (InvalidArgumentException $e) {
diff --git a/Model/Write/Stock/ExportEntity.php b/Model/Write/Stock/ExportEntity.php
index 6284b84..1c434cb 100644
--- a/Model/Write/Stock/ExportEntity.php
+++ b/Model/Write/Stock/ExportEntity.php
@@ -223,7 +223,7 @@ public function getCategories(): array
/**
* @param string $attribute
- * @param $value
+ * @param mixed $value
*/
public function addAttribute(string $attribute, $value): void
{
diff --git a/Model/Write/Stock/ExportEntityFactory.php b/Model/Write/Stock/ExportEntityFactory.php
index c166c68..57c73ef 100644
--- a/Model/Write/Stock/ExportEntityFactory.php
+++ b/Model/Write/Stock/ExportEntityFactory.php
@@ -55,6 +55,7 @@ public function create(array $data = []): ExportEntity
if (!$typeId) {
$this->_objectManager->create(ExportEntity::class, $data);
}
+
return $this->_objectManager->create($this->getInstanceType($typeId), $data);
}
diff --git a/Model/Write/Stock/Iterator.php b/Model/Write/Stock/Iterator.php
index 4205244..8b53cf8 100644
--- a/Model/Write/Stock/Iterator.php
+++ b/Model/Write/Stock/Iterator.php
@@ -1,4 +1,5 @@
collectionFactory->create(['store' => $this->store]);
foreach (parent::getIterator() as $entityData) {
@@ -105,6 +102,7 @@ public function getIterator() : \Traversable
foreach ($this->processBatch($batch) as $processedEntity) {
yield $processedEntity;
}
+
$batch = $this->collectionFactory->create(['store' => $this->store]);
}
}
diff --git a/Model/Write/Stock/IteratorInitializer.php b/Model/Write/Stock/IteratorInitializer.php
index c262c0b..cc58aaa 100644
--- a/Model/Write/Stock/IteratorInitializer.php
+++ b/Model/Write/Stock/IteratorInitializer.php
@@ -5,10 +5,6 @@
use Tweakwise\Magento2TweakwiseExport\Model\ProductAttributes;
use Tweakwise\Magento2TweakwiseExport\Model\Write\EavIterator;
-/**
- * Class IteratorInitializer
- * @package Tweakwise\Magento2TweakwiseExport\Model\Write\Products
- */
class IteratorInitializer
{
/**
diff --git a/Model/Write/Writer.php b/Model/Write/Writer.php
index e5203d3..675f043 100644
--- a/Model/Write/Writer.php
+++ b/Model/Write/Writer.php
@@ -1,4 +1,5 @@
storeManager = $storeManager;
$this->appState = $appState;
$this->writers = $writers;
$this->composerInformation = $composerInformation;
+ $this->driver = $driver;
}
/**
@@ -82,6 +91,7 @@ public function getNow(): DateTime
if (!$this->now) {
$this->now = new DateTime();
}
+
return $this->now;
}
@@ -132,6 +142,7 @@ public function write($resource, StoreInterface $store = null, $type = null): vo
foreach ($this->writers as $writer) {
$writer->write($this, $xml, $store);
}
+
$this->endDocument();
} finally {
$this->close();
@@ -184,7 +195,7 @@ public function flush(): void
{
$output = $this->getXml()->flush();
if ($output) {
- fwrite($this->resource, $output);
+ $this->driver->fileWrite($this->resource, $output);
}
}
@@ -236,6 +247,7 @@ protected function getModuleVersion(): string
// This should never be the case
return '';
}
+
$version = $installedPackages['tweakwise/magento2-tweakwise-export']['version'];
return sprintf('Magento2TweakwiseExport %s', $version);
@@ -252,14 +264,14 @@ protected function endDocument(): void
$this->flush();
}
- protected function determineWriters($type = null) : void
+ protected function determineWriters($type = null): void
{
if ($type === null) {
- unset ($this->writers['stock']);
+ unset($this->writers['stock']);
unset($this->writers['price']);
} else {
foreach ($this->writers as $key => $value) {
- if($type !== $key) {
+ if ($type !== $key) {
unset($this->writers[$key]);
}
}
diff --git a/Model/Write/WriterInterface.php b/Model/Write/WriterInterface.php
index b2c5a4c..d71ca02 100644
--- a/Model/Write/WriterInterface.php
+++ b/Model/Write/WriterInterface.php
@@ -1,4 +1,5 @@
xmlPrepare($value);
}
+
$this->text((string) $value);
if (!is_numeric($value) && !empty($value)) {
$this->endCdata();
}
+
parent::endElement();
return $this;
diff --git a/Profiler/Driver/ConsoleDriver.php b/Profiler/Driver/ConsoleDriver.php
index 0d34a5a..828490e 100644
--- a/Profiler/Driver/ConsoleDriver.php
+++ b/Profiler/Driver/ConsoleDriver.php
@@ -1,4 +1,5 @@
output->writeln(sprintf('[CodeProfiler][start] %s', $timerId));
} else {
- $this->output->writeln(sprintf(
- '[CodeProfiler][stop] %s %s (Memory usage: real - %s, emalloc - %s)',
- $timerId,
- number_format($data[Stat::TIME], 6),
- $data[Stat::REALMEM],
- $data[Stat::EMALLOC]
- ));
+ $this->output->writeln(
+ sprintf(
+ '[CodeProfiler][stop] %s %s (Memory usage: real - %s, emalloc - %s)',
+ $timerId,
+ number_format($data[Stat::TIME], 6),
+ $data[Stat::REALMEM],
+ $data[Stat::EMALLOC]
+ )
+ );
}
-
-
}
}
diff --git a/Test/Integration/Export/MultiStore/BasicTest.php b/Test/Integration/Export/MultiStore/BasicTest.php
index e334fb7..db1ca4e 100644
--- a/Test/Integration/Export/MultiStore/BasicTest.php
+++ b/Test/Integration/Export/MultiStore/BasicTest.php
@@ -1,4 +1,5 @@
configurableProvider = $this->getObject(ConfigurableProvider::class);
@@ -49,14 +50,21 @@ public function testConfigurableNotExportedWhenChildrenDisabledSingleStore()
$this->setConfig(Config::PATH_OUT_OF_STOCK_CHILDREN, false);
/** @var Product $product */
- $product = $this->configurableProvider->create([
+ $product = $this->configurableProvider->create(
+ [
['color' => 'black', 'qty' => 10],
['color' => 'blue', 'qty' => 10],
- ]);
+ ]
+ );
/** @var Product $configurableProduct */
foreach ($product->getData(ConfigurableProvider::GENERATED_CHILD_PRODUCTS) as $configurableProduct) {
- $this->productData->saveAttribute($configurableProduct, 'status', Status::STATUS_DISABLED, self::STORE_STORE_CODE);
+ $this->productData->saveAttribute(
+ $configurableProduct,
+ 'status',
+ Status::STATUS_DISABLED,
+ self::STORE_STORE_CODE
+ );
}
$feed = $this->exportFeed();
diff --git a/Test/Integration/Export/MultiStoreTest.php b/Test/Integration/Export/MultiStoreTest.php
index ff48a95..36117a0 100644
--- a/Test/Integration/Export/MultiStoreTest.php
+++ b/Test/Integration/Export/MultiStoreTest.php
@@ -1,4 +1,5 @@
storeProvider = $this->getObject(StoreProvider::class);
diff --git a/Test/Integration/Export/Product/AttributeOptionTest.php b/Test/Integration/Export/Product/AttributeOptionTest.php
index 0e21d50..02c5ddf 100644
--- a/Test/Integration/Export/Product/AttributeOptionTest.php
+++ b/Test/Integration/Export/Product/AttributeOptionTest.php
@@ -1,4 +1,5 @@
configurableProvider->create([
+ $product = $this->configurableProvider->create(
+ [
['color' => 'Black'],
['color' => 'Blue'],
- ]);
+ ]
+ );
// Remove one attribute
$this->attributeProvider->deleteOption('color', 'Blue');
diff --git a/Test/Integration/Export/Product/BasicTest.php b/Test/Integration/Export/Product/BasicTest.php
index 53301bb..9d70632 100644
--- a/Test/Integration/Export/Product/BasicTest.php
+++ b/Test/Integration/Export/Product/BasicTest.php
@@ -1,4 +1,5 @@
assertSku($product->getSku());
$feedProduct->assertName($product->getName());
$feedProduct->assertPrice($product->getPrice());
- $feedProduct->assertAttributes([
+ $feedProduct->assertAttributes(
+ [
'sku' => $product->getSku(),
'type_id' => 'simple',
'tax_class_id' => 'Taxable Goods',
- ]);
+ ]
+ );
$feedProduct->assertCategories([100012]);
}
}
diff --git a/Test/Integration/Export/Product/Configurable/ChildExportedTest.php b/Test/Integration/Export/Product/Configurable/ChildExportedTest.php
index bf24bf5..eeb4b34 100644
--- a/Test/Integration/Export/Product/Configurable/ChildExportedTest.php
+++ b/Test/Integration/Export/Product/Configurable/ChildExportedTest.php
@@ -1,4 +1,5 @@
configurableProvider = $this->getObject(ConfigurableProvider::class);
@@ -48,10 +50,20 @@ protected function setUp() : void
public function testVisibleSimples()
{
/** @var Product $product */
- $product = $this->configurableProvider->create([
- ['color' => 'black', 'status' => Status::STATUS_ENABLED, 'visibility' => Product\Visibility::VISIBILITY_BOTH],
- ['color' => 'blue', 'status' => Status::STATUS_ENABLED, 'visibility' => Product\Visibility::VISIBILITY_BOTH],
- ]);
+ $product = $this->configurableProvider->create(
+ [
+ [
+ 'color' => 'black',
+ 'status' => Status::STATUS_ENABLED,
+ 'visibility' => Product\Visibility::VISIBILITY_BOTH
+ ],
+ [
+ 'color' => 'blue',
+ 'status' => Status::STATUS_ENABLED,
+ 'visibility' => Product\Visibility::VISIBILITY_BOTH
+ ],
+ ]
+ );
$feed = $this->exportFeed();
$feed->getProduct($product->getId());
diff --git a/Test/Integration/Export/Product/Configurable/ExcludeAttributesTest.php b/Test/Integration/Export/Product/Configurable/ExcludeAttributesTest.php
index 1e01a8e..3b2f7f1 100644
--- a/Test/Integration/Export/Product/Configurable/ExcludeAttributesTest.php
+++ b/Test/Integration/Export/Product/Configurable/ExcludeAttributesTest.php
@@ -1,4 +1,5 @@
configurableProvider = $this->getObject(ConfigurableProvider::class);
@@ -48,11 +50,13 @@ protected function setUp() : void
public function testAttributesWhenDisabled()
{
/** @var Product $product */
- $product = $this->configurableProvider->create([
+ $product = $this->configurableProvider->create(
+ [
['color' => 'Black', 'status' => Status::STATUS_ENABLED],
['color' => 'Blue', 'status' => Status::STATUS_ENABLED],
['color' => 'White', 'status' => Status::STATUS_DISABLED],
- ]);
+ ]
+ );
$feed = $this->exportFeed();
$feed->getProduct($product->getId())->assertAttributes(['color' => ['Black', 'Blue']]);
@@ -98,6 +102,10 @@ public function testAttributesHiddenWhenIncluded()
['color' => $parentColorId]
);
- $this->exportFeed()->getProduct($product->getId())->assertAttributes(['color' => ['parent color', 'child color']]);
+ $this->exportFeed()->getProduct($product->getId())->assertAttributes(
+ [
+ 'color' => ['parent color', 'child color']
+ ]
+ );
}
}
diff --git a/Test/Integration/Export/Product/Configurable/StatusTest.php b/Test/Integration/Export/Product/Configurable/StatusTest.php
index 5c72cc9..1767fa3 100644
--- a/Test/Integration/Export/Product/Configurable/StatusTest.php
+++ b/Test/Integration/Export/Product/Configurable/StatusTest.php
@@ -1,4 +1,5 @@
configurableProvider = $this->getObject(ConfigurableProvider::class);
@@ -36,11 +38,13 @@ protected function setUp() : void
*/
public function testAttributesWhenDisabled()
{
- $product = $this->configurableProvider->create([
+ $product = $this->configurableProvider->create(
+ [
['color' => 'black', 'status' => Status::STATUS_ENABLED],
['color' => 'blue', 'status' => Status::STATUS_ENABLED],
['color' => 'white', 'status' => Status::STATUS_DISABLED],
- ]);
+ ]
+ );
$this->exportFeed()->getProduct($product->getId())->assertAttributes(['color' => ['black', 'blue']]);
}
@@ -50,11 +54,13 @@ public function testAttributesWhenDisabled()
*/
public function testWhenAllSimpleDisabled()
{
- $product = $this->configurableProvider->create([
+ $product = $this->configurableProvider->create(
+ [
['color' => 'black', 'status' => Status::STATUS_DISABLED],
['color' => 'blue', 'status' => Status::STATUS_DISABLED],
['color' => 'white', 'status' => Status::STATUS_DISABLED],
- ]);
+ ]
+ );
$this->exportFeed()->assertProductMissing($product->getId());
}
diff --git a/Test/Integration/Export/Product/Configurable/StockTest.php b/Test/Integration/Export/Product/Configurable/StockTest.php
index e7ea25d..aa2c6b5 100644
--- a/Test/Integration/Export/Product/Configurable/StockTest.php
+++ b/Test/Integration/Export/Product/Configurable/StockTest.php
@@ -1,4 +1,5 @@
configurableProvider = $this->getObject(ConfigurableProvider::class);
@@ -42,11 +44,13 @@ public function testAttributesVisibleWhenOutStock()
$this->setConfig(StockConfiguration::XML_PATH_SHOW_OUT_OF_STOCK, false);
$this->setConfig(Config::PATH_OUT_OF_STOCK_CHILDREN, true);
- $product = $this->configurableProvider->create([
+ $product = $this->configurableProvider->create(
+ [
['color' => 'black', 'qty' => 0],
['color' => 'blue', 'qty' => 10],
['color' => 'white', 'qty' => 2],
- ]);
+ ]
+ );
$this->exportFeed()->getProduct($product->getId())->assertAttributes(['color' => ['black', 'blue', 'white']]);
}
@@ -60,11 +64,13 @@ public function testAttributesNotVisibleWhenOutStock()
$this->setConfig(StockConfiguration::XML_PATH_SHOW_OUT_OF_STOCK, false);
$this->setConfig(Config::PATH_OUT_OF_STOCK_CHILDREN, false);
- $product = $this->configurableProvider->create([
+ $product = $this->configurableProvider->create(
+ [
['color' => 'black', 'qty' => 0],
['color' => 'blue', 'qty' => 10],
['color' => 'white', 'qty' => 2],
- ]);
+ ]
+ );
$this->exportFeed()->getProduct($product->getId())->assertAttributes(['color' => ['blue', 'white']]);
}
@@ -78,11 +84,13 @@ public function testAttributesNotVisibleWhenOutStockWithProductSpecificConfigura
$this->setConfig(StockConfiguration::XML_PATH_SHOW_OUT_OF_STOCK, false);
$this->setConfig(Config::PATH_OUT_OF_STOCK_CHILDREN, false);
- $product = $this->configurableProvider->create([
+ $product = $this->configurableProvider->create(
+ [
['color' => 'black', 'qty' => 0],
['color' => 'blue', 'qty' => 10],
['color' => 'white', 'qty' => 2, 'use_config_min_qty' => false, 'min_qty' => 5],
- ]);
+ ]
+ );
$this->exportFeed()->getProduct($product->getId())->assertAttributes(['color' => 'blue']);
}
@@ -96,10 +104,12 @@ public function testProductNotExportWhenOutStockWithProductSpecificConfiguration
$this->setConfig(StockConfiguration::XML_PATH_SHOW_OUT_OF_STOCK, false);
$this->setConfig(Config::PATH_OUT_OF_STOCK_CHILDREN, false);
- $product = $this->configurableProvider->create([
+ $product = $this->configurableProvider->create(
+ [
['color' => 'black', 'qty' => 0],
['color' => 'white', 'qty' => 2, 'use_config_min_qty' => false, 'min_qty' => 5],
- ]);
+ ]
+ );
$this->exportFeed()->assertProductMissing($product->getId());
}
diff --git a/Test/Integration/Export/Product/StockTest.php b/Test/Integration/Export/Product/StockTest.php
index 44cc242..88690d6 100644
--- a/Test/Integration/Export/Product/StockTest.php
+++ b/Test/Integration/Export/Product/StockTest.php
@@ -1,4 +1,5 @@
getObject(MutableScopeConfigInterface::class);
$config->setValue($path, $value, $scope, $store);
diff --git a/Test/TestCase.php b/Test/TestCase.php
index 2d96339..23d3778 100644
--- a/Test/TestCase.php
+++ b/Test/TestCase.php
@@ -1,4 +1,5 @@
$method($value);
}
}
+
return $object;
}
@@ -64,6 +65,7 @@ protected function getFieldToMethodFilter(): FilterInterface
$this->fieldToMethodFilter = $filter;
}
+
return $this->fieldToMethodFilter;
}
@@ -77,6 +79,7 @@ protected function getReflectionClass(string $class): ReflectionClass
if (!isset($this->reflectionCache[$class])) {
$this->reflectionCache[$class] = new ReflectionClass($class);
}
+
return $this->reflectionCache[$class];
}
@@ -97,6 +100,7 @@ protected function getSetMethod(string $class, string $field)
$this->methodCache[$key] = $reflection->hasMethod($method) ? $method : false;
}
+
return $this->methodCache[$key];
}
}
diff --git a/TestHelper/Data/Product/AttributeProvider.php b/TestHelper/Data/Product/AttributeProvider.php
index 86b3d51..4cf5a27 100644
--- a/TestHelper/Data/Product/AttributeProvider.php
+++ b/TestHelper/Data/Product/AttributeProvider.php
@@ -1,4 +1,5 @@
eavConfig = $eavConfig;
$this->categorySetup = $categorySetup;
$this->eavSetup = $eavSetup;
@@ -121,10 +121,12 @@ public function getOptionId(string $code, string $label): int
return $option->getId();
}
- $this->eavSetup->addAttributeOption([
+ $this->eavSetup->addAttributeOption(
+ [
'values' => [0 => $label],
'attribute_id' => $attribute->getAttributeId(),
- ]);
+ ]
+ );
$attribute->setOptions();
return $this->getOptionId($code, $label);
@@ -139,11 +141,13 @@ public function deleteOption(string $code, string $label)
{
$attribute = $this->get($code);
$optionId = $this->getOptionId($code, $label);
- $this->eavSetup->addAttributeOption([
+ $this->eavSetup->addAttributeOption(
+ [
'value' => [$optionId => ''],
'delete' => [$optionId => true],
'attribute_id' => $attribute->getAttributeId(),
- ]);
+ ]
+ );
$attribute->setOptions();
}
}
diff --git a/TestHelper/Data/Product/ConfigurableProvider.php b/TestHelper/Data/Product/ConfigurableProvider.php
index 9159c25..9e7bac2 100644
--- a/TestHelper/Data/Product/ConfigurableProvider.php
+++ b/TestHelper/Data/Product/ConfigurableProvider.php
@@ -1,4 +1,5 @@
productProvider = $productProvider;
$this->attributeProvider = $attributeProvider;
$this->optionsFactory = $optionsFactory;
@@ -74,8 +76,7 @@ public function create(
array $simpleData,
array $productData = [],
array $configurableAttributes = ['color']
- ): ProductInterface
- {
+ ): ProductInterface {
if (!isset($productData['type_id'])) {
$productData['type_id'] = Configurable::TYPE_CODE;
}
@@ -87,6 +88,7 @@ public function create(
foreach ($configurableAttributes as $attribute) {
$this->attributeProvider->ensureSet($attribute, 'Default');
}
+
$product = $this->productProvider->create($productData);
$simpleProducts = $this->createSimpleProducts($simpleData, $configurableAttributes);
@@ -127,17 +129,21 @@ protected function createSimpleProducts(array $simplesData, array $configurableA
* @param array $data
* @param array $configurableAttributes
* @return ProductInterface
+ * @throws LocalizedException
+ * @throws RuntimeException
*/
protected function createSimpleProduct(array $data, array $configurableAttributes): ProductInterface
{
// Rewrite configurable data to option values
foreach ($configurableAttributes as $attributeCode) {
if (!isset($data[$attributeCode])) {
- throw new RuntimeException(sprintf(
- 'Attribute code %s does not exists in simple data %s',
- $attributeCode,
- Json::encode($data)
- ));
+ throw new RuntimeException(
+ sprintf(
+ 'Attribute code %s does not exists in simple data %s',
+ $attributeCode,
+ Json::encode($data)
+ )
+ );
}
if (!\is_int($data[$attributeCode])) {
diff --git a/TestHelper/Data/ProductProvider.php b/TestHelper/Data/ProductProvider.php
index 0f93c96..78de048 100644
--- a/TestHelper/Data/ProductProvider.php
+++ b/TestHelper/Data/ProductProvider.php
@@ -1,4 +1,5 @@
faker = Factory::create();
$this->productRepository = $productRepository;
$this->productFactory = $productFactory;
@@ -174,6 +176,7 @@ public function create(array $data = [], array $extensionAttributeData = []): Pr
if ($data['qty'] > 0 && !isset($data['is_in_stock'])) {
$data['is_in_stock'] = 1;
}
+
$this->updateStockItem($product, $data);
// Assign product to categories
@@ -201,7 +204,7 @@ public function save(ProductInterface $product)
/**
* @param ProductInterface $product
* @param string $attribute
- * @param $value
+ * @param mixed $value
* @param string|null $store
*/
public function saveAttribute(ProductInterface $product, string $attribute, $value, string $store = null)
diff --git a/TestHelper/Data/StoreProvider.php b/TestHelper/Data/StoreProvider.php
index 2062564..aa7024e 100644
--- a/TestHelper/Data/StoreProvider.php
+++ b/TestHelper/Data/StoreProvider.php
@@ -1,4 +1,5 @@
faker = Factory::create();
$this->hydrator = $hydrator;
$this->websiteFactory = $websiteFactory;
@@ -138,6 +138,8 @@ public function createWebsite(array $data = []): WebsiteInterface
*
* @param string $code
* @return bool
+ * @throws \Exception
+ * @throws BadMethodCallException
*/
public function removeWebsite(string $code): bool
{
@@ -211,6 +213,8 @@ public function createStoreGroup(WebsiteInterface $website = null, array $data =
*
* @param string $code
* @return bool
+ * @throws \Exception
+ * @throws BadMethodCallException
*/
public function removeStoreGroup(string $code): bool
{
@@ -279,6 +283,8 @@ public function createStoreView(GroupInterface $group = null, array $data = []):
*
* @param string $code
* @return bool
+ * @throws \Exception
+ * @throws BadMethodCallException
*/
public function removeStoreView(string $code): bool
{
diff --git a/TestHelper/FeedData.php b/TestHelper/FeedData.php
index b30e196..94682ea 100644
--- a/TestHelper/FeedData.php
+++ b/TestHelper/FeedData.php
@@ -1,4 +1,5 @@
helper = $helper;
$this->storeManager = $storeManager;
$this->feed = $feed;
@@ -139,11 +139,13 @@ public function assertProductMissing(int $entityId, string $storeCode = null)
return;
}
- $this->test->fail(sprintf(
- 'Product for store %s with id %s was not supposed to be in de the feed.',
- $store->getCode(),
- $entityId
- ));
+ $this->test->fail(
+ sprintf(
+ 'Product for store %s with id %s was not supposed to be in de the feed.',
+ $store->getCode(),
+ $entityId
+ )
+ );
}
/**
@@ -206,6 +208,7 @@ protected function getStore(string $storeCode = null): StoreInterface
if (!$store) {
$this->test->fail('Default store not set and no store id provided.');
}
+
return $store;
}
}
diff --git a/TestHelper/FeedData/ProductData.php b/TestHelper/FeedData/ProductData.php
index a150032..fee27c8 100644
--- a/TestHelper/FeedData/ProductData.php
+++ b/TestHelper/FeedData/ProductData.php
@@ -103,6 +103,7 @@ public function assertAttributes(array $attributes)
if (\is_array($this->attributes[$key])) {
asort($this->attributes[$key]);
}
+
$this->test->assertEquals($value, $this->attributes[$key]);
}
}
@@ -118,7 +119,6 @@ public function assertCategories(array $categories)
$this->parseCategories();
}
-
$this->test->safeAssertArraySubset($categories, $this->categories);
}
@@ -130,6 +130,7 @@ protected function parsePrice()
if ($this->price !== null) {
return;
}
+
$this->price = (float) $this->element->price;
}
diff --git a/phpcs.xml b/phpcs.xml
index 2eb1290..1b47977 100644
--- a/phpcs.xml
+++ b/phpcs.xml
@@ -11,5 +11,11 @@
+
+
+
+
+
+
diff --git a/registration.php b/registration.php
index 4b34ba4..f8f0e7c 100644
--- a/registration.php
+++ b/registration.php
@@ -1,4 +1,5 @@