From ab98a00ff951cd32e29608b2f918d4b258673de3 Mon Sep 17 00:00:00 2001 From: Michael Telgmann Date: Sat, 13 Jan 2018 12:14:10 +0100 Subject: [PATCH 1/3] Add cs-fixer and fix code style --- .eslintignore | 0 .githooks/install_hooks.sh | 5 + .githooks/pre-commit | 225 ++++++++++++++++ .php_cs.dist | 31 +++ Bootstrap.php | 24 +- Bundle/SearchBundle/SortProductSearch.php | 16 +- .../StoreFrontBundle/ListProductService.php | 13 +- Components/Listing.php | 13 +- Components/Sorting.php | 18 +- Controllers/Backend/CustomSort.php | 253 +++++++++--------- Models/CustomSort/ArticleSort.php | 26 +- Models/CustomSort/CustomSortRepository.php | 144 +++++----- README.md | 12 +- Sorter/Sort/DragDropSorting.php | 3 +- Sorter/Sort/RatingSorting.php | 4 +- Sorter/Sort/StockSorting.php | 3 +- Sorter/SortDBAL/Handler/DragDropHandler.php | 56 ++-- .../SortDBAL/Handler/RatingSortingHandler.php | 11 +- .../SortDBAL/Handler/StockSortingHandler.php | 11 +- Sorter/SortFactory.php | 5 +- Subscriber/Backend.php | 36 +-- Subscriber/ControllerPath.php | 24 +- Subscriber/Frontend.php | 10 +- Subscriber/Resource.php | 11 +- Subscriber/Sort.php | 17 +- Subscriber/StoreFrontBundle.php | 15 +- 26 files changed, 627 insertions(+), 359 deletions(-) create mode 100644 .eslintignore create mode 100755 .githooks/install_hooks.sh create mode 100755 .githooks/pre-commit create mode 100644 .php_cs.dist diff --git a/.eslintignore b/.eslintignore new file mode 100644 index 0000000..e69de29 diff --git a/.githooks/install_hooks.sh b/.githooks/install_hooks.sh new file mode 100755 index 0000000..6187077 --- /dev/null +++ b/.githooks/install_hooks.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env php +writeln(); + $this->writeln('Checking commit requirements', 0); + $this->writeln(); + + if ($this->isRebase()) { + echo 'Not on branch' . PHP_EOL; + + return (int) 0; + } + + $this->runPhpLint($this->getCommittedFileList('php')); + $this->runPhpCsFixer($this->getCommittedFileList('php')); + $this->runEsLint($this->getCommittedFileList('js')); + + if ($this->error) { + $this->writeln("If you are ABSOLUTELY sure your code is correct, you can use 'git commit --no-verify' to bypass this validation", 0); + } + + exit((int) $this->error); + } + + /** + * @param string $output + * @param int $level + */ + private function writeln($output = '', $level = 1) + { + $this->write($output, $level); + echo PHP_EOL; + } + + /** + * @param string $output + * @param int $level + */ + private function write($output = '', $level = 1) + { + $spaces = $level * 3; + + echo str_pad($output, strlen($output) + $spaces, ' ', STR_PAD_LEFT); + } + + /** + * @return bool + */ + private function isRebase() + { + $output = []; + exec('git symbolic-ref --short -q HEAD', $output); + + return empty($output); + } + + /** + * @param string $extension + * @return string[] + */ + private function getCommittedFileList($extension = 'php') + { + exec("git diff --name-only --diff-filter=ACMRTUXB \"HEAD\" | grep -e '\." . $extension . "$'", $fileList); + + return $fileList; + } + + /** + * @param array $fileList + */ + private function runPhpLint(array $fileList) + { + $this->writeln('# Checking php syntax'); + $this->writeln('> php -l'); + + foreach ($fileList as $file) { + exec('php -l ' . escapeshellarg($file) . ' 2> /dev/null', $output, $return); + if ($return !== 0) { + $this->writeln('- ' . $output[1], 2); + $this->error = true; + } + } + + $this->writeln(); + } + + /** + * @param array $fileList + */ + private function runPhpCsFixer(array $fileList) + { + $this->writeln('# Checking php code style'); + $this->writeln('> php-cs-fixer fix -v --no-ansi --dry-run'); + + if (!$this->isPHPCSFixerAvailable()) { + $this->error = true; + $this->writeln('- php-cs-fixer is NOT installed. Please install composer with dev dependencies.', 2); + $this->writeln(); + + return; + } + + foreach ($fileList as $file) { + exec('./../../../../../../vendor/bin/php-cs-fixer fix -v --no-ansi --dry-run ' . escapeshellarg($file) . ' 2>&1', $output, $return); + + if ($return !== 0) { + $this->writeln('- ' . preg_replace('#^(\s+)?\d\)\s#', '', $output[3]), 2); + $fixes[] = './../../../../../../vendor/bin/php-cs-fixer fix -v ' . escapeshellarg($file); + $this->error = true; + } + } + + if (!empty($fixes)) { + $this->writeln(); + $this->writeln('Help:', 2); + foreach ($fixes as $fix) { + $this->writeln($fix, 3); + } + } + + $this->writeln(); + } + + /** + * @param array $fileList + */ + private function runEsLint(array $fileList) + { + $this->writeln('# Checking javascript code style'); + $this->writeln('> eslint.js --ignore-path .eslintignore'); + + if (!$this->isESLintAvailable()) { + $this->writeln('- eslint.js not found. Skipping javascript code style check.', 2); + $this->writeln(); + + return; + } + + $this->checkESLint($fileList); + + $this->writeln(); + } + + /** + * @return bool + */ + private function isPHPCSFixerAvailable() + { + $output = []; + $return = 0; + exec('command -v ./../../../../../../vendor/bin/php-cs-fixer >/dev/null 2>&1', $output, $return); + + return !(bool) $return; + } + + /** + * @return bool + */ + private function isESLintAvailable() + { + $output = []; + $return = 0; + exec('command -v ./../../../../../../themes/node_modules/eslint/bin/eslint.js >/dev/null 2>&1', $output, $return); + + return !(bool) $return; + } + + /** + * @param array $fileList + */ + private function checkESLint(array $fileList = []) + { + $output = []; + $return = 0; + exec( + './../../../../../../themes/node_modules/eslint/bin/eslint.js ' . + '--ignore-path .eslintignore ' . + '-c ./../../../../../../themes/.eslintrc.js ' . + '--global "Ext" ' . + implode(' ', $fileList), + $output, + $return + ); + $return = !(bool) $return; + + if (!$return) { + $this->error = true; + + foreach ($output as $line) { + $this->writeln($line, 2); + } + + $this->writeln('Help:', 2); + $this->writeln( + './../../../../../../themes/node_modules/eslint/bin/eslint.js ' . + '--fix --ignore-path .eslintignore ' . + '-c ./../../../../../../themes/.eslintrc.js ' . + '--global "Ext" ' . + implode(' ', $fileList), + 3 + ); + } + } +} + +$checks = new PreCommitChecks(); +$checks->run(); diff --git a/.php_cs.dist b/.php_cs.dist new file mode 100644 index 0000000..e69d497 --- /dev/null +++ b/.php_cs.dist @@ -0,0 +1,31 @@ +in(__DIR__) +; + +$header = << + +For the full copyright and license information, please view the LICENSE +file that was distributed with this source code. +EOF; + +return PhpCsFixer\Config::create() + ->setUsingCache(false) + ->setRules([ + '@PSR2' => true, + '@Symfony' => true, + 'header_comment' => ['header' => $header, 'separate' => 'bottom', 'commentType' => 'PHPDoc'], + 'no_useless_else' => true, + 'no_useless_return' => true, + 'ordered_class_elements' => true, + 'ordered_imports' => true, + 'phpdoc_order' => true, + 'phpdoc_summary' => false, + 'blank_line_after_opening_tag' => false, + 'concat_space' => ['spacing' => 'one'], + 'array_syntax' => ['syntax' => 'short'] + ]) + ->setFinder($finder) +; diff --git a/Bootstrap.php b/Bootstrap.php index 7f4dc1a..b18595e 100644 --- a/Bootstrap.php +++ b/Bootstrap.php @@ -1,10 +1,9 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. - * */ use Shopware\Models\Config\Element; @@ -37,8 +36,9 @@ public function getLabel() /** * Returns the version of the plugin as a string * - * @return string|void * @throws Exception + * + * @return string|void */ public function getVersion() { @@ -46,16 +46,16 @@ public function getVersion() if ($info) { return $info['currentVersion']; - } else { - throw new Exception('The plugin has an invalid version file.'); } + throw new Exception('The plugin has an invalid version file.'); } /** * Install Plugin / Add Events * - * @return bool * @throws Exception + * + * @return bool */ public function install() { @@ -74,6 +74,7 @@ public function install() /** * @param string $version + * * @return bool */ public function update($version) @@ -138,7 +139,7 @@ public function onStartDispatch() new Frontend($this), new Backend($this, $this->get('models')), new Sort($this->get('models'), $sortingComponent, $listingComponent), - new StoreFrontBundle($container, $sortingComponent) + new StoreFrontBundle($container, $sortingComponent), ]; foreach ($subscribers as $subscriber) { @@ -191,7 +192,6 @@ public function createDatabase() try { $tool->createSchema($classes); } catch (\Doctrine\ORM\Tools\ToolsException $e) { - // } } @@ -253,7 +253,7 @@ protected function createForm(Form $form) 'value' => 'Individuelle Sortierung', 'description' => 'Die neue Sortierung ist unter diesem Namen im Frontend sichtbar.', 'required' => true, - 'scope' => Element::SCOPE_SHOP + 'scope' => Element::SCOPE_SHOP, ] ); @@ -263,9 +263,9 @@ protected function createForm(Form $form) 'swagCustomSortName' => [ 'label' => 'Name', 'description' => 'The new sort will be visible in the frontend under this name.', - 'value' => 'Custom Sorting' - ] - ] + 'value' => 'Custom Sorting', + ], + ], ] ); } diff --git a/Bundle/SearchBundle/SortProductSearch.php b/Bundle/SearchBundle/SortProductSearch.php index 4480bdc..6eec42b 100644 --- a/Bundle/SearchBundle/SortProductSearch.php +++ b/Bundle/SearchBundle/SortProductSearch.php @@ -1,41 +1,40 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. - * */ namespace Shopware\SwagCustomSort\Bundle\SearchBundle; use Shopware\Bundle\SearchBundle\Criteria; +use Shopware\Bundle\SearchBundle\ProductNumberSearchResult; use Shopware\Bundle\SearchBundle\ProductSearchInterface; use Shopware\Bundle\SearchBundle\ProductSearchResult; use Shopware\Bundle\StoreFrontBundle\Struct; -use Shopware\Bundle\SearchBundle\ProductNumberSearchResult; use Shopware\SwagCustomSort\Components\Sorting; /** * @category Shopware - * @package ShopwarePlugins\SwagCustomSort\Bundle\SearchBundle + * * @copyright Copyright (c) shopware AG (http://www.shopware.de) */ class SortProductSearch implements ProductSearchInterface { /** - * @var ProductSearchInterface $productSearch + * @var ProductSearchInterface */ private $productSearch; /** - * @var Sorting $sortingComponent + * @var Sorting */ private $sortingComponent; /** * @param ProductSearchInterface $productSearch - * @param Sorting $sortingComponent + * @param Sorting $sortingComponent */ public function __construct(ProductSearchInterface $productSearch, Sorting $sortingComponent) { @@ -47,8 +46,9 @@ public function __construct(ProductSearchInterface $productSearch, Sorting $sort * Creates a search request on the internal search gateway to * get the product result for the passed criteria object. * - * @param Criteria $criteria + * @param Criteria $criteria * @param Struct\ProductContextInterface $context + * * @return ProductSearchResult */ public function search(Criteria $criteria, Struct\ProductContextInterface $context) diff --git a/Bundle/StoreFrontBundle/ListProductService.php b/Bundle/StoreFrontBundle/ListProductService.php index 900b917..1cc52bb 100644 --- a/Bundle/StoreFrontBundle/ListProductService.php +++ b/Bundle/StoreFrontBundle/ListProductService.php @@ -1,10 +1,9 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. - * */ namespace Shopware\SwagCustomSort\Bundle\StoreFrontBundle; @@ -21,13 +20,13 @@ class ListProductService implements ListProductServiceInterface private $coreService = null; /** - * @var Sorting $sortingComponent + * @var Sorting */ private $sortingComponent = null; /** * @param ListProductServiceInterface $coreService - * @param Sorting $sortingComponent + * @param Sorting $sortingComponent */ public function __construct(ListProductServiceInterface $coreService, Sorting $sortingComponent) { @@ -36,8 +35,9 @@ public function __construct(ListProductServiceInterface $coreService, Sorting $s } /** - * @param string $number + * @param string $number * @param Struct\ProductContextInterface $context + * * @return Struct\ListProduct */ public function get($number, Struct\ProductContextInterface $context) @@ -48,8 +48,9 @@ public function get($number, Struct\ProductContextInterface $context) } /** - * @param array $numbers + * @param array $numbers * @param Struct\ProductContextInterface $context + * * @return Struct\ListProduct[] */ public function getList(array $numbers, Struct\ProductContextInterface $context) diff --git a/Components/Listing.php b/Components/Listing.php index fbc05ab..67bd3af 100644 --- a/Components/Listing.php +++ b/Components/Listing.php @@ -1,10 +1,9 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. - * */ namespace Shopware\SwagCustomSort\Components; @@ -92,6 +91,7 @@ public function getCustomSortRepository() /** * @param $categoryId + * * @return bool */ public function showCustomSortName($categoryId) @@ -119,9 +119,6 @@ public function getFormattedSortName() return trim($formattedName); } - /** - * @return null - */ public function getSortName() { $name = $this->getConfig()->get('swagCustomSortName'); @@ -131,6 +128,7 @@ public function getSortName() /** * @param $categoryId + * * @return bool */ public function hasCustomSort($categoryId) @@ -150,6 +148,7 @@ public function hasCustomSort($categoryId) /** * @param $categoryId + * * @return bool */ public function isLinked($categoryId) @@ -178,6 +177,7 @@ public function isLinked($categoryId) * Checks whether this category has own custom sort * * @param $categoryId + * * @return bool */ public function hasOwnSort($categoryId) @@ -189,6 +189,7 @@ public function hasOwnSort($categoryId) * Checks whether this category has to use its custom sort by default, e.g. on category load use this custom sort * * @param $categoryId + * * @return bool */ public function showCustomSortAsDefault($categoryId) @@ -213,6 +214,7 @@ public function showCustomSortAsDefault($categoryId) * Returns the id of the linked category. * * @param $categoryId + * * @return int */ public function getLinkedCategoryId($categoryId) @@ -241,6 +243,7 @@ public function getLinkedCategoryId($categoryId) * Returns the base sort id for selected category * * @param $categoryId + * * @return bool */ public function getCategoryBaseSort($categoryId) diff --git a/Components/Sorting.php b/Components/Sorting.php index 589db4a..9f75dbd 100644 --- a/Components/Sorting.php +++ b/Components/Sorting.php @@ -1,10 +1,9 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. - * */ namespace Shopware\SwagCustomSort\Components; @@ -40,8 +39,9 @@ class Sorting * Return limited sorted products based on offset and limit * * @param array $allProducts - * @param int $offset - * @param int $limit + * @param int $offset + * @param int $limit + * * @return array */ public function sortProducts($allProducts, $offset, $limit) @@ -70,7 +70,7 @@ public function sortProducts($allProducts, $offset, $limit) $result[$i] = $product; - $i++; + ++$i; } ksort($result); @@ -88,6 +88,7 @@ public function sortProducts($allProducts, $offset, $limit) * Return product numbers after sorted and unsorted products are properly merged * * @param array $numbers + * * @return array */ public function sortByNumber($numbers) @@ -118,7 +119,7 @@ public function sortByNumber($numbers) } $result[$index] = $number; - $index++; + ++$index; } ksort($result); @@ -181,6 +182,7 @@ public function getSortedProductsNumbers() * @param int $offset * @param int $page * @param int $limit + * * @return int */ public function getOffset($offset, $page, $limit) @@ -192,11 +194,11 @@ public function getOffset($offset, $page, $limit) foreach ($this->sortedProducts as $sorted) { if (($sorted['position'] >= $min) && ($sorted['position'] < $max)) { - $offset--; + --$offset; } } - $page--; + --$page; } if ($offset < 0) { diff --git a/Controllers/Backend/CustomSort.php b/Controllers/Backend/CustomSort.php index ae5bfa3..9fafdf5 100644 --- a/Controllers/Backend/CustomSort.php +++ b/Controllers/Backend/CustomSort.php @@ -1,10 +1,9 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. - * */ use Shopware\Components\Model\ModelManager; @@ -17,7 +16,12 @@ class Shopware_Controllers_Backend_CustomSort extends Shopware_Controllers_Backend_ExtJs { /** - * @var ModelManager $em + * @var array + */ + protected $categoryIdCollection; + + /** + * @var ModelManager */ private $em = null; @@ -27,7 +31,7 @@ class Shopware_Controllers_Backend_CustomSort extends Shopware_Controllers_Backe private $sortRepo = null; /** - * @var \Enlight_Components_Db_Adapter_Pdo_Mysql $db + * @var \Enlight_Components_Db_Adapter_Pdo_Mysql */ private $db = null; @@ -38,7 +42,6 @@ class Shopware_Controllers_Backend_CustomSort extends Shopware_Controllers_Backe */ private $config = null; - /** * @var \Enlight_Event_EventManager */ @@ -56,31 +59,6 @@ public function getModelManager() return $this->em; } - /** - * @var array - */ - protected $categoryIdCollection; - - /** - * Convert a given virtual media path to its real URL used in the - * media repository for Shopware versions >= 5.1.0 (which introduced the - * MediaService). - * For older versions the path matches the filesystem structure. - * - * @param string $path - * - * @return string - */ - private function getMediaPath($path) - { - if (version_compare(Shopware()->Config()->get('Version'), '5.1', '<')) { - return $path; - } - /** @var Shopware\Bundle\MediaBundle\MediaService $mediaService */ - $mediaService = $this->get('shopware_media.media_service'); - return $mediaService->getUrl($path); - } - /** * Returns sort repository * @@ -170,6 +148,7 @@ public function getArticleListAction() $resultElement['path'] = $this->getMediaPath( 'media/image/thumbnail/' . $resultElement['path'] . '_140x140.' . $resultElement['extension'] ); + return $resultElement; }, $result); $this->View()->assign(['success' => true, 'data' => $result, 'total' => $total['Total']]); @@ -190,7 +169,7 @@ public function getCategorySettingsAction() 'id' => null, 'defaultSort' => 0, 'categoryLink' => 0, - 'baseSort' => $defaultSort + 'baseSort' => $defaultSort, ]; /** @var CategoryAttributes $categoryAttributes */ @@ -206,7 +185,7 @@ public function getCategorySettingsAction() 'id' => null, 'defaultSort' => $categoryAttributes->getSwagShowByDefault(), 'categoryLink' => $categoryAttributes->getSwagLink(), - 'baseSort' => $defaultSort + 'baseSort' => $defaultSort, ]; } @@ -281,7 +260,7 @@ public function saveArticleListAction() $sqlValues = $this->getSQLValues($sortedProducts, $categoryId); //update positions - $sql = "REPLACE INTO s_articles_sort (id, categoryId, articleId, position, pin) VALUES " + $sql = 'REPLACE INTO s_articles_sort (id, categoryId, articleId, position, pin) VALUES ' . rtrim($sqlValues, ','); $this->getDB()->query($sql); @@ -297,12 +276,116 @@ public function saveArticleListAction() $this->View()->assign(['success' => true]); } + /** + * Unpin product + */ + public function unpinArticleAction() + { + $product = $this->Request()->getParam('products'); + $sortId = (int) $product['positionId']; + + try { + if (!$sortId) { + throw new Exception("Unpin product '{$product['name']}' with id '{$product['id']}', failed!"); + } + + $categoryId = (int) $this->Request()->getParam('categoryId'); + + $this->getSortRepository()->unpinById($sortId); + + $this->getSortRepository()->deleteUnpinnedRecords($categoryId); + + $this->View()->assign(['success' => true]); + } catch (\Exception $ex) { + $this->View()->assign(['success' => false, 'message' => $ex->getMessage()]); + } + } + + /** + * Remove product from current and child categories. + */ + public function removeProductAction() + { + $articleId = (int) $this->Request()->get('articleId'); + $categoryId = (int) $this->Request()->get('categoryId'); + + /** @var Category $category */ + $category = Shopware()->Models()->getReference('Shopware\Models\Category\Category', $categoryId); + if ($category) { + $this->collectCategoryIds($category); + $categories = $this->getCategoryIdCollection(); + + /** @var Article $article */ + $article = Shopware()->Models()->getReference('Shopware\Models\Article\Article', (int) $articleId); + $article->removeCategory($category); + + if ($categories) { + foreach ($categories as $childCategoryId) { + /** @var Category $childCategoryModel */ + $childCategoryModel = Shopware()->Models() + ->getReference('Shopware\Models\Category\Category', $childCategoryId); + if ($childCategoryModel) { + $article->removeCategory($childCategoryModel); + } + } + } + + Shopware()->Models()->flush(); + } + + $this->View()->assign(['success' => true]); + } + + /** + * Get category ids collection. + * + * @return array + */ + public function getCategoryIdCollection() + { + return $this->categoryIdCollection; + } + + /** + * Insert category id to category ids collection. + * + * @param $categoryIdCollection + * + * @return array + */ + public function setCategoryIdCollection($categoryIdCollection) + { + $this->categoryIdCollection[] = $categoryIdCollection; + } + + /** + * Convert a given virtual media path to its real URL used in the + * media repository for Shopware versions >= 5.1.0 (which introduced the + * MediaService). + * For older versions the path matches the filesystem structure. + * + * @param string $path + * + * @return string + */ + private function getMediaPath($path) + { + if (version_compare(Shopware()->Config()->get('Version'), '5.1', '<')) { + return $path; + } + /** @var Shopware\Bundle\MediaBundle\MediaService $mediaService */ + $mediaService = $this->get('shopware_media.media_service'); + + return $mediaService->getUrl($path); + } + /** * Apply new positions of the products * * @param array $allProducts - all products contained in the current category - * @param array $products - the selected products, that were dragged - * @param int $index - the id of offset products + * @param array $products - the selected products, that were dragged + * @param int $index - the id of offset products + * * @return array $result */ private function applyNewPosition($allProducts, $products, $index) @@ -334,7 +417,7 @@ private function applyNewPosition($allProducts, $products, $index) $result[$index]['position'] = $index; $result[$index]['oldPosition'] = $index; - $index++; + ++$index; } return $result; @@ -344,7 +427,8 @@ private function applyNewPosition($allProducts, $products, $index) * Returns sql values for update query * * @param array $productsForUpdate - * @param int $categoryId + * @param int $categoryId + * * @return string - values for update */ private function getSQLValues($productsForUpdate, $categoryId) @@ -377,8 +461,9 @@ private function prepareKeys($products) * Helper function, for getting a part of the array, which contains all products. * Returns the offset from which the new array should start. * - * @param array $products - selected products - * @param int $categoryId + * @param array $products - selected products + * @param int $categoryId + * * @return int - the smallest position */ private function getOffset($products, $categoryId) @@ -414,8 +499,9 @@ private function getOffset($products, $categoryId) * Returns the length of the new array. * * @param array $products - * @param int $offset - * @param int $categoryId + * @param int $offset + * @param int $categoryId + * * @return int - the length of the new array */ private function getLength($products, $offset, $categoryId) @@ -442,31 +528,6 @@ private function getLength($products, $offset, $categoryId) return $length; } - /** - * Unpin product - */ - public function unpinArticleAction() - { - $product = $this->Request()->getParam('products'); - $sortId = (int) $product['positionId']; - - try { - if (!$sortId) { - throw new Exception("Unpin product '{$product['name']}' with id '{$product['id']}', failed!"); - } - - $categoryId = (int) $this->Request()->getParam('categoryId'); - - $this->getSortRepository()->unpinById($sortId); - - $this->getSortRepository()->deleteUnpinnedRecords($categoryId); - - $this->View()->assign(['success' => true]); - } catch (\Exception $ex) { - $this->View()->assign(['success' => false, 'message' => $ex->getMessage()]); - } - } - private function fixDeletedPosition($deletedPosition, $allProducts) { $index = $deletedPosition; @@ -497,41 +558,6 @@ private function invalidateProductCache($movedProducts) } } - /** - * Remove product from current and child categories. - */ - public function removeProductAction() - { - $articleId = (int) $this->Request()->get('articleId'); - $categoryId = (int) $this->Request()->get('categoryId'); - - /** @var Category $category */ - $category = Shopware()->Models()->getReference('Shopware\Models\Category\Category', $categoryId); - if ($category) { - $this->collectCategoryIds($category); - $categories = $this->getCategoryIdCollection(); - - /** @var Article $article */ - $article = Shopware()->Models()->getReference('Shopware\Models\Article\Article', (int) $articleId); - $article->removeCategory($category); - - if ($categories) { - foreach ($categories as $childCategoryId) { - /** @var Category $childCategoryModel */ - $childCategoryModel = Shopware()->Models() - ->getReference('Shopware\Models\Category\Category', $childCategoryId); - if ($childCategoryModel) { - $article->removeCategory($childCategoryModel); - } - } - } - - Shopware()->Models()->flush(); - } - - $this->View()->assign(['success' => true]); - } - /** * Check current category for child categories and * add ids to collection. @@ -543,7 +569,7 @@ private function collectCategoryIds($categoryModel) $categoryId = $categoryModel->getId(); $this->setCategoryIdCollection($categoryId); - $sql = "SELECT id FROM s_categories WHERE path LIKE ?"; + $sql = 'SELECT id FROM s_categories WHERE path LIKE ?'; $categories = Shopware()->Db()->fetchAll($sql, ['%|' . $categoryId . '|%']); if (!$categories) { @@ -553,28 +579,5 @@ private function collectCategoryIds($categoryModel) foreach ($categories as $categoryId) { $this->setCategoryIdCollection($categoryId); } - - return; - } - - /** - * Get category ids collection. - * - * @return array - */ - public function getCategoryIdCollection() - { - return $this->categoryIdCollection; - } - - /** - * Insert category id to category ids collection. - * - * @param $categoryIdCollection - * @return array - */ - public function setCategoryIdCollection($categoryIdCollection) - { - $this->categoryIdCollection[] = $categoryIdCollection; } } diff --git a/Models/CustomSort/ArticleSort.php b/Models/CustomSort/ArticleSort.php index 9ad1428..ec2d365 100644 --- a/Models/CustomSort/ArticleSort.php +++ b/Models/CustomSort/ArticleSort.php @@ -1,16 +1,14 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. - * */ namespace Shopware\CustomModels\CustomSort; use Doctrine\ORM\Mapping as ORM; -use Symfony\Component\Validator\Constraints as Assert; use Shopware\Components\Model\ModelEntity; /** @@ -21,7 +19,7 @@ class ArticleSort extends ModelEntity { /** - * @var integer $id + * @var int * * @ORM\Id * @ORM\Column(type="integer") @@ -30,28 +28,28 @@ class ArticleSort extends ModelEntity private $id; /** - * @var integer $categoryId + * @var int * * @ORM\Column(name="categoryId", type="integer") */ private $categoryId; /** - * @var integer $articleId + * @var int * * @ORM\Column(name="articleId", type="integer") */ private $articleId; /** - * @var integer $position + * @var int * * @ORM\Column(name="position", type="integer") */ private $position; /** - * @var boolean $position + * @var bool * * @ORM\Column(name="pin", type="boolean", nullable=false) */ @@ -66,7 +64,7 @@ public function getId() } /** - * @return integer + * @return int */ public function getArticleId() { @@ -74,7 +72,7 @@ public function getArticleId() } /** - * @param integer $articleId + * @param int $articleId */ public function setArticleId($articleId) { @@ -82,7 +80,7 @@ public function setArticleId($articleId) } /** - * @return integer + * @return int */ public function getCategoryId() { @@ -90,7 +88,7 @@ public function getCategoryId() } /** - * @param integer $categoryId + * @param int $categoryId */ public function setCategoryId($categoryId) { @@ -98,7 +96,7 @@ public function setCategoryId($categoryId) } /** - * @return integer + * @return int */ public function getPosition() { @@ -106,7 +104,7 @@ public function getPosition() } /** - * @param integer $position + * @param int $position */ public function setPosition($position) { diff --git a/Models/CustomSort/CustomSortRepository.php b/Models/CustomSort/CustomSortRepository.php index acc2a8c..372139a 100644 --- a/Models/CustomSort/CustomSortRepository.php +++ b/Models/CustomSort/CustomSortRepository.php @@ -1,10 +1,9 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. - * */ namespace Shopware\CustomModels\CustomSort; @@ -19,6 +18,7 @@ class CustomSortRepository extends ModelRepository * Check if selected category has custom sorted products * * @param $categoryId + * * @return bool */ public function hasCustomSort($categoryId) @@ -40,6 +40,7 @@ public function hasCustomSort($categoryId) * Return last sort position for selected category * * @param $categoryId + * * @return mixed */ public function getMaxPosition($categoryId) @@ -60,11 +61,12 @@ public function getMaxPosition($categoryId) /** * Return product list and exclude product containing passed ids for selected category * - * @param int $categoryId - * @param array $sortedProductsIds - * @param int $orderBy + * @param int $categoryId + * @param array $sortedProductsIds + * @param int $orderBy * @param int|null $offset * @param int|null $limit + * * @return mixed */ public function getArticleImageQuery($categoryId, $sortedProductsIds, $orderBy, $offset = null, $limit = null) @@ -87,7 +89,7 @@ public function getArticleImageQuery($categoryId, $sortedProductsIds, $orderBy, ->setParameter('categoryId', $categoryId); if ($sortedProductsIds) { - $builder->andWhere($builder->expr()->notIn("product.id", $sortedProductsIds)); + $builder->andWhere($builder->expr()->notIn('product.id', $sortedProductsIds)); } if ($offset !== null && $limit !== null) { @@ -103,8 +105,9 @@ public function getArticleImageQuery($categoryId, $sortedProductsIds, $orderBy, /** * Get products from current category which are manually sorted * - * @param int $categoryId + * @param int $categoryId * @param bool|false $linkedCategoryId + * * @return array */ public function getSortedProducts($categoryId, $linkedCategoryId = false) @@ -150,6 +153,7 @@ public function getSortedProducts($categoryId, $linkedCategoryId = false) * Return total count of products in selected category * * @param $categoryId + * * @return mixed */ public function getArticleImageCountQuery($categoryId) @@ -166,68 +170,6 @@ public function getArticleImageCountQuery($categoryId) return $builder; } - /** - * Sort products for current category by passed sort type - * - * @param QueryBuilder $builder - * @param integer $orderBy - */ - private function sortUnsortedByDefault($builder, $orderBy) - { - switch ($orderBy) { - case 1: - $builder->addOrderBy('product.datum', 'DESC') - ->addOrderBy('product.changetime', 'DESC'); - break; - case 2: - $builder->leftJoin('product', 's_articles_top_seller_ro', 'topSeller', 'topSeller.article_id = product.id') - ->addOrderBy('topSeller.sales', 'DESC') - ->addOrderBy('topSeller.article_id', 'DESC'); - break; - case 3: - $builder->addSelect('MIN(ROUND(defaultPrice.price * priceVariant.minpurchase * 1, 2)) as cheapest_price') - ->leftJoin('product', 's_articles_prices', 'defaultPrice', 'defaultPrice.articleID = product.id') - ->innerJoin('defaultPrice', 's_articles_details', 'priceVariant', 'priceVariant.id = defaultPrice.articledetailsID') - ->addOrderBy('cheapest_price', 'ASC') - ->addOrderBy('product.id', 'DESC'); - break; - case 4: - $builder->addSelect('MIN(ROUND(defaultPrice.price * priceVariant.minpurchase * 1, 2)) as cheapest_price') - ->leftJoin('product', 's_articles_prices', 'defaultPrice', 'defaultPrice.articleID = product.id') - ->innerJoin('defaultPrice', 's_articles_details', 'priceVariant', 'priceVariant.id = defaultPrice.articledetailsID') - ->addOrderBy('cheapest_price', 'DESC') - ->addOrderBy('product.id', 'DESC'); - break; - case 5: - $builder->addOrderBy('product.name', 'ASC'); - break; - case 6: - $builder->addOrderBy('product.name', 'DESC'); - break; - case 7: - $builder - ->addSelect('(SUM(vote.points) / COUNT(vote.id)) as votes') - ->leftJoin('product', 's_articles_vote', 'vote', 'product.id = vote.articleID') - ->addOrderBy('votes', 'DESC') - ->addOrderBy('product.id', 'DESC') - ->groupBy('product.id'); - break; - case 9: - $builder - ->innerJoin('product', 's_articles_details', 'variant', 'variant.id = product.main_detail_id') - ->addOrderBy('variant.instock', 'ASC') - ->addOrderBy('product.id', 'DESC'); - break; - case 10: - $builder - ->innerJoin('product', 's_articles_details', 'variant', 'variant.id = product.main_detail_id') - ->addOrderBy('variant.instock', 'DESC') - ->addOrderBy('product.id', 'DESC'); - break; - - } - } - /** * Sets pin value to 0 * @@ -273,6 +215,7 @@ public function deleteUnpinnedRecords($categoryId) * Returns the position of the pinned record with max position * * @param $categoryId + * * @return mixed */ public function getMaxPinPosition($categoryId) @@ -295,6 +238,7 @@ public function getMaxPinPosition($categoryId) * Returns product position for selected product * * @param $articleId + * * @return mixed */ public function getPositionByArticleId($articleId) @@ -315,6 +259,7 @@ public function getPositionByArticleId($articleId) * Returns last deleted position of product for selected category * * @param $categoryId + * * @return mixed */ public function getPositionOfDeletedProduct($categoryId) @@ -379,6 +324,67 @@ public function updateCategoryAttributes($categoryId, $baseSort, $categoryLink = $builder->execute(); } + /** + * Sort products for current category by passed sort type + * + * @param QueryBuilder $builder + * @param int $orderBy + */ + private function sortUnsortedByDefault($builder, $orderBy) + { + switch ($orderBy) { + case 1: + $builder->addOrderBy('product.datum', 'DESC') + ->addOrderBy('product.changetime', 'DESC'); + break; + case 2: + $builder->leftJoin('product', 's_articles_top_seller_ro', 'topSeller', 'topSeller.article_id = product.id') + ->addOrderBy('topSeller.sales', 'DESC') + ->addOrderBy('topSeller.article_id', 'DESC'); + break; + case 3: + $builder->addSelect('MIN(ROUND(defaultPrice.price * priceVariant.minpurchase * 1, 2)) as cheapest_price') + ->leftJoin('product', 's_articles_prices', 'defaultPrice', 'defaultPrice.articleID = product.id') + ->innerJoin('defaultPrice', 's_articles_details', 'priceVariant', 'priceVariant.id = defaultPrice.articledetailsID') + ->addOrderBy('cheapest_price', 'ASC') + ->addOrderBy('product.id', 'DESC'); + break; + case 4: + $builder->addSelect('MIN(ROUND(defaultPrice.price * priceVariant.minpurchase * 1, 2)) as cheapest_price') + ->leftJoin('product', 's_articles_prices', 'defaultPrice', 'defaultPrice.articleID = product.id') + ->innerJoin('defaultPrice', 's_articles_details', 'priceVariant', 'priceVariant.id = defaultPrice.articledetailsID') + ->addOrderBy('cheapest_price', 'DESC') + ->addOrderBy('product.id', 'DESC'); + break; + case 5: + $builder->addOrderBy('product.name', 'ASC'); + break; + case 6: + $builder->addOrderBy('product.name', 'DESC'); + break; + case 7: + $builder + ->addSelect('(SUM(vote.points) / COUNT(vote.id)) as votes') + ->leftJoin('product', 's_articles_vote', 'vote', 'product.id = vote.articleID') + ->addOrderBy('votes', 'DESC') + ->addOrderBy('product.id', 'DESC') + ->groupBy('product.id'); + break; + case 9: + $builder + ->innerJoin('product', 's_articles_details', 'variant', 'variant.id = product.main_detail_id') + ->addOrderBy('variant.instock', 'ASC') + ->addOrderBy('product.id', 'DESC'); + break; + case 10: + $builder + ->innerJoin('product', 's_articles_details', 'variant', 'variant.id = product.main_detail_id') + ->addOrderBy('variant.instock', 'DESC') + ->addOrderBy('product.id', 'DESC'); + break; + } + } + /** * @return QueryBuilder */ diff --git a/README.md b/README.md index bdbc097..83266dc 100644 --- a/README.md +++ b/README.md @@ -3,13 +3,13 @@ > Higher versions may work either but were not tested. ## Description -Do you want to comletely customize the sort order of the article listing? +Do you want to comletely customize the sort order of the product listing? -Special promotion articles or new articles should always be displayed on top? +Special promotion products or new products should always be displayed on top? Now you can define custom sortings with the "CustomSort" plugin. -You can move the articles via drag 'n' drop to their new position. +You can move the products via drag 'n' drop to their new position. Instead of defining own sortings you have the ability to provide basic sorting methods and modify them. This lets you create listings fast, effective and with just a few steps. @@ -21,12 +21,12 @@ The new sortings will be displayed in the frontend with their chosen name. The n **Features:** -* custom sorting for all categories (independend from the category layer) +* custom sorting for all categories (independent from the category layer) * sorting via Drag&Drop * base sortings can be inherited * setup a custom sorting as default sorting * synchronize between categories (e.g language-shops) -* the amount of products is customizable for a better overview (from 10 to all articles) +* the amount of products is customizable for a better overview (from 10 to all products) * displaying as own sorting entry in the frontend **Requirements:** @@ -39,4 +39,4 @@ The new sortings will be displayed in the frontend with their chosen name. The n ## License -The MIT License (MIT). Please see [License File](LICENSE) for more information. \ No newline at end of file +The MIT License (MIT). Please see [License File](LICENSE) for more information. diff --git a/Sorter/Sort/DragDropSorting.php b/Sorter/Sort/DragDropSorting.php index fa43f02..20d97ce 100644 --- a/Sorter/Sort/DragDropSorting.php +++ b/Sorter/Sort/DragDropSorting.php @@ -1,10 +1,9 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. - * */ namespace Shopware\SwagCustomSort\Sorter\Sort; diff --git a/Sorter/Sort/RatingSorting.php b/Sorter/Sort/RatingSorting.php index 669830e..72fbd7b 100644 --- a/Sorter/Sort/RatingSorting.php +++ b/Sorter/Sort/RatingSorting.php @@ -1,11 +1,11 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. - * */ + namespace Shopware\SwagCustomSort\Sorter\Sort; use Shopware\Bundle\SearchBundle\Sorting\Sorting; diff --git a/Sorter/Sort/StockSorting.php b/Sorter/Sort/StockSorting.php index 207c64d..4f5c6e5 100644 --- a/Sorter/Sort/StockSorting.php +++ b/Sorter/Sort/StockSorting.php @@ -1,10 +1,9 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. - * */ namespace Shopware\SwagCustomSort\Sorter\Sort; diff --git a/Sorter/SortDBAL/Handler/DragDropHandler.php b/Sorter/SortDBAL/Handler/DragDropHandler.php index f4bcde3..dfd6473 100644 --- a/Sorter/SortDBAL/Handler/DragDropHandler.php +++ b/Sorter/SortDBAL/Handler/DragDropHandler.php @@ -1,23 +1,22 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. - * */ namespace Shopware\SwagCustomSort\Sorter\SortDBAL\Handler; -use \Shopware\Bundle\SearchBundleDBAL\SortingHandlerInterface; -use \Shopware\Bundle\SearchBundle\SortingInterface; -use \Shopware\Bundle\SearchBundleDBAL\QueryBuilder; -use \Shopware\Bundle\StoreFrontBundle\Struct\ShopContextInterface; -use \Shopware\Bundle\SearchBundle\StoreFrontCriteriaFactory; -use \Shopware\Bundle\SearchBundleDBAL\SortingHandler\ReleaseDateSortingHandler; -use \Shopware\Bundle\SearchBundleDBAL\SortingHandler\PopularitySortingHandler; -use \Shopware\Bundle\SearchBundleDBAL\SortingHandler\PriceSortingHandler; -use \Shopware\Bundle\SearchBundleDBAL\SortingHandler\ProductNameSortingHandler; +use Shopware\Bundle\SearchBundle\SortingInterface; +use Shopware\Bundle\SearchBundle\StoreFrontCriteriaFactory; +use Shopware\Bundle\SearchBundleDBAL\QueryBuilder; +use Shopware\Bundle\SearchBundleDBAL\SortingHandler\PopularitySortingHandler; +use Shopware\Bundle\SearchBundleDBAL\SortingHandler\PriceSortingHandler; +use Shopware\Bundle\SearchBundleDBAL\SortingHandler\ProductNameSortingHandler; +use Shopware\Bundle\SearchBundleDBAL\SortingHandler\ReleaseDateSortingHandler; +use Shopware\Bundle\SearchBundleDBAL\SortingHandlerInterface; +use Shopware\Bundle\StoreFrontBundle\Struct\ShopContextInterface; use Shopware\SwagCustomSort\Components\Listing; use Shopware\SwagCustomSort\Components\Sorting; use Shopware\SwagCustomSort\Sorter\Sort\DragDropSorting; @@ -28,7 +27,7 @@ class DragDropHandler implements SortingHandlerInterface const SORTING_STOCK_DESC = 10; /** - * @var Sorting $sortingComponent + * @var Sorting */ private $sortingComponent; @@ -42,17 +41,19 @@ public function __construct(Sorting $sortingComponent) /** * @param SortingInterface $sorting + * * @return bool */ public function supportsSorting(SortingInterface $sorting) { - return ($sorting instanceof DragDropSorting); + return $sorting instanceof DragDropSorting; } /** - * @param SortingInterface $sorting - * @param QueryBuilder $query + * @param SortingInterface $sorting + * @param QueryBuilder $query * @param ShopContextInterface $context + * * @throws \Exception */ public function generateSorting(SortingInterface $sorting, QueryBuilder $query, ShopContextInterface $context) @@ -90,7 +91,7 @@ public function generateSorting(SortingInterface $sorting, QueryBuilder $query, //exclude passed products ids from result $sortedProductsIds = $this->sortingComponent->getSortedProductsIds(); if ($sortedProductsIds) { - $query->andWhere($query->expr()->notIn("product.id", $sortedProductsIds)); + $query->andWhere($query->expr()->notIn('product.id', $sortedProductsIds)); } //for records with no 'plugin' order data use the default shopware order @@ -103,6 +104,7 @@ public function generateSorting(SortingInterface $sorting, QueryBuilder $query, /** * @param $defaultSort + * * @return array */ protected function getDefaultData($defaultSort) @@ -111,47 +113,47 @@ protected function getDefaultData($defaultSort) case StoreFrontCriteriaFactory::SORTING_RELEASE_DATE: return [ 'handler' => new ReleaseDateSortingHandler(), - 'direction' => 'DESC' + 'direction' => 'DESC', ]; case StoreFrontCriteriaFactory::SORTING_POPULARITY: return [ 'handler' => new PopularitySortingHandler(), - 'direction' => 'DESC' + 'direction' => 'DESC', ]; case StoreFrontCriteriaFactory::SORTING_CHEAPEST_PRICE: return [ 'handler' => new PriceSortingHandler(Shopware()->Container()->get('shopware_searchdbal.search_price_helper_dbal')), - 'direction' => 'ASC' + 'direction' => 'ASC', ]; case StoreFrontCriteriaFactory::SORTING_HIGHEST_PRICE: return [ 'handler' => new PriceSortingHandler(Shopware()->Container()->get('shopware_searchdbal.search_price_helper_dbal')), - 'direction' => 'DESC' + 'direction' => 'DESC', ]; case StoreFrontCriteriaFactory::SORTING_PRODUCT_NAME_ASC: return [ 'handler' => new ProductNameSortingHandler(), - 'direction' => 'ASC' + 'direction' => 'ASC', ]; case StoreFrontCriteriaFactory::SORTING_PRODUCT_NAME_DESC: return [ 'handler' => new ProductNameSortingHandler(), - 'direction' => 'DESC' + 'direction' => 'DESC', ]; case StoreFrontCriteriaFactory::SORTING_SEARCH_RANKING: return [ 'handler' => new RatingSortingHandler(), - 'direction' => 'DESC' + 'direction' => 'DESC', ]; - case DragDropHandler::SORTING_STOCK_ASC: + case self::SORTING_STOCK_ASC: return [ 'handler' => new StockSortingHandler(), - 'direction' => 'ASC' + 'direction' => 'ASC', ]; - case DragDropHandler::SORTING_STOCK_DESC: + case self::SORTING_STOCK_DESC: return [ 'handler' => new StockSortingHandler(), - 'direction' => 'DESC' + 'direction' => 'DESC', ]; } } diff --git a/Sorter/SortDBAL/Handler/RatingSortingHandler.php b/Sorter/SortDBAL/Handler/RatingSortingHandler.php index 3488b37..8e1415b 100644 --- a/Sorter/SortDBAL/Handler/RatingSortingHandler.php +++ b/Sorter/SortDBAL/Handler/RatingSortingHandler.php @@ -1,23 +1,22 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. - * */ namespace Shopware\SwagCustomSort\Sorter\SortDBAL\Handler; -use Shopware\Bundle\SearchBundleDBAL\SortingHandlerInterface; use Shopware\Bundle\SearchBundle\SortingInterface; -use Shopware\Bundle\StoreFrontBundle\Struct\ShopContextInterface; use Shopware\Bundle\SearchBundleDBAL\QueryBuilder; +use Shopware\Bundle\SearchBundleDBAL\SortingHandlerInterface; +use Shopware\Bundle\StoreFrontBundle\Struct\ShopContextInterface; use Shopware\SwagCustomSort\Sorter\Sort\RatingSorting; /** * @category Shopware - * @package Shopware\Bundle\SearchBundleDBAL\SortingHandler + * * @copyright Copyright (c) shopware AG (http://www.shopware.de) */ class RatingSortingHandler implements SortingHandlerInterface @@ -27,7 +26,7 @@ class RatingSortingHandler implements SortingHandlerInterface */ public function supportsSorting(SortingInterface $sorting) { - return ($sorting instanceof RatingSorting); + return $sorting instanceof RatingSorting; } /** diff --git a/Sorter/SortDBAL/Handler/StockSortingHandler.php b/Sorter/SortDBAL/Handler/StockSortingHandler.php index a187915..aeefc0e 100644 --- a/Sorter/SortDBAL/Handler/StockSortingHandler.php +++ b/Sorter/SortDBAL/Handler/StockSortingHandler.php @@ -1,23 +1,22 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. - * */ namespace Shopware\SwagCustomSort\Sorter\SortDBAL\Handler; -use Shopware\Bundle\SearchBundleDBAL\SortingHandlerInterface; use Shopware\Bundle\SearchBundle\SortingInterface; -use Shopware\Bundle\StoreFrontBundle\Struct\ShopContextInterface; use Shopware\Bundle\SearchBundleDBAL\QueryBuilder; +use Shopware\Bundle\SearchBundleDBAL\SortingHandlerInterface; +use Shopware\Bundle\StoreFrontBundle\Struct\ShopContextInterface; use Shopware\SwagCustomSort\Sorter\Sort\StockSorting; /** * @category Shopware - * @package Shopware\Bundle\SearchBundleDBAL\SortingHandler + * * @copyright Copyright (c) shopware AG (http://www.shopware.de) */ class StockSortingHandler implements SortingHandlerInterface @@ -27,7 +26,7 @@ class StockSortingHandler implements SortingHandlerInterface */ public function supportsSorting(SortingInterface $sorting) { - return ($sorting instanceof StockSorting); + return $sorting instanceof StockSorting; } /** diff --git a/Sorter/SortFactory.php b/Sorter/SortFactory.php index c408529..db9f9aa 100644 --- a/Sorter/SortFactory.php +++ b/Sorter/SortFactory.php @@ -1,18 +1,17 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. - * */ namespace Shopware\SwagCustomSort\Sorter; use Enlight_Controller_Request_Request as Request; use Shopware\Bundle\SearchBundle\Criteria; -use Shopware\SwagCustomSort\Sorter\Sort\DragDropSorting; use Shopware\Bundle\SearchBundle\SortingInterface; +use Shopware\SwagCustomSort\Sorter\Sort\DragDropSorting; class SortFactory { diff --git a/Subscriber/Backend.php b/Subscriber/Backend.php index 2f38875..54881ec 100644 --- a/Subscriber/Backend.php +++ b/Subscriber/Backend.php @@ -1,17 +1,16 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. - * */ namespace Shopware\SwagCustomSort\Subscriber; use Enlight\Event\SubscriberInterface; -use Enlight_Event_EventArgs as EventArgs; use Enlight_Controller_ActionEventArgs as ActionEventArgs; +use Enlight_Event_EventArgs as EventArgs; use Shopware\Components\Model\ModelManager; use Shopware\Models\Article\Article; use Shopware\Models\Category\Category; @@ -20,23 +19,23 @@ class Backend implements SubscriberInterface { /** - * @var SwagCustomSort_Bootstrap $bootstrap + * @var SwagCustomSort_Bootstrap */ protected $bootstrap; /** - * @var ModelManager $em + * @var ModelManager */ protected $em; /** - * @var \Shopware\CustomModels\CustomSort\CustomSortRepository $customSortRepo + * @var \Shopware\CustomModels\CustomSort\CustomSortRepository */ protected $customSortRepo = null; /** * @param SwagCustomSort_Bootstrap $bootstrap - * @param ModelManager $em + * @param ModelManager $em */ public function __construct(SwagCustomSort_Bootstrap $bootstrap, ModelManager $em) { @@ -44,20 +43,12 @@ public function __construct(SwagCustomSort_Bootstrap $bootstrap, ModelManager $e $this->em = $em; } - private function getSortRepository() - { - if ($this->customSortRepo === null) { - $this->customSortRepo = $this->em->getRepository('Shopware\CustomModels\CustomSort\ArticleSort'); - } - return $this->customSortRepo; - } - public static function getSubscribedEvents() { return [ 'Enlight_Controller_Action_PostDispatchSecure_Backend_Index' => 'onPostDispatchSecureBackendIndex', 'Shopware\Models\Article\Article::preRemove' => 'preRemoveArticle', - 'Shopware\Models\Category\Category::preRemove' => 'preRemoveCategory' + 'Shopware\Models\Category\Category::preRemove' => 'preRemoveCategory', ]; } @@ -89,7 +80,7 @@ public function preRemoveArticle(EventArgs $arguments) $catAttributes = $category->getAttribute(); $deletedPosition = $catAttributes->getSwagDeletedPosition(); if ($deletedPosition === null || $deletedPosition > $position) { - $catAttributes->setSwagDeletedPosition((int)$position); + $catAttributes->setSwagDeletedPosition((int) $position); } } } @@ -110,11 +101,20 @@ public function preRemoveCategory(EventArgs $arguments) $categoryModel = $arguments->get('entity'); $categoryId = $categoryModel->getId(); - $builder = $this->em->getDBALQueryBuilder(); + $builder = $this->em->getDBALQueryBuilder(); $builder->delete('s_articles_sort') ->where('categoryId = :categoryId') ->setParameter('categoryId', $categoryId); $builder->execute(); } + + private function getSortRepository() + { + if ($this->customSortRepo === null) { + $this->customSortRepo = $this->em->getRepository('Shopware\CustomModels\CustomSort\ArticleSort'); + } + + return $this->customSortRepo; + } } diff --git a/Subscriber/ControllerPath.php b/Subscriber/ControllerPath.php index 82426a2..79f1944 100644 --- a/Subscriber/ControllerPath.php +++ b/Subscriber/ControllerPath.php @@ -1,11 +1,11 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. - * */ + namespace Shopware\SwagCustomSort\Subscriber; use Enlight\Event\SubscriberInterface; @@ -13,22 +13,21 @@ /** * Class ControllerPath - * @package Shopware\SwagCustomSort\Subscriber */ class ControllerPath implements SubscriberInterface { /** - * @var string $bootstrapPath + * @var string */ private $bootstrapPath; /** - * @var TemplateManager $templateManager + * @var TemplateManager */ private $templateManager; /** - * @param string $bootstrapPath + * @param string $bootstrapPath * @param TemplateManager $templateManager */ public function __construct($bootstrapPath, TemplateManager $templateManager) @@ -41,16 +40,17 @@ public static function getSubscribedEvents() { return [ 'Enlight_Controller_Dispatcher_ControllerPath_Backend_CustomSort' => 'onGetCustomSortControllerPath', - 'Enlight_Controller_Dispatcher_ControllerPath_Widgets_CustomSort' => 'onGetCustomSortControllerPath' + 'Enlight_Controller_Dispatcher_ControllerPath_Widgets_CustomSort' => 'onGetCustomSortControllerPath', ]; } /** - * This function is responsible to resolve the backend / frontend controller path. - * - * @param \Enlight_Event_EventArgs $args - * @return string - */ + * This function is responsible to resolve the backend / frontend controller path. + * + * @param \Enlight_Event_EventArgs $args + * + * @return string + */ public function onGetCustomSortControllerPath(\Enlight_Event_EventArgs $args) { $this->templateManager->addTemplateDir($this->bootstrapPath . 'Views/'); diff --git a/Subscriber/Frontend.php b/Subscriber/Frontend.php index 7035453..67d73c4 100644 --- a/Subscriber/Frontend.php +++ b/Subscriber/Frontend.php @@ -1,11 +1,11 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. - * */ + namespace Shopware\SwagCustomSort\Subscriber; use Enlight\Event\SubscriberInterface; @@ -15,12 +15,12 @@ class Frontend implements SubscriberInterface { /** - * @var PluginBootstrap $bootstrap + * @var PluginBootstrap */ private $bootstrap; /** - * @var string $bootstrapPath + * @var string */ private $bootstrapPath; @@ -73,7 +73,7 @@ public function onPostDispatchSecureListing($args) /** * @param \Enlight_View_Default $view - * @param string $templatePath + * @param string $templatePath */ protected function extendsTemplate($view, $templatePath) { diff --git a/Subscriber/Resource.php b/Subscriber/Resource.php index f491ba1..ac2d236 100644 --- a/Subscriber/Resource.php +++ b/Subscriber/Resource.php @@ -1,10 +1,9 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. - * */ namespace Shopware\SwagCustomSort\Subscriber; @@ -12,13 +11,13 @@ use Enlight\Event\SubscriberInterface; use Shopware\Components\Model\ModelManager; use Shopware\SwagCustomSort\Components\Listing; -use Shopware_Components_Config as ShopwareConfig; use Shopware\SwagCustomSort\Components\Sorting; +use Shopware_Components_Config as ShopwareConfig; class Resource implements SubscriberInterface { /** - * @var ModelManager $modelManager + * @var ModelManager */ private $modelManager; @@ -28,7 +27,7 @@ class Resource implements SubscriberInterface private $config; /** - * @param ModelManager $modelManager + * @param ModelManager $modelManager * @param ShopwareConfig $config */ public function __construct(ModelManager $modelManager, ShopwareConfig $config) @@ -46,7 +45,7 @@ public static function getSubscribedEvents() { return [ 'Enlight_Bootstrap_InitResource_swagcustomsort.listing_component' => 'onInitListingComponent', - 'Enlight_Bootstrap_InitResource_swagcustomsort.sorting_component' => 'onInitSortingComponent' + 'Enlight_Bootstrap_InitResource_swagcustomsort.sorting_component' => 'onInitSortingComponent', ]; } diff --git a/Subscriber/Sort.php b/Subscriber/Sort.php index a4de6f0..1943ee7 100644 --- a/Subscriber/Sort.php +++ b/Subscriber/Sort.php @@ -1,10 +1,9 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. - * */ namespace Shopware\SwagCustomSort\Subscriber; @@ -16,30 +15,30 @@ use Shopware\Components\Model\ModelManager; use Shopware\SwagCustomSort\Components\Listing; use Shopware\SwagCustomSort\Components\Sorting; -use Shopware\SwagCustomSort\Sorter\SortFactory; use Shopware\SwagCustomSort\Sorter\SortDBAL\Handler\DragDropHandler; +use Shopware\SwagCustomSort\Sorter\SortFactory; class Sort implements SubscriberInterface { /** - * @var ModelManager $em + * @var ModelManager */ protected $em; /** - * @var Sorting $sortingComponent + * @var Sorting */ private $sortingComponent; /** - * @var Listing $listingComponent + * @var Listing */ private $listingComponent; /** * @param ModelManager $em - * @param Sorting $sortingComponent - * @param Listing $listingComponent + * @param Sorting $sortingComponent + * @param Listing $listingComponent */ public function __construct(ModelManager $em, Sorting $sortingComponent, Listing $listingComponent) { @@ -59,7 +58,7 @@ public static function getSubscribedEvents() 'Shopware_SearchBundle_Create_Listing_Criteria' => 'onCreateListingCriteria', 'Shopware_SearchBundle_Create_Ajax_Listing_Criteria' => 'onCreateListingCriteria', 'Shopware_SearchBundle_Create_Product_Navigation_Criteria' => 'onCreateListingCriteria', - 'Shopware_SearchBundleDBAL_Collect_Sorting_Handlers' => 'onCollectSortingHandlers' + 'Shopware_SearchBundleDBAL_Collect_Sorting_Handlers' => 'onCollectSortingHandlers', ]; } diff --git a/Subscriber/StoreFrontBundle.php b/Subscriber/StoreFrontBundle.php index ed6f5c5..8502166 100644 --- a/Subscriber/StoreFrontBundle.php +++ b/Subscriber/StoreFrontBundle.php @@ -1,35 +1,34 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. - * */ namespace Shopware\SwagCustomSort\Subscriber; use Enlight\Event\SubscriberInterface; -use Symfony\Component\DependencyInjection\Container; -use Shopware\SwagCustomSort\Bundle\StoreFrontBundle\ListProductService; use Shopware\SwagCustomSort\Bundle\SearchBundle\SortProductSearch; +use Shopware\SwagCustomSort\Bundle\StoreFrontBundle\ListProductService; use Shopware\SwagCustomSort\Components\Sorting; +use Symfony\Component\DependencyInjection\Container; class StoreFrontBundle implements SubscriberInterface { /** - * @var Container $container + * @var Container */ private $container; /** - * @var Sorting $sortingComponent + * @var Sorting */ private $sortingComponent; /** * @param Container $container - * @param Sorting $sortingComponent + * @param Sorting $sortingComponent */ public function __construct(Container $container, Sorting $sortingComponent) { @@ -46,7 +45,7 @@ public static function getSubscribedEvents() { return [ 'Enlight_Bootstrap_AfterInitResource_shopware_storefront.list_product_service' => 'afterInitListProductService', - 'Enlight_Bootstrap_AfterInitResource_shopware_search.product_search' => 'afterInitProductSearch' + 'Enlight_Bootstrap_AfterInitResource_shopware_search.product_search' => 'afterInitProductSearch', ]; } From 5ff909c8d7d677b160f8afefbc34cdd559f4611e Mon Sep 17 00:00:00 2001 From: Michael Telgmann Date: Sat, 13 Jan 2018 14:16:53 +0100 Subject: [PATCH 2/3] Add composer.json --- composer.json | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 composer.json diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..bd60eb0 --- /dev/null +++ b/composer.json @@ -0,0 +1,12 @@ +{ + "name": "shopware/swag-custom-sort", + "type": "shopware-frontend-plugin", + "description": "Customize the sorting of product listings", + "license": "MIT", + "extra": { + "installer-name": "SwagCustomSort" + }, + "require": { + "php": ">=5.6.4" + } +} From 7fefb2220517bb3783042331a39e8e65944eb4ec Mon Sep 17 00:00:00 2001 From: Michael Telgmann Date: Sat, 13 Jan 2018 14:17:23 +0100 Subject: [PATCH 3/3] Fix code style; Improve code; Rename article occurences to product --- .githooks/pre-commit | 11 +- Bootstrap.php | 78 +++--- Bundle/SearchBundle/SortProductSearch.php | 9 +- .../StoreFrontBundle/ListProductService.php | 18 +- Components/Listing.php | 165 +++++------- Components/Sorting.php | 55 ++-- Controllers/Backend/CustomSort.php | 227 ++++++++-------- Models/CustomSort/CustomSortRepository.php | 70 ++--- .../{ArticleSort.php => ProductSort.php} | 18 +- README.md | 2 +- Snippets/backend/custom_sort/main.ini | 4 +- Sorter/SortDBAL/Handler/DragDropHandler.php | 25 +- Sorter/SortFactory.php | 12 +- Subscriber/Backend.php | 36 ++- Subscriber/ControllerPath.php | 3 + Subscriber/Frontend.php | 3 + Subscriber/Resource.php | 4 +- Subscriber/Sort.php | 13 +- Subscriber/StoreFrontBundle.php | 4 +- Views/backend/_resources/css/custom_sort.css | 32 +-- Views/backend/custom_sort/app.js | 14 +- Views/backend/custom_sort/controller/main.js | 248 +++++++++--------- Views/backend/custom_sort/header.tpl | 5 +- .../model/{article.js => product.js} | 20 +- Views/backend/custom_sort/model/settings.js | 6 +- .../store/{article.js => product.js} | 8 +- Views/backend/custom_sort/store/settings.js | 4 +- Views/backend/custom_sort/store/tree.js | 4 +- .../backend/custom_sort/view/category/tree.js | 22 +- Views/backend/custom_sort/view/main/window.js | 10 +- .../view/{article => product}/list.js | 83 +++--- .../view/{article => product}/view.js | 22 +- plugin.json | 2 +- 33 files changed, 573 insertions(+), 664 deletions(-) rename Models/CustomSort/{ArticleSort.php => ProductSort.php} (82%) rename Views/backend/custom_sort/model/{article.js => product.js} (77%) rename Views/backend/custom_sort/store/{article.js => product.js} (71%) rename Views/backend/custom_sort/view/{article => product}/list.js (83%) rename Views/backend/custom_sort/view/{article => product}/view.js (89%) diff --git a/.githooks/pre-commit b/.githooks/pre-commit index 2ebe7ee..7289b4b 100755 --- a/.githooks/pre-commit +++ b/.githooks/pre-commit @@ -26,11 +26,11 @@ class PreCommitChecks if ($this->isRebase()) { echo 'Not on branch' . PHP_EOL; - return (int) 0; + return 0; } - $this->runPhpLint($this->getCommittedFileList('php')); - $this->runPhpCsFixer($this->getCommittedFileList('php')); + $this->runPhpLint($this->getCommittedFileList()); + $this->runPhpCsFixer($this->getCommittedFileList()); $this->runEsLint($this->getCommittedFileList('js')); if ($this->error) { @@ -118,6 +118,7 @@ class PreCommitChecks return; } + $fixes = []; foreach ($fileList as $file) { exec('./../../../../../../vendor/bin/php-cs-fixer fix -v --no-ansi --dry-run ' . escapeshellarg($file) . ' 2>&1', $output, $return); @@ -194,7 +195,7 @@ class PreCommitChecks './../../../../../../themes/node_modules/eslint/bin/eslint.js ' . '--ignore-path .eslintignore ' . '-c ./../../../../../../themes/.eslintrc.js ' . - '--global "Ext" ' . + '--global "Ext, Shopware" ' . implode(' ', $fileList), $output, $return @@ -213,7 +214,7 @@ class PreCommitChecks './../../../../../../themes/node_modules/eslint/bin/eslint.js ' . '--fix --ignore-path .eslintignore ' . '-c ./../../../../../../themes/.eslintrc.js ' . - '--global "Ext" ' . + '--global "Ext, Shopware" ' . implode(' ', $fileList), 3 ); diff --git a/Bootstrap.php b/Bootstrap.php index b18595e..7d418c9 100644 --- a/Bootstrap.php +++ b/Bootstrap.php @@ -6,6 +6,8 @@ * file that was distributed with this source code. */ +use Shopware\Components\Model\ModelManager; +use Shopware\CustomModels\CustomSort\ProductSort; use Shopware\Models\Config\Element; use Shopware\Models\Config\Form; use Shopware\SwagCustomSort\Components\Listing; @@ -38,7 +40,7 @@ public function getLabel() * * @throws Exception * - * @return string|void + * @return string */ public function getVersion() { @@ -47,7 +49,7 @@ public function getVersion() if ($info) { return $info['currentVersion']; } - throw new Exception('The plugin has an invalid version file.'); + throw new RuntimeException('The plugin has an invalid version file.'); } /** @@ -60,7 +62,7 @@ public function getVersion() public function install() { if (!$this->assertMinimumVersion('5.0.0')) { - throw new \Exception('This plugin requires Shopware 5.0.0 or a later version'); + throw new RuntimeException('This plugin requires Shopware 5.0.0 or a later version'); } $this->subscribeEvents(); @@ -75,11 +77,19 @@ public function install() /** * @param string $version * - * @return bool + * @return array */ public function update($version) { - return true; + if (version_compare($version, '2.0.0', '<=')) { + $sql = 'RENAME TABLE `s_articles_sort` TO `s_products_sort`;'; + Shopware()->Db()->query($sql); + + $sql = 'ALTER TABLE `s_products_sort` CHANGE `articleId` `productId` INT(11) NOT NULL;'; + Shopware()->Db()->query($sql); + } + + return ['success' => true, 'invalidateCache' => $this->getInvalidateCacheArray()]; } /** @@ -92,7 +102,7 @@ public function enable() $sql = "UPDATE s_core_menu SET active = 1 WHERE controller = 'CustomSort';"; Shopware()->Db()->query($sql); - return ['success' => true, 'invalidateCache' => ['backend']]; + return ['success' => true, 'invalidateCache' => $this->getInvalidateCacheArray()]; } /** @@ -105,15 +115,7 @@ public function disable() $sql = "UPDATE s_core_menu SET active = 0 WHERE controller = 'CustomSort';"; Shopware()->Db()->query($sql); - return ['success' => true, 'invalidateCache' => ['backend']]; - } - - /** - * Registers all necessary events. - */ - public function subscribeEvents() - { - $this->subscribeEvent('Enlight_Controller_Front_StartDispatch', 'onStartDispatch'); + return ['success' => true, 'invalidateCache' => $this->getInvalidateCacheArray()]; } /** @@ -156,10 +158,18 @@ public function afterInit() $this->Application()->Loader()->registerNamespace('Shopware\SwagCustomSort', $this->Path()); } + /** + * Registers all necessary events. + */ + private function subscribeEvents() + { + $this->subscribeEvent('Enlight_Controller_Front_StartDispatch', 'onStartDispatch'); + } + /** * Creates the backend menu item. */ - public function createMenu() + private function createMenu() { $parent = $this->Menu()->findOneBy(['label' => 'Artikel']); @@ -179,14 +189,14 @@ public function createMenu() /** * Creates the plugin database tables over the doctrine schema tool. */ - public function createDatabase() + private function createDatabase() { - /** @var \Shopware\Components\Model\ModelManager $em */ + /** @var ModelManager $em */ $em = $this->get('models'); $tool = new \Doctrine\ORM\Tools\SchemaTool($em); $classes = [ - $em->getClassMetadata('Shopware\CustomModels\CustomSort\ArticleSort'), + $em->getClassMetadata(ProductSort::class), ]; try { @@ -198,18 +208,16 @@ public function createDatabase() /** * creates necessary attributes for categories */ - public function createAttributes() + private function createAttributes() { - /** @var \Shopware\Components\Model\ModelManager $em */ + /** @var ModelManager $em */ $em = $this->get('models'); $em->addAttribute( 's_categories_attributes', 'swag', 'link', - 'int(11)', - true, - null + 'int(11)' ); $em->addAttribute( 's_categories_attributes', @@ -223,18 +231,14 @@ public function createAttributes() 's_categories_attributes', 'swag', 'deleted_position', - 'int(11)', - true, - null + 'int(11)' ); $em->addAttribute( 's_categories_attributes', 'swag', 'base_sort', - 'int(11)', - true, - null + 'int(11)' ); $em->generateAttributeModels(['s_categories_attributes']); @@ -243,7 +247,7 @@ public function createAttributes() /** * @param Form $form */ - protected function createForm(Form $form) + private function createForm(Form $form) { $form->setElement( 'text', @@ -269,4 +273,16 @@ protected function createForm(Form $form) ] ); } + + /** + * @return array + */ + private function getInvalidateCacheArray() + { + return [ + 'backend', + 'proxy', + 'config', + ]; + } } diff --git a/Bundle/SearchBundle/SortProductSearch.php b/Bundle/SearchBundle/SortProductSearch.php index 6eec42b..ff05267 100644 --- a/Bundle/SearchBundle/SortProductSearch.php +++ b/Bundle/SearchBundle/SortProductSearch.php @@ -11,7 +11,6 @@ use Shopware\Bundle\SearchBundle\Criteria; use Shopware\Bundle\SearchBundle\ProductNumberSearchResult; use Shopware\Bundle\SearchBundle\ProductSearchInterface; -use Shopware\Bundle\SearchBundle\ProductSearchResult; use Shopware\Bundle\StoreFrontBundle\Struct; use Shopware\SwagCustomSort\Components\Sorting; @@ -43,13 +42,7 @@ public function __construct(ProductSearchInterface $productSearch, Sorting $sort } /** - * Creates a search request on the internal search gateway to - * get the product result for the passed criteria object. - * - * @param Criteria $criteria - * @param Struct\ProductContextInterface $context - * - * @return ProductSearchResult + * {@inheritdoc} */ public function search(Criteria $criteria, Struct\ProductContextInterface $context) { diff --git a/Bundle/StoreFrontBundle/ListProductService.php b/Bundle/StoreFrontBundle/ListProductService.php index 1cc52bb..cdf1281 100644 --- a/Bundle/StoreFrontBundle/ListProductService.php +++ b/Bundle/StoreFrontBundle/ListProductService.php @@ -17,12 +17,12 @@ class ListProductService implements ListProductServiceInterface /** * @var ListProductServiceInterface */ - private $coreService = null; + private $coreService; /** * @var Sorting */ - private $sortingComponent = null; + private $sortingComponent; /** * @param ListProductServiceInterface $coreService @@ -35,10 +35,7 @@ public function __construct(ListProductServiceInterface $coreService, Sorting $s } /** - * @param string $number - * @param Struct\ProductContextInterface $context - * - * @return Struct\ListProduct + * {@inheritdoc} */ public function get($number, Struct\ProductContextInterface $context) { @@ -48,17 +45,12 @@ public function get($number, Struct\ProductContextInterface $context) } /** - * @param array $numbers - * @param Struct\ProductContextInterface $context - * - * @return Struct\ListProduct[] + * {@inheritdoc} */ public function getList(array $numbers, Struct\ProductContextInterface $context) { $getSortedNumbers = $this->sortingComponent->sortByNumber($numbers); - $products = $this->coreService->getList($getSortedNumbers, $context); - - return $products; + return $this->coreService->getList($getSortedNumbers, $context); } } diff --git a/Components/Listing.php b/Components/Listing.php index 67bd3af..422003e 100644 --- a/Components/Listing.php +++ b/Components/Listing.php @@ -9,6 +9,7 @@ namespace Shopware\SwagCustomSort\Components; use Shopware\Components\Model\ModelManager; +use Shopware\CustomModels\CustomSort\ProductSort; use Shopware\Models\Attribute\Category as CategoryAttributes; use Shopware\Models\Category\Category; use Shopware_Components_Config as Config; @@ -18,75 +19,34 @@ class Listing /** * @var Config */ - private $config = null; + private $config; /** - * @var ModelManager + * @var \Shopware\Components\Model\ModelRepository */ - private $em = null; - - private $categoryAttributesRepo = null; - - private $categoryRepo = null; - - private $customSortRepo = null; - - public function __construct(Config $config, ModelManager $em) - { - $this->config = $config; - $this->em = $em; - } + private $categoryAttributesRepo; /** - * @return Config + * @var \Shopware\Models\Category\Repository */ - public function getConfig() - { - return $this->config; - } + private $categoryRepo; /** - * @return ModelManager + * @var \Shopware\CustomModels\CustomSort\CustomSortRepository */ - public function getEntityManager() - { - return $this->em; - } - - /** - * @return null|\Shopware\Components\Model\ModelRepository - */ - public function getCategoryAttributesRepository() - { - if ($this->categoryAttributesRepo === null) { - $this->categoryAttributesRepo = $this->getEntityManager()->getRepository('Shopware\Models\Attribute\Category'); - } - - return $this->categoryAttributesRepo; - } - - /** - * @return null|\Shopware\Models\Category\Repository - */ - public function getCategoryRepository() - { - if ($this->categoryRepo === null) { - $this->categoryRepo = $this->getEntityManager()->getRepository('Shopware\Models\Category\Category'); - } - - return $this->categoryRepo; - } + private $customSortRepo; /** - * @return null|\Shopware\CustomModels\CustomSort\CustomSortRepository + * @param Config $config + * @param ModelManager $modelManager */ - public function getCustomSortRepository() + public function __construct(Config $config, ModelManager $modelManager) { - if ($this->customSortRepo === null) { - $this->customSortRepo = $this->getEntityManager()->getRepository('Shopware\CustomModels\CustomSort\ArticleSort'); - } + $this->config = $config; - return $this->customSortRepo; + $this->categoryAttributesRepo = $modelManager->getRepository(CategoryAttributes::class); + $this->categoryRepo = $modelManager->getRepository(Category::class); + $this->customSortRepo = $modelManager->getRepository(ProductSort::class); } /** @@ -114,18 +74,11 @@ public function showCustomSortName($categoryId) */ public function getFormattedSortName() { - $formattedName = $this->getSortName(); + $formattedName = $this->config->get('swagCustomSortName'); return trim($formattedName); } - public function getSortName() - { - $name = $this->getConfig()->get('swagCustomSortName'); - - return $name; - } - /** * @param $categoryId * @@ -146,45 +99,6 @@ public function hasCustomSort($categoryId) return false; } - /** - * @param $categoryId - * - * @return bool - */ - public function isLinked($categoryId) - { - /* @var CategoryAttributes $categoryAttributes */ - $categoryAttributes = $this->getCategoryAttributesRepository()->findOneBy(['categoryId' => $categoryId]); - if (!$categoryAttributes instanceof CategoryAttributes) { - return false; - } - - $linkedCategoryId = $categoryAttributes->getSwagLink(); - if ($linkedCategoryId === null) { - return false; - } - - /* @var Category $category */ - $category = $this->getCategoryRepository()->find($linkedCategoryId); - if (!$category instanceof Category) { - return false; - } - - return true; - } - - /** - * Checks whether this category has own custom sort - * - * @param $categoryId - * - * @return bool - */ - public function hasOwnSort($categoryId) - { - return $this->getCustomSortRepository()->hasCustomSort($categoryId); - } - /** * Checks whether this category has to use its custom sort by default, e.g. on category load use this custom sort * @@ -195,7 +109,7 @@ public function hasOwnSort($categoryId) public function showCustomSortAsDefault($categoryId) { /* @var CategoryAttributes $categoryAttributes */ - $categoryAttributes = $this->getCategoryAttributesRepository()->findOneBy(['categoryId' => $categoryId]); + $categoryAttributes = $this->categoryAttributesRepo->findOneBy(['categoryId' => $categoryId]); if (!$categoryAttributes instanceof CategoryAttributes) { return false; } @@ -220,7 +134,7 @@ public function showCustomSortAsDefault($categoryId) public function getLinkedCategoryId($categoryId) { /* @var CategoryAttributes $categoryAttributes */ - $categoryAttributes = $this->getCategoryAttributesRepository()->findOneBy(['categoryId' => $categoryId]); + $categoryAttributes = $this->categoryAttributesRepo->findOneBy(['categoryId' => $categoryId]); if (!$categoryAttributes instanceof CategoryAttributes) { return false; } @@ -231,7 +145,7 @@ public function getLinkedCategoryId($categoryId) } /* @var Category $category */ - $category = $this->getCategoryRepository()->find($linkedCategoryId); + $category = $this->categoryRepo->find($linkedCategoryId); if (!$category instanceof Category) { return false; } @@ -249,7 +163,7 @@ public function getLinkedCategoryId($categoryId) public function getCategoryBaseSort($categoryId) { /* @var CategoryAttributes $categoryAttributes */ - $categoryAttributes = $this->getCategoryAttributesRepository()->findOneBy(['categoryId' => $categoryId]); + $categoryAttributes = $this->categoryAttributesRepo->findOneBy(['categoryId' => $categoryId]); if (!$categoryAttributes instanceof CategoryAttributes) { return false; } @@ -261,4 +175,43 @@ public function getCategoryBaseSort($categoryId) return $baseSortId; } + + /** + * @param $categoryId + * + * @return bool + */ + private function isLinked($categoryId) + { + /* @var CategoryAttributes $categoryAttributes */ + $categoryAttributes = $this->categoryAttributesRepo->findOneBy(['categoryId' => $categoryId]); + if (!$categoryAttributes instanceof CategoryAttributes) { + return false; + } + + $linkedCategoryId = $categoryAttributes->getSwagLink(); + if ($linkedCategoryId === null) { + return false; + } + + /* @var Category $category */ + $category = $this->categoryRepo->find($linkedCategoryId); + if (!$category instanceof Category) { + return false; + } + + return true; + } + + /** + * Checks whether this category has own custom sort + * + * @param $categoryId + * + * @return bool + */ + private function hasOwnSort($categoryId) + { + return $this->customSortRepo->hasCustomSort($categoryId); + } } diff --git a/Components/Sorting.php b/Components/Sorting.php index 9f75dbd..5e76709 100644 --- a/Components/Sorting.php +++ b/Components/Sorting.php @@ -20,11 +20,6 @@ class Sorting */ private $sortedProductsIds = []; - /** - * @var array - */ - private $sortedProductsNumber = []; - /** * @var int */ @@ -49,17 +44,17 @@ public function sortProducts($allProducts, $offset, $limit) //Contain all products $allUnsortedProducts = []; foreach ($allProducts as $product) { - $allUnsortedProducts[$product['articleID']] = $product; + $allUnsortedProducts[$product['productId']] = $product; } $result = []; foreach ($this->getSortedProducts() as $sort) { - $articleId = $sort['articleID']; + $productId = $sort['productId']; $position = $sort['position']; if ($position >= $offset && $position <= ($limit + $offset)) { $result[$position] = $sort; } - unset($allUnsortedProducts[$articleId]); + unset($allUnsortedProducts[$productId]); } $i = $offset; @@ -101,7 +96,7 @@ public function sortByNumber($numbers) $result = []; foreach ($sortedProducts as $sort) { //Remove unsorted product if sorted one exists - $num = array_search($sort['ordernumber'], $numbers); + $num = array_search($sort['ordernumber'], $numbers, true); if ($num) { unset($numbers[$num]); } @@ -124,34 +119,22 @@ public function sortByNumber($numbers) ksort($result); - $getLimitedResult = array_slice($result, 0, $this->limit); - - return $getLimitedResult; - } - - /** - * Return data for all sorted products - * - * @return array - */ - public function getSortedProducts() - { - return $this->sortedProducts; + return array_slice($result, 0, $this->limit); } /** * Set proper position of sorted products * - * @param $sortedProducts + * @param array $sortedProducts */ - public function setSortedProducts($sortedProducts) + public function setSortedProducts(array $sortedProducts) { if ($sortedProducts) { foreach ($sortedProducts as $sortedProduct) { $position = $sortedProduct['position']; $this->sortedProducts[$position] = $sortedProduct; - $this->sortedProductsIds[] = $sortedProduct['articleID']; + $this->sortedProductsIds[] = $sortedProduct['productId']; } } } @@ -166,16 +149,6 @@ public function getSortedProductsIds() return $this->sortedProductsIds; } - /** - * Return array with all sorted products - * - * @return array - */ - public function getSortedProductsNumbers() - { - return $this->sortedProductsNumber; - } - /** * Return new offset by counting sorted products for in previous pages * @@ -187,7 +160,7 @@ public function getSortedProductsNumbers() */ public function getOffset($offset, $page, $limit) { - $page = $page - 1; + --$page; while ($page >= 1) { $min = ($page - 1) * $limit; $max = $page * $limit; @@ -229,4 +202,14 @@ public function getTotalCount() { return count($this->getSortedProducts()); } + + /** + * Return data for all sorted products + * + * @return array + */ + private function getSortedProducts() + { + return $this->sortedProducts; + } } diff --git a/Controllers/Backend/CustomSort.php b/Controllers/Backend/CustomSort.php index 9fafdf5..09d1eb7 100644 --- a/Controllers/Backend/CustomSort.php +++ b/Controllers/Backend/CustomSort.php @@ -6,8 +6,8 @@ * file that was distributed with this source code. */ -use Shopware\Components\Model\ModelManager; use Shopware\CustomModels\CustomSort\CustomSortRepository; +use Shopware\CustomModels\CustomSort\ProductSort; use Shopware\Models\Article\Article; use Shopware\Models\Attribute\Category as CategoryAttributes; use Shopware\Models\Category\Category; @@ -18,109 +18,38 @@ class Shopware_Controllers_Backend_CustomSort extends Shopware_Controllers_Backe /** * @var array */ - protected $categoryIdCollection; - - /** - * @var ModelManager - */ - private $em = null; + protected $categoryIdCollection = []; /** * @var CustomSortRepository */ - private $sortRepo = null; + private $sortRepo; /** * @var \Enlight_Components_Db_Adapter_Pdo_Mysql */ - private $db = null; + private $db; /** * References the shopware config object * * @var \Shopware_Components_Config */ - private $config = null; + private $config; /** * @var \Enlight_Event_EventManager */ - private $events = null; - - /** - * @return ModelManager - */ - public function getModelManager() - { - if ($this->em === null) { - $this->em = Shopware()->Models(); - } - - return $this->em; - } - - /** - * Returns sort repository - * - * @return CustomSortRepository - */ - public function getSortRepository() - { - if ($this->sortRepo === null) { - $this->sortRepo = $this->getModelManager()->getRepository('\Shopware\CustomModels\CustomSort\ArticleSort'); - } - - return $this->sortRepo; - } - - /** - * Returns pdo mysql db adapter instance - * - * @return \Enlight_Components_Db_Adapter_Pdo_Mysql - */ - public function getDB() - { - if ($this->db === null) { - $this->db = Shopware()->Db(); - } - - return $this->db; - } - - /** - * Returns config instance - * - * @return \Shopware_Components_Config - */ - public function getConfig() - { - if ($this->config === null) { - $this->config = Shopware()->Config(); - } - - return $this->config; - } - - /** - * @return \Enlight_Event_EventManager - */ - public function getEvents() - { - if ($this->events === null) { - $this->events = Shopware()->Events(); - } - - return $this->events; - } + private $events; /** - * Get article list and images for current category + * Get product list and images for current category */ - public function getArticleListAction() + public function getProductListAction() { $categoryId = (int) $this->Request()->getParam('categoryId'); $page = (int) $this->Request()->getParam('page'); - $limit = (int) $this->Request()->getParam('limit', null); + $limit = (int) $this->Request()->getParam('limit'); $offset = (int) $this->Request()->getParam('start'); $defaultSort = $this->getConfig()->get('defaultListingSorting'); @@ -136,9 +65,9 @@ public function getArticleListAction() $sortedProductsIds = $sorting->getSortedProductsIds(); $newOffset = $sorting->getOffset($offset, $page, $limit); $builder = $this->getSortRepository() - ->getArticleImageQuery($categoryId, $sortedProductsIds, $sort, $newOffset, $limit); + ->getProductImageQuery($categoryId, $sortedProductsIds, $sort, $newOffset, $limit); - $countBuilder = $this->getSortRepository()->getArticleImageCountQuery($categoryId); + $countBuilder = $this->getSortRepository()->getProductImageCountQuery($categoryId); $total = $countBuilder->execute()->fetch(); $getUnsortedProducts = $builder->execute()->fetchAll(); @@ -173,7 +102,7 @@ public function getCategorySettingsAction() ]; /** @var CategoryAttributes $categoryAttributes */ - $categoryAttributes = $this->getModelManager()->getRepository('\Shopware\Models\Attribute\Category') + $categoryAttributes = $this->getModelManager()->getRepository(CategoryAttributes::class) ->findOneBy(['categoryId' => $categoryId]); if ($categoryAttributes) { $baseSort = $categoryAttributes->getSwagBaseSort(); @@ -214,14 +143,14 @@ public function saveCategorySettingsAction() /** * Save product list after product reorder */ - public function saveArticleListAction() + public function saveProductListAction() { $movedProducts = $this->Request()->getParam('products'); if (empty($movedProducts)) { return; } - if ($movedProducts['articleID']) { + if ($movedProducts['productId']) { $movedProducts = [$movedProducts]; } @@ -241,7 +170,7 @@ public function saveArticleListAction() //Get unsorted products for current category $sortedProductsIds = $sorting->getSortedProductsIds(); - $builder = $this->getSortRepository()->getArticleImageQuery($categoryId, $sortedProductsIds, $sort); + $builder = $this->getSortRepository()->getProductImageQuery($categoryId, $sortedProductsIds, $sort); $getProducts = $builder->execute()->fetchAll(); //Return result with proper position of all products @@ -260,7 +189,7 @@ public function saveArticleListAction() $sqlValues = $this->getSQLValues($sortedProducts, $categoryId); //update positions - $sql = 'REPLACE INTO s_articles_sort (id, categoryId, articleId, position, pin) VALUES ' + $sql = 'REPLACE INTO s_products_sort (id, categoryId, productId, position, pin) VALUES ' . rtrim($sqlValues, ','); $this->getDB()->query($sql); @@ -279,14 +208,14 @@ public function saveArticleListAction() /** * Unpin product */ - public function unpinArticleAction() + public function unpinProductAction() { $product = $this->Request()->getParam('products'); $sortId = (int) $product['positionId']; try { if (!$sortId) { - throw new Exception("Unpin product '{$product['name']}' with id '{$product['id']}', failed!"); + throw new RuntimeException("Unpin product '{$product['name']}' with id '{$product['id']}', failed!"); } $categoryId = (int) $this->Request()->getParam('categoryId'); @@ -306,27 +235,24 @@ public function unpinArticleAction() */ public function removeProductAction() { - $articleId = (int) $this->Request()->get('articleId'); + $productId = (int) $this->Request()->get('productId'); $categoryId = (int) $this->Request()->get('categoryId'); /** @var Category $category */ - $category = Shopware()->Models()->getReference('Shopware\Models\Category\Category', $categoryId); + $category = Shopware()->Models()->getReference(Category::class, $categoryId); if ($category) { $this->collectCategoryIds($category); - $categories = $this->getCategoryIdCollection(); - - /** @var Article $article */ - $article = Shopware()->Models()->getReference('Shopware\Models\Article\Article', (int) $articleId); - $article->removeCategory($category); - - if ($categories) { - foreach ($categories as $childCategoryId) { - /** @var Category $childCategoryModel */ - $childCategoryModel = Shopware()->Models() - ->getReference('Shopware\Models\Category\Category', $childCategoryId); - if ($childCategoryModel) { - $article->removeCategory($childCategoryModel); - } + + /** @var Article $product */ + $product = Shopware()->Models()->getReference(Article::class, $productId); + $product->removeCategory($category); + + foreach ($this->categoryIdCollection as $childCategoryId) { + /** @var Category $childCategoryModel */ + $childCategoryModel = Shopware()->Models() + ->getReference(Category::class, $childCategoryId); + if ($childCategoryModel) { + $product->removeCategory($childCategoryModel); } } @@ -337,23 +263,65 @@ public function removeProductAction() } /** - * Get category ids collection. + * Returns sort repository * - * @return array + * @return CustomSortRepository + */ + private function getSortRepository() + { + if ($this->sortRepo === null) { + $this->sortRepo = $this->getModelManager()->getRepository(ProductSort::class); + } + + return $this->sortRepo; + } + + /** + * Returns pdo mysql db adapter instance + * + * @return \Enlight_Components_Db_Adapter_Pdo_Mysql */ - public function getCategoryIdCollection() + private function getDB() { - return $this->categoryIdCollection; + if ($this->db === null) { + $this->db = Shopware()->Db(); + } + + return $this->db; + } + + /** + * Returns config instance + * + * @return \Shopware_Components_Config + */ + private function getConfig() + { + if ($this->config === null) { + $this->config = Shopware()->Config(); + } + + return $this->config; + } + + /** + * @return \Enlight_Event_EventManager + */ + private function getEvents() + { + if ($this->events === null) { + $this->events = Shopware()->Events(); + } + + return $this->events; } /** * Insert category id to category ids collection. * * @param $categoryIdCollection - * - * @return array */ - public function setCategoryIdCollection($categoryIdCollection) + private function setCategoryIdCollection($categoryIdCollection) { $this->categoryIdCollection[] = $categoryIdCollection; } @@ -434,24 +402,29 @@ private function applyNewPosition($allProducts, $products, $index) private function getSQLValues($productsForUpdate, $categoryId) { $sqlValues = ''; - foreach ($productsForUpdate as $newArticle) { - if ($newArticle['articleID'] > 0 && $newArticle['pin'] > 0) { - $sqlValues .= "('" . $newArticle['positionId'] . "', '" + foreach ($productsForUpdate as $newProduct) { + if ($newProduct['productId'] > 0 && $newProduct['pin'] > 0) { + $sqlValues .= "('" . $newProduct['positionId'] . "', '" . $categoryId . "', '" - . $newArticle['articleID'] . "', '" - . $newArticle['position'] . "', '" - . $newArticle['pin'] . "'),"; + . $newProduct['productId'] . "', '" + . $newProduct['position'] . "', '" + . $newProduct['pin'] . "'),"; } } return $sqlValues; } - private function prepareKeys($products) + /** + * @param array $products + * + * @return array + */ + private function prepareKeys(array $products) { $result = []; foreach ($products as $product) { - $result[$product['articleID']] = $product; + $result[$product['productId']] = $product; } return $result; @@ -528,7 +501,13 @@ private function getLength($products, $offset, $categoryId) return $length; } - private function fixDeletedPosition($deletedPosition, $allProducts) + /** + * @param int $deletedPosition + * @param array $allProducts + * + * @return array + */ + private function fixDeletedPosition($deletedPosition, array $allProducts) { $index = $deletedPosition; foreach ($allProducts as &$product) { @@ -546,7 +525,10 @@ private function fixDeletedPosition($deletedPosition, $allProducts) return $allProducts; } - private function invalidateProductCache($movedProducts) + /** + * @param array $movedProducts + */ + private function invalidateProductCache(array $movedProducts) { //Invalidate the cache for the current product foreach ($movedProducts as $product) { @@ -554,7 +536,6 @@ private function invalidateProductCache($movedProducts) 'Shopware_Plugins_HttpCache_InvalidateCacheId', ['cacheId' => "a{$product['id']}"] ); - break; } } diff --git a/Models/CustomSort/CustomSortRepository.php b/Models/CustomSort/CustomSortRepository.php index 372139a..92c03f6 100644 --- a/Models/CustomSort/CustomSortRepository.php +++ b/Models/CustomSort/CustomSortRepository.php @@ -27,13 +27,11 @@ public function hasCustomSort($categoryId) $builder = $this->getQueryBuilder(); $builder->select('id') - ->from('s_articles_sort', 'sort') + ->from('s_products_sort', 'sort') ->where('categoryId = :categoryId') ->setParameter('categoryId', $categoryId); - $result = (bool) $builder->execute()->fetchColumn(); - - return $result; + return (bool) $builder->execute()->fetchColumn(); } /** @@ -49,13 +47,11 @@ public function getMaxPosition($categoryId) $builder = $this->getQueryBuilder(); $builder->select('MAX(position)') - ->from('s_articles_sort', 'sort') + ->from('s_products_sort', 'sort') ->where('categoryId = :categoryId') ->setParameter('categoryId', $categoryId); - $max = $builder->execute()->fetchColumn(); - - return $max; + return $builder->execute()->fetchColumn(); } /** @@ -69,13 +65,13 @@ public function getMaxPosition($categoryId) * * @return mixed */ - public function getArticleImageQuery($categoryId, $sortedProductsIds, $orderBy, $offset = null, $limit = null) + public function getProductImageQuery($categoryId, $sortedProductsIds, $orderBy, $offset = null, $limit = null) { $builder = $this->getQueryBuilder(); $builder->select( [ - 'product.id as articleID', + 'product.id as productId', 'product.name', 'images.img as path', 'images.extension', @@ -118,7 +114,7 @@ public function getSortedProducts($categoryId, $linkedCategoryId = false) $builder->select( [ 'sort.id as positionId', - 'product.id as articleID', + 'product.id as productId', 'productDetail.ordernumber', 'product.name', 'images.img as path', @@ -138,15 +134,13 @@ public function getSortedProducts($categoryId, $linkedCategoryId = false) ->setParameter('categoryId', $categoryId); if ($linkedCategoryId !== false) { - $builder->leftJoin('product', 's_articles_sort', 'sort', 'product.id = sort.articleId AND sort.categoryId = :linkedCategoryId OR sort.categoryId IS NULL') + $builder->leftJoin('product', 's_products_sort', 'sort', 'product.id = sort.productId AND sort.categoryId = :linkedCategoryId OR sort.categoryId IS NULL') ->setParameter('linkedCategoryId', $linkedCategoryId); } else { - $builder->leftJoin('product', 's_articles_sort', 'sort', 'product.id = sort.articleId AND (sort.categoryId = productCategory.categoryID OR sort.categoryId IS NULL)'); + $builder->leftJoin('product', 's_products_sort', 'sort', 'product.id = sort.productId AND (sort.categoryId = productCategory.categoryID OR sort.categoryId IS NULL)'); } - $result = $builder->execute()->fetchAll(); - - return $result; + return $builder->execute()->fetchAll(); } /** @@ -156,7 +150,7 @@ public function getSortedProducts($categoryId, $linkedCategoryId = false) * * @return mixed */ - public function getArticleImageCountQuery($categoryId) + public function getProductImageCountQuery($categoryId) { $builder = $this->getQueryBuilder(); @@ -173,13 +167,13 @@ public function getArticleImageCountQuery($categoryId) /** * Sets pin value to 0 * - * @param $id - the id of the s_articles_sort record + * @param $id - the id of the s_products_sort record */ public function unpinById($id) { $builder = $this->getQueryBuilder(); - $builder->update('s_articles_sort') + $builder->update('s_products_sort') ->set('pin', 0) ->where('id = :id') ->setParameter('id', $id); @@ -201,7 +195,7 @@ public function deleteUnpinnedRecords($categoryId) $builder = $this->getQueryBuilder(); - $builder->delete('s_articles_sort') + $builder->delete('s_products_sort') ->where('categoryId = :categoryId') ->andWhere('position >= :maxPinPosition') ->andWhere('pin = 0') @@ -223,36 +217,32 @@ public function getMaxPinPosition($categoryId) $builder = $this->getQueryBuilder(); $builder->select(['MAX(position) AS maxPinPosition']) - ->from('s_articles_sort', 'sort') + ->from('s_products_sort', 'sort') ->where('categoryId = :categoryId') ->andWhere('pin = 1') ->orderBy('position', 'DESC') ->setParameter('categoryId', $categoryId); - $maxPinPosition = $builder->execute()->fetchColumn(); - - return $maxPinPosition; + return $builder->execute()->fetchColumn(); } /** * Returns product position for selected product * - * @param $articleId + * @param int $productId * - * @return mixed + * @return string */ - public function getPositionByArticleId($articleId) + public function getPositionByProductId($productId) { $builder = $this->getQueryBuilder(); $builder->select(['position']) - ->from('s_articles_sort', 'sort') - ->where('articleId = :articleId') - ->setParameter('articleId', $articleId); + ->from('s_products_sort', 'sort') + ->where('productId = :productId') + ->setParameter('productId', $productId); - $position = $builder->execute()->fetchColumn(); - - return $position; + return $builder->execute()->fetchColumn(); } /** @@ -271,9 +261,7 @@ public function getPositionOfDeletedProduct($categoryId) ->where('categoryID = :categoryId') ->setParameter('categoryId', $categoryId); - $deletedPosition = $builder->execute()->fetchColumn(); - - return $deletedPosition; + return $builder->execute()->fetchColumn(); } /** @@ -296,8 +284,8 @@ public function resetDeletedPosition($categoryId) /** * Update category attributes for selected category * - * @param $categoryId - * @param $baseSort + * @param int $categoryId + * @param int $baseSort * @param null $categoryLink * @param null $defaultSort */ @@ -309,7 +297,7 @@ public function updateCategoryAttributes($categoryId, $baseSort, $categoryLink = ->where('categoryID = :categoryId') ->setParameter('categoryId', $categoryId); - if ($baseSort != 0) { + if ($baseSort !== 0) { $builder->set('swag_base_sort', $baseSort); } @@ -392,9 +380,7 @@ private function getQueryBuilder() { /** @var ModelManager $em */ $em = $this->getEntityManager(); - /** @var QueryBuilder $builder */ - $builder = $em->getDBALQueryBuilder(); - return $builder; + return $em->getDBALQueryBuilder(); } } diff --git a/Models/CustomSort/ArticleSort.php b/Models/CustomSort/ProductSort.php similarity index 82% rename from Models/CustomSort/ArticleSort.php rename to Models/CustomSort/ProductSort.php index ec2d365..0077587 100644 --- a/Models/CustomSort/ArticleSort.php +++ b/Models/CustomSort/ProductSort.php @@ -13,10 +13,10 @@ /** * @ORM\Entity - * @ORM\Table(name="s_articles_sort", indexes={@ORM\Index(name="articleId", columns={"articleId"})}) + * @ORM\Table(name="s_products_sort", indexes={@ORM\Index(name="productId", columns={"productId"})}) * @ORM\Entity(repositoryClass="CustomSortRepository") */ -class ArticleSort extends ModelEntity +class ProductSort extends ModelEntity { /** * @var int @@ -37,9 +37,9 @@ class ArticleSort extends ModelEntity /** * @var int * - * @ORM\Column(name="articleId", type="integer") + * @ORM\Column(name="productId", type="integer") */ - private $articleId; + private $productId; /** * @var int @@ -66,17 +66,17 @@ public function getId() /** * @return int */ - public function getArticleId() + public function getProductId() { - return $this->articleId; + return $this->productId; } /** - * @param int $articleId + * @param int $productId */ - public function setArticleId($articleId) + public function setProductId($productId) { - $this->articleId = $articleId; + $this->productId = $productId; } /** diff --git a/README.md b/README.md index 83266dc..48c2065 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ # SwagCustomSort -> Working with Shopware version 5.0.0 to 5.1.1. +> Working with Shopware version 5.0.0 to 5.2.27. > Higher versions may work either but were not tested. ## Description diff --git a/Snippets/backend/custom_sort/main.ini b/Snippets/backend/custom_sort/main.ini index 6962468..7e69430 100644 --- a/Snippets/backend/custom_sort/main.ini +++ b/Snippets/backend/custom_sort/main.ini @@ -1,7 +1,7 @@ [en_GB] window/title = "Custom category sorting" view/tree/title = "Categories" -list/no_articles = "No articles found" +list/no_products = "No products found" view/default_sort = "Show this sort order by default" view/category_sync = "Sync from category" view/category_sync/empty_text = "Please select a category" @@ -27,7 +27,7 @@ list/pagingCombo/allProducts = "All products" [de_DE] window/title = "Individuelle Kategoriesortierung" view/tree/title = "Kategorien" -list/no_articles = "Keine Artikel gefunden" +list/no_products = "Keine Artikel gefunden" view/default_sort = "Diese Sortierung als Standard anzeigen" view/category_sync = "Von Kategorie synchronisieren" view/category_sync/empty_text = "Bitte wählen Sie eine Kategorie" diff --git a/Sorter/SortDBAL/Handler/DragDropHandler.php b/Sorter/SortDBAL/Handler/DragDropHandler.php index dfd6473..c81b378 100644 --- a/Sorter/SortDBAL/Handler/DragDropHandler.php +++ b/Sorter/SortDBAL/Handler/DragDropHandler.php @@ -40,9 +40,7 @@ public function __construct(Sorting $sortingComponent) } /** - * @param SortingInterface $sorting - * - * @return bool + * {@inheritdoc} */ public function supportsSorting(SortingInterface $sorting) { @@ -50,11 +48,7 @@ public function supportsSorting(SortingInterface $sorting) } /** - * @param SortingInterface $sorting - * @param QueryBuilder $query - * @param ShopContextInterface $context - * - * @throws \Exception + * {@inheritdoc} */ public function generateSorting(SortingInterface $sorting, QueryBuilder $query, ShopContextInterface $context) { @@ -74,17 +68,17 @@ public function generateSorting(SortingInterface $sorting, QueryBuilder $query, if ($linkedCategoryId) { $query->leftJoin( 'productCategory', - 's_articles_sort', + 's_products_sort', 'customSort', - 'customSort.articleId = productCategory.articleID AND (customSort.categoryId = :sortCategoryId OR customSort.categoryId IS NULL)' + 'customSort.productId = productCategory.articleID AND (customSort.categoryId = :sortCategoryId OR customSort.categoryId IS NULL)' ); $query->setParameter('sortCategoryId', $linkedCategoryId); } else { $query->leftJoin( 'productCategory', - 's_articles_sort', + 's_products_sort', 'customSort', - 'customSort.articleId = productCategory.articleID AND (customSort.categoryId = productCategory.categoryID OR customSort.categoryId IS NULL)' + 'customSort.productId = productCategory.articleID AND (customSort.categoryId = productCategory.categoryID OR customSort.categoryId IS NULL)' ); } @@ -105,9 +99,11 @@ public function generateSorting(SortingInterface $sorting, QueryBuilder $query, /** * @param $defaultSort * + * @throws \RuntimeException + * * @return array */ - protected function getDefaultData($defaultSort) + private function getDefaultData($defaultSort) { switch ($defaultSort) { case StoreFrontCriteriaFactory::SORTING_RELEASE_DATE: @@ -155,6 +151,9 @@ protected function getDefaultData($defaultSort) 'handler' => new StockSortingHandler(), 'direction' => 'DESC', ]; + + default: + throw new \RuntimeException('No matching sort found'); } } } diff --git a/Sorter/SortFactory.php b/Sorter/SortFactory.php index db9f9aa..0bd259e 100644 --- a/Sorter/SortFactory.php +++ b/Sorter/SortFactory.php @@ -17,10 +17,14 @@ class SortFactory { const DRAG_DROP_SORTING = 8; - private $request = null; + private $request; - private $criteria = null; + private $criteria; + /** + * @param Request $request + * @param Criteria $criteria + */ public function __construct(Request $request, Criteria $criteria) { $this->request = $request; @@ -28,7 +32,7 @@ public function __construct(Request $request, Criteria $criteria) } /** - * @return Request|null + * @return Request */ public function getRequest() { @@ -36,7 +40,7 @@ public function getRequest() } /** - * @return Criteria|null + * @return Criteria */ public function getCriteria() { diff --git a/Subscriber/Backend.php b/Subscriber/Backend.php index 54881ec..8abe766 100644 --- a/Subscriber/Backend.php +++ b/Subscriber/Backend.php @@ -12,6 +12,8 @@ use Enlight_Controller_ActionEventArgs as ActionEventArgs; use Enlight_Event_EventArgs as EventArgs; use Shopware\Components\Model\ModelManager; +use Shopware\CustomModels\CustomSort\CustomSortRepository; +use Shopware\CustomModels\CustomSort\ProductSort; use Shopware\Models\Article\Article; use Shopware\Models\Category\Category; use Shopware_Plugins_Frontend_SwagCustomSort_Bootstrap as SwagCustomSort_Bootstrap; @@ -29,9 +31,9 @@ class Backend implements SubscriberInterface protected $em; /** - * @var \Shopware\CustomModels\CustomSort\CustomSortRepository + * @var CustomSortRepository */ - protected $customSortRepo = null; + private $customSortRepo; /** * @param SwagCustomSort_Bootstrap $bootstrap @@ -43,11 +45,14 @@ public function __construct(SwagCustomSort_Bootstrap $bootstrap, ModelManager $e $this->em = $em; } + /** + * {@inheritdoc} + */ public static function getSubscribedEvents() { return [ 'Enlight_Controller_Action_PostDispatchSecure_Backend_Index' => 'onPostDispatchSecureBackendIndex', - 'Shopware\Models\Article\Article::preRemove' => 'preRemoveArticle', + 'Shopware\Models\Article\Article::preRemove' => 'preRemoveProduct', 'Shopware\Models\Category\Category::preRemove' => 'preRemoveCategory', ]; } @@ -66,15 +71,15 @@ public function onPostDispatchSecureBackendIndex(ActionEventArgs $args) /** * @param EventArgs $arguments */ - public function preRemoveArticle(EventArgs $arguments) + public function preRemoveProduct(EventArgs $arguments) { - /** @var Article $articleModel */ - $articleModel = $arguments->get('entity'); - $articleDetailId = $articleModel->getId(); + /** @var Article $productModel */ + $productModel = $arguments->get('entity'); + $productVariantId = (int) $productModel->getId(); - $position = $this->getSortRepository()->getPositionByArticleId($articleDetailId); + $position = $this->getSortRepository()->getPositionByProductId($productVariantId); if ($position) { - $categories = $articleModel->getCategories(); + $categories = $productModel->getCategories(); /** @var Category $category */ foreach ($categories as $category) { $catAttributes = $category->getAttribute(); @@ -86,9 +91,9 @@ public function preRemoveArticle(EventArgs $arguments) } $builder = $this->em->getDBALQueryBuilder(); - $builder->delete('s_articles_sort') - ->where('articleId = :articleId') - ->setParameter('articleId', $articleDetailId); + $builder->delete('s_products_sort') + ->where('productId = :productId') + ->setParameter('productId', $productVariantId); $builder->execute(); } @@ -102,17 +107,20 @@ public function preRemoveCategory(EventArgs $arguments) $categoryId = $categoryModel->getId(); $builder = $this->em->getDBALQueryBuilder(); - $builder->delete('s_articles_sort') + $builder->delete('s_products_sort') ->where('categoryId = :categoryId') ->setParameter('categoryId', $categoryId); $builder->execute(); } + /** + * @return CustomSortRepository + */ private function getSortRepository() { if ($this->customSortRepo === null) { - $this->customSortRepo = $this->em->getRepository('Shopware\CustomModels\CustomSort\ArticleSort'); + $this->customSortRepo = $this->em->getRepository(ProductSort::class); } return $this->customSortRepo; diff --git a/Subscriber/ControllerPath.php b/Subscriber/ControllerPath.php index 79f1944..ad8399f 100644 --- a/Subscriber/ControllerPath.php +++ b/Subscriber/ControllerPath.php @@ -36,6 +36,9 @@ public function __construct($bootstrapPath, TemplateManager $templateManager) $this->templateManager = $templateManager; } + /** + * {@inheritdoc} + */ public static function getSubscribedEvents() { return [ diff --git a/Subscriber/Frontend.php b/Subscriber/Frontend.php index 67d73c4..1706521 100644 --- a/Subscriber/Frontend.php +++ b/Subscriber/Frontend.php @@ -33,6 +33,9 @@ public function __construct($bootstrap) $this->bootstrap = $bootstrap; } + /** + * {@inheritdoc} + */ public static function getSubscribedEvents() { return [ diff --git a/Subscriber/Resource.php b/Subscriber/Resource.php index ac2d236..bb94301 100644 --- a/Subscriber/Resource.php +++ b/Subscriber/Resource.php @@ -63,9 +63,9 @@ public function onInitListingComponent() } /** - * returns new instance of Listing + * returns new instance of Sorting * - * @return Listing + * @return Sorting */ public function onInitSortingComponent() { diff --git a/Subscriber/Sort.php b/Subscriber/Sort.php index 1943ee7..81a2507 100644 --- a/Subscriber/Sort.php +++ b/Subscriber/Sort.php @@ -13,6 +13,7 @@ use Enlight_Event_EventArgs; use Shopware\Bundle\SearchBundle\Criteria; use Shopware\Components\Model\ModelManager; +use Shopware\CustomModels\CustomSort\ProductSort; use Shopware\SwagCustomSort\Components\Listing; use Shopware\SwagCustomSort\Components\Sorting; use Shopware\SwagCustomSort\Sorter\SortDBAL\Handler\DragDropHandler; @@ -48,9 +49,7 @@ public function __construct(ModelManager $em, Sorting $sortingComponent, Listing } /** - * Returns an array of event names this subscriber wants to listen to. - * - * @return array The event names to listen to + * {@inheritdoc} */ public static function getSubscribedEvents() { @@ -77,7 +76,7 @@ public function onCreateListingCriteria(Enlight_Event_EventArgs $args) $allowedActions = ['index', 'ajaxListing', 'productNavigation']; //Don't apply custom sort if we are not in category listing - if (!in_array($request->getActionName(), $allowedActions)) { + if (!in_array($request->getActionName(), $allowedActions, true)) { return; } @@ -91,12 +90,12 @@ public function onCreateListingCriteria(Enlight_Event_EventArgs $args) $baseSort = $this->listingComponent->getCategoryBaseSort($categoryId); $sortId = $request->getParam('sSort'); - if ($request->getParam('sSort') == SortFactory::DRAG_DROP_SORTING) { + if ((int) $sortId === SortFactory::DRAG_DROP_SORTING) { $useDefaultSort = true; } if ((!$useDefaultSort && $baseSort) || empty($sortName) - || ($sortId !== null && $sortId != SortFactory::DRAG_DROP_SORTING) + || ($sortId !== null && (int) $sortId !== SortFactory::DRAG_DROP_SORTING) ) { return; } @@ -110,7 +109,7 @@ public function onCreateListingCriteria(Enlight_Event_EventArgs $args) //Get all sorted products for current category and set them in components for further sorting $linkedCategoryId = $this->listingComponent->getLinkedCategoryId($categoryId); - $sortedProducts = $this->em->getRepository('\Shopware\CustomModels\CustomSort\ArticleSort') + $sortedProducts = $this->em->getRepository(ProductSort::class) ->getSortedProducts($categoryId, $linkedCategoryId); $this->sortingComponent->setSortedProducts($sortedProducts); diff --git a/Subscriber/StoreFrontBundle.php b/Subscriber/StoreFrontBundle.php index 8502166..dcb724f 100644 --- a/Subscriber/StoreFrontBundle.php +++ b/Subscriber/StoreFrontBundle.php @@ -37,9 +37,7 @@ public function __construct(Container $container, Sorting $sortingComponent) } /** - * Returns an array of event names this subscriber wants to listen to. - * - * @return array The event names to listen to + * {@inheritdoc} */ public static function getSubscribedEvents() { diff --git a/Views/backend/_resources/css/custom_sort.css b/Views/backend/_resources/css/custom_sort.css index 91c0cfc..cd8fa9d 100644 --- a/Views/backend/_resources/css/custom_sort.css +++ b/Views/backend/_resources/css/custom_sort.css @@ -7,7 +7,7 @@ margin-left: 5px; } -.x-article-sort .thumb { +.x-product-sort .thumb { float: left; position: relative; width: 175px; @@ -21,13 +21,13 @@ box-shadow: 0 0 5px rgba(0, 0, 0, 0.35); } -.x-article-sort .thumb .detail { +.x-product-sort .thumb .detail { position: absolute; bottom: 0; width: 95%; } -.x-article-sort .thumb .pin { +.x-product-sort .thumb .pin { position: absolute; top: 5px; right: 10px; @@ -36,14 +36,14 @@ background-position: 0 -1044px !important } -.x-article-sort .thumb .remove { +.x-product-sort .thumb .remove { display: block; width: 16px; height: 16px; } -.x-article-sort .thumb .pin, -.x-article-sort .thumb .remove { +.x-product-sort .thumb .pin, +.x-product-sort .thumb .remove { cursor: pointer; } @@ -70,7 +70,7 @@ } .detail .paging span.prev { - background-position: 0px -66px; + background-position: 0 -66px; } .detail .paging span.prev.disabled { @@ -79,7 +79,7 @@ } .detail .paging span.next { - background-position: 0px -462px; + background-position: 0 -462px; } .detail .paging span.next.disabled { @@ -88,7 +88,7 @@ } .detail .paging span.last { - background-position: 0px -330px; + background-position: 0 -330px; } .detail .paging span.last.disabled { @@ -96,20 +96,20 @@ background-position: 0 -264px; } -.x-article-sort .thumb span { +.x-product-sort .thumb span { display: block; width: 95%; text-align: center; } -.x-article-sort .thumb.x-item-selected { +.x-product-sort .thumb.x-item-selected { -webkit-box-shadow: 0 0 5px #189eff; -moz-box-shadow: 0 0 5px #189eff; box-shadow: 0 0 5px #189eff; border-color: #189eff; } -.x-article-sort .thumb.drag-over:before { +.x-product-sort .thumb.drag-over:before { position: absolute; height: 205px; left: -15px; @@ -121,8 +121,8 @@ background-position: left bottom, left top, 3px top; } -.x-article-sort .empty-text { - box-shadow: #f5f7f8 0 1px 0px 0 inset, #f5f7f8 0 -1px 0px 0 inset, #f5f7f8 -1px 0 0px 0 inset, #f5f7f8 1px 0 0px 0 inset; +.x-product-sort .empty-text { + box-shadow: #f5f7f8 0 1px 0 0 inset, #f5f7f8 0 -1px 0 0 inset, #f5f7f8 -1px 0 0 0 inset, #f5f7f8 1px 0 0 0 inset; top: 50%; left: 50%; width: 150px; @@ -132,7 +132,7 @@ padding: 6px; } -.x-article-sort .empty-text span { +.x-product-sort .empty-text span { display: block; background: #f0f2f4; color: #668498; @@ -140,4 +140,4 @@ font: 11px/18px Arial, Verdana, sans-serif; text-align: center; padding: 4px 0; -} \ No newline at end of file +} diff --git a/Views/backend/custom_sort/app.js b/Views/backend/custom_sort/app.js index 7efb1d5..80ad0bd 100644 --- a/Views/backend/custom_sort/app.js +++ b/Views/backend/custom_sort/app.js @@ -1,5 +1,5 @@ -//{namespace name="backend/custom_sort/view/main"} -//{block name="backend/custom_sort/app"} +// {namespace name="backend/custom_sort/view/main"} +// {block name="backend/custom_sort/app"} Ext.define('Shopware.apps.CustomSort', { /** @@ -37,20 +37,20 @@ Ext.define('Shopware.apps.CustomSort', { models: [ 'Settings', - 'Article' + 'Product' ], stores: [ 'Settings', 'Tree', - 'Article' + 'Product' ], views: [ 'main.Window', 'category.Tree', - 'article.View', - 'article.List' + 'product.View', + 'product.List' ], /** @@ -61,4 +61,4 @@ Ext.define('Shopware.apps.CustomSort', { return this.getController('Main').mainWindow; } }); -//{/block} \ No newline at end of file +// {/block} diff --git a/Views/backend/custom_sort/controller/main.js b/Views/backend/custom_sort/controller/main.js index 5322bd9..e0307fe 100644 --- a/Views/backend/custom_sort/controller/main.js +++ b/Views/backend/custom_sort/controller/main.js @@ -1,5 +1,5 @@ -//{namespace name="backend/custom_sort/main"} -//{block name="backend/custom_sort/controller/main"} +// {namespace name="backend/custom_sort/main"} +// {block name="backend/custom_sort/controller/main"} Ext.define('Shopware.apps.CustomSort.controller.Main', { /** @@ -21,8 +21,8 @@ Ext.define('Shopware.apps.CustomSort.controller.Main', { * @array */ refs: [ - { ref: 'articleView', selector: 'sort-articles-view' }, - { ref: 'articleList', selector: 'sort-articles-list' } + { ref: 'productView', selector: 'sort-products-view' }, + { ref: 'productList', selector: 'sort-products-list' } ], /** @@ -39,7 +39,7 @@ Ext.define('Shopware.apps.CustomSort.controller.Main', { me.subApplication.treeStore = me.subApplication.getStore('Tree'); me.subApplication.treeStore.load(); - me.subApplication.articleStore = me.subApplication.getStore('Article'); + me.subApplication.productStore = me.subApplication.getStore('Product'); me.subApplication.categorySettings = me.subApplication.getStore('Settings'); @@ -47,18 +47,18 @@ Ext.define('Shopware.apps.CustomSort.controller.Main', { 'sort-category-tree': { itemclick: me.onCategorySelect }, - 'sort-articles-view': { + 'sort-products-view': { defaultSort: me.onSaveSettings, sortChange: me.onSortChange, categoryLink: me.onSaveSettings }, - 'sort-articles-list': { + 'sort-products-list': { pageChange: me.onPageChange, moveToStart: me.onMoveToStart, moveToEnd: me.onMoveToEnd, moveToPrevPage: me.onMoveToPrevPage, moveToNextPage: me.onMoveToNextPage, - articleMove: me.onArticleMove, + productMove: me.onProductMove, unpin: me.onUnpin, remove: me.onRemove } @@ -66,7 +66,7 @@ Ext.define('Shopware.apps.CustomSort.controller.Main', { me.mainWindow = me.getView('main.Window').create({ treeStore: me.subApplication.treeStore, - articleStore: me.subApplication.articleStore, + productStore: me.subApplication.productStore, categorySettings: me.subApplication.categorySettings }).show(); @@ -74,12 +74,12 @@ Ext.define('Shopware.apps.CustomSort.controller.Main', { }, /** - * Event listener function of the article list panel. + * Event listener function of the product list panel. * Fired when the user uses paging navigation. */ onPageChange: function () { var me = this, - list = me.getArticleList(); + list = me.getProductList(); list.setLoading(true); }, @@ -88,15 +88,15 @@ Ext.define('Shopware.apps.CustomSort.controller.Main', { * Event listener function of the category tree panel. * Fired when the user select category from category tree. * - * @param [object] view - Ext.view.View - * @param [Ext.data.Model] The selected record + * @param { object } view - Ext.view.View + * @param { Ext.data.Model } record The selected record */ onCategorySelect: function (view, record) { var me = this, - grid = me.getArticleView(), - list = me.getArticleList(); + grid = me.getProductView(), + list = me.getProductList(); - //Hide grid buttons on category select + // Hide grid buttons on category select grid.setDisabled(true); list.setDisabled(true); list.setLoading(true); @@ -126,20 +126,20 @@ Ext.define('Shopware.apps.CustomSort.controller.Main', { list.setDisabled(false); } - me.subApplication.articleStore.getProxy().extraParams = { + me.subApplication.productStore.getProxy().extraParams = { categoryId: me.categoryId, sortBy: baseSort }; - me.subApplication.articleStore.filters.clear(); - me.subApplication.articleStore.currentPage = 1; - me.subApplication.articleStore.load(); + me.subApplication.productStore.filters.clear(); + me.subApplication.productStore.currentPage = 1; + me.subApplication.productStore.load(); grid.sorting.setValue(baseSort); } } }); - me.subApplication.articleStore.on('load', function () { + me.subApplication.productStore.on('load', function () { list.setLoading(false); }); }, @@ -147,22 +147,22 @@ Ext.define('Shopware.apps.CustomSort.controller.Main', { /** * Prepare combo tree if selected category is linked to another category. * - * @param [integer] linkedCategoryId - * @returns [boolean] + * @param { integer } linkedCategoryId + * @returns { boolean } */ prepareTreeCombo: function (linkedCategoryId) { var me = this, - comboBox = me.getArticleView().categoryTreeCombo, + comboBox = me.getProductView().categoryTreeCombo, treePanel = comboBox.getPicker(), treeStore = treePanel.getStore(); - //clear tree selection if it is not linked + // clear tree selection if it is not linked if (!linkedCategoryId) { treePanel.collapseAll(); comboBox.setRawValue(); } - //helper function for selecting tree node + // helper function for selecting tree node var selectNode = function () { var node = treeStore.getNodeById(linkedCategoryId); if (node) { @@ -172,39 +172,39 @@ Ext.define('Shopware.apps.CustomSort.controller.Main', { } }; - //load whole category tree + // load whole category tree treeStore.on('load', function () { treePanel.expandAll(); treePanel.collapseAll(); - //select tree node on first load + // select tree node on first load selectNode(); }); - //select tree node on change + // select tree node on change selectNode(); return true; }, /** * Event listener function of the sort combobox. - * Fired when the user change sorting of articles in article view panel. + * Fired when the user change sorting of products in product view panel. * - * @param [Ext.data.Model] The selected record + * @param { Ext.data.Model } record The selected record */ onSortChange: function (record) { var me = this, - list = me.getArticleList(); + list = me.getProductList(); list.setLoading(true); me.onSaveSettings(); - me.subApplication.articleStore.getProxy().extraParams = { + me.subApplication.productStore.getProxy().extraParams = { categoryId: me.categoryId, sortBy: record }; - me.subApplication.articleStore.load({ + me.subApplication.productStore.load({ callback: function () { list.setLoading(false); } @@ -212,13 +212,13 @@ Ext.define('Shopware.apps.CustomSort.controller.Main', { }, /** - * Event listener function of the article view panel. + * Event listener function of the product view panel. * Fired when the user change default display or linked category */ onSaveSettings: function () { var me = this, - grid = me.getArticleView(), - list = me.getArticleList(), + grid = me.getProductView(), + list = me.getProductList(), form = grid.getForm(), record = form.getRecord(), values = form.getValues(); @@ -245,84 +245,84 @@ Ext.define('Shopware.apps.CustomSort.controller.Main', { /** * - * @param [Ext.data.Store] The article store + * @param { Ext.data.Store } productStore */ - onMoveToStart: function (articleStore) { - if (!articleStore instanceof Ext.data.Store) { + onMoveToStart: function (productStore) { + if (!(productStore instanceof Ext.data.Store)) { return false; } var me = this, - list = me.getArticleList(), + list = me.getProductList(), selectedRecords = list.dataView.getSelectionModel().getSelection(), oldPosition = null; list.setLoading(true); selectedRecords.forEach(function (record, index) { - if (!record instanceof Ext.data.Model) { + if (!(record instanceof Ext.data.Model)) { return false; } - oldPosition = articleStore.indexOf(record) + ((articleStore.currentPage - 1) * articleStore.pageSize); + oldPosition = productStore.indexOf(record) + ((productStore.currentPage - 1) * productStore.pageSize); record.set('position', index); record.set('oldPosition', oldPosition); record.set('pin', 1); }); - me.onSaveArticles(articleStore); + me.onSaveProducts(productStore); return true; }, /** - * Event listener function of the article list. + * Event listener function of the product list. * Fired when the user click on "move to end" fast move icon. * - * @param [Ext.data.Store] The article store + * @param { Ext.data.Store } productStore */ - onMoveToEnd: function (articleStore) { - if (!articleStore instanceof Ext.data.Store) { + onMoveToEnd: function (productStore) { + if (!(productStore instanceof Ext.data.Store)) { return false; } var me = this, - list = me.getArticleList(), + list = me.getProductList(), selectedRecords = list.dataView.getSelectionModel().getSelection(), oldPosition = null, - total = articleStore.getTotalCount() - 1; + total = productStore.getTotalCount() - 1; list.setLoading(true); selectedRecords.forEach(function (record, index) { - if (!record instanceof Ext.data.Model) { + if (!(record instanceof Ext.data.Model)) { return false; } - oldPosition = articleStore.indexOf(record) + ((articleStore.currentPage - 1) * articleStore.pageSize); + oldPosition = productStore.indexOf(record) + ((productStore.currentPage - 1) * productStore.pageSize); record.set('position', total - index); record.set('oldPosition', oldPosition); record.set('pin', 1); }); - me.onSaveArticles(articleStore); + me.onSaveProducts(productStore); return true; }, /** - * Event listener function of the article list. + * Event listener function of the product list. * Fired when the user click on "move to prev page" fast move icon. * - * @param [Ext.data.Store] The article store + * @param { Ext.data.Store } productStore */ - onMoveToPrevPage: function (articleStore) { - if (!articleStore instanceof Ext.data.Store) { + onMoveToPrevPage: function (productStore) { + if (!(productStore instanceof Ext.data.Store)) { return false; } var me = this, - list = me.getArticleList(), + list = me.getProductList(), selectedRecords = list.dataView.getSelectionModel().getSelection(), oldPosition = null, position = null, @@ -331,20 +331,20 @@ Ext.define('Shopware.apps.CustomSort.controller.Main', { list.setLoading(true); selectedRecords.forEach(function (record) { - if (!record instanceof Ext.data.Model) { + if (!(record instanceof Ext.data.Model)) { return false; } - if (articleStore.allProductsPageSize && articleStore.indexOf(record) < articleStore.allProductsPageSize) { + if (productStore.allProductsPageSize && productStore.indexOf(record) < productStore.allProductsPageSize) { return true; } - if (articleStore.allProductsPageSize) { //all products mode - oldPosition = articleStore.indexOf(record); - position = oldPosition - articleStore.allProductsPageSize; + if (productStore.allProductsPageSize) { // all products mode + oldPosition = productStore.indexOf(record); + position = oldPosition - productStore.allProductsPageSize; } else { - oldPosition = articleStore.indexOf(record) + ((articleStore.currentPage - 1) * articleStore.pageSize); - position = ((articleStore.currentPage - 1) * articleStore.pageSize) - count; + oldPosition = productStore.indexOf(record) + ((productStore.currentPage - 1) * productStore.pageSize); + position = ((productStore.currentPage - 1) * productStore.pageSize) - count; } record.set('oldPosition', oldPosition); @@ -353,24 +353,24 @@ Ext.define('Shopware.apps.CustomSort.controller.Main', { count--; }); - me.onSaveArticles(articleStore); + me.onSaveProducts(productStore); return true; }, /** - * Event listener function of the article list. + * Event listener function of the product list. * Fired when the user click on "move to next page" fast move icon. * - * @param [Ext.data.Store] The article store + * @param { Ext.data.Store } productStore */ - onMoveToNextPage: function (articleStore) { - if (!articleStore instanceof Ext.data.Store) { + onMoveToNextPage: function (productStore) { + if (!(productStore instanceof Ext.data.Store)) { return false; } var me = this, - list = me.getArticleList(), + list = me.getProductList(), selectedRecords = list.dataView.getSelectionModel().getSelection(), oldPosition = null, position = null; @@ -378,20 +378,20 @@ Ext.define('Shopware.apps.CustomSort.controller.Main', { list.setLoading(true); selectedRecords.forEach(function (record, index) { - if (!record instanceof Ext.data.Model) { + if (!(record instanceof Ext.data.Model)) { return false; } - if (articleStore.allProductsPageSize && articleStore.indexOf(record) >= (articleStore.totalCount - articleStore.allProductsPageSize)) { + if (productStore.allProductsPageSize && productStore.indexOf(record) >= (productStore.totalCount - productStore.allProductsPageSize)) { return true; } - if (articleStore.allProductsPageSize) { //all products mode - oldPosition = articleStore.indexOf(record); - position = oldPosition + articleStore.allProductsPageSize; + if (productStore.allProductsPageSize) { // all products mode + oldPosition = productStore.indexOf(record); + position = oldPosition + productStore.allProductsPageSize; } else { - oldPosition = articleStore.indexOf(record) + ((articleStore.currentPage - 1) * articleStore.pageSize); - position = (articleStore.currentPage * articleStore.pageSize) + index; + oldPosition = productStore.indexOf(record) + ((productStore.currentPage - 1) * productStore.pageSize); + position = (productStore.currentPage * productStore.pageSize) + index; } record.set('oldPosition', oldPosition); @@ -399,38 +399,37 @@ Ext.define('Shopware.apps.CustomSort.controller.Main', { record.set('pin', 1); }); - me.onSaveArticles(articleStore); + me.onSaveProducts(productStore); return true; }, /** - * Event listener function of the article view list. - * Fired when the user move selected articles. + * Event listener function of the product view list. + * Fired when the user move selected products. * - * @param [Ext.data.Store] The article store - * @param [Array] Array with selected article in article view list - * @param [Shopware.apps.Article.model.Article] The target record, on which the dragged record dropped + * @param { Ext.data.Store } productStore + * @param { Array } productModel Array with selected product in product view list + * @param { Shopware.apps.Article.model.Article} targetRecord The target record, on which the dragged record dropped */ - onArticleMove: function (articleStore, articleModel, targetRecord) { + onProductMove: function (productStore, productModel, targetRecord) { var me = this, - list = me.getArticleList(), - startPosition = (articleStore.currentPage - 1) * articleStore.pageSize; + list = me.getProductList(), + startPosition = (productStore.currentPage - 1) * productStore.pageSize; - if (!articleStore instanceof Ext.data.Store - || !targetRecord instanceof Ext.data.Model) { + if (!(productStore instanceof Ext.data.Store) || + !(targetRecord instanceof Ext.data.Model)) { return false; } list.setLoading(true); - var count = articleModel.length; + var count = productModel.length; if (count > 0) { - - var positionIndex = articleStore.indexOf(targetRecord) + startPosition; + var positionIndex = productStore.indexOf(targetRecord) + startPosition; var forward = [], backward = [], temp = 0; - Ext.each(articleModel, function (record) { - var oldPosition = articleStore.indexOf(record) + startPosition; + Ext.each(productModel, function (record) { + var oldPosition = productStore.indexOf(record) + startPosition; if (oldPosition < positionIndex) { forward.push(record); } @@ -440,14 +439,14 @@ Ext.define('Shopware.apps.CustomSort.controller.Main', { } }); - Ext.each(articleModel, function (record, index) { - if (!record instanceof Ext.data.Model) { + Ext.each(productModel, function (record, index) { + if (!(record instanceof Ext.data.Model)) { return; } var oldPosition, position; - oldPosition = articleStore.indexOf(record) + startPosition; + oldPosition = productStore.indexOf(record) + startPosition; if (oldPosition < positionIndex) { position = positionIndex - forward.length + index; } @@ -461,44 +460,42 @@ Ext.define('Shopware.apps.CustomSort.controller.Main', { record.set('oldPosition', oldPosition); record.set('pin', 1); }); - } - me.onSaveArticles(articleStore); + me.onSaveProducts(productStore); }, /** - * Event listener function of the article view list. - * Fired when the user move article in view list or use fast move buttons. + * Event listener function of the product view list. + * Fired when the user move product in view list or use fast move buttons. * - * @param [Ext.data.Store] The article store + * @param { Ext.data.Store } productStore */ - onSaveArticles: function (articleStore) { - articleStore.update(); + onSaveProducts: function (productStore) { + productStore.update(); }, /** - * Event listener function of the article view list. - * Fired when the user click on unpin icon on article. + * Event listener function of the product view list. + * Fired when the user click on unpin icon on product. * - * @param [Ext.data.Store] The article store - * @param [Ext.data.Model] The selected record - * @param [boolean] + * @param { Ext.data.Store } productStore + * @param { Ext.data.Model } record The selected record */ - onUnpin: function (articleStore, record) { + onUnpin: function (productStore, record) { var me = this, - list = me.getArticleList(); + list = me.getProductList(); - if (!articleStore instanceof Ext.data.Store || !record instanceof Ext.data.Model) { + if (!(productStore instanceof Ext.data.Store) || !(record instanceof Ext.data.Model)) { return false; } list.setLoading(true); - var store = articleStore; + var store = productStore; record.set('pin', 0); - articleStore.remove(record); - articleStore.sync({ + productStore.remove(record); + productStore.sync({ success: function () { Shopware.Notification.createGrowlMessage('{s name=main/success/title}Success{/s}', '{s name=main/success/message}Successfully applied changes{/s}'); }, @@ -512,30 +509,29 @@ Ext.define('Shopware.apps.CustomSort.controller.Main', { }, /** - * Event listener function of the article view list. - * Fired when the user click on remove icon on article. + * Event listener function of the product view list. + * Fired when the user click on remove icon on product. * - * @param [Ext.data.Store] The article store - * @param [Ext.data.Model] The selected record - * @param [boolean] + * @param { Ext.data.Store } productStore + * @param { Ext.data.Model } record The selected record */ - onRemove: function (articleStore, record) { + onRemove: function (productStore, record) { var me = this, - list = me.getArticleList(); + list = me.getProductList(); - if (!articleStore instanceof Ext.data.Store || !record instanceof Ext.data.Model) { + if (!(productStore instanceof Ext.data.Store) || !(record instanceof Ext.data.Model)) { return false; } list.setLoading(true); - var store = articleStore; + var store = productStore; Ext.Ajax.request({ url: '{url controller="CustomSort" action="removeProduct"}', method: 'POST', params: { - articleId: record.get('articleID'), + productId: record.get('productId'), categoryId: me.categoryId }, success: function () { @@ -550,4 +546,4 @@ Ext.define('Shopware.apps.CustomSort.controller.Main', { return true; } }); -//{/block} \ No newline at end of file +// {/block} diff --git a/Views/backend/custom_sort/header.tpl b/Views/backend/custom_sort/header.tpl index 6c081a5..5e0a805 100644 --- a/Views/backend/custom_sort/header.tpl +++ b/Views/backend/custom_sort/header.tpl @@ -1,3 +1,4 @@ -{block name="backend/base/header/css" append} +{block name="backend/base/header/css"} + {$smarty.block.parent} -{/block} \ No newline at end of file +{/block} diff --git a/Views/backend/custom_sort/model/article.js b/Views/backend/custom_sort/model/product.js similarity index 77% rename from Views/backend/custom_sort/model/article.js rename to Views/backend/custom_sort/model/product.js index b82e0ee..5c4eba9 100644 --- a/Views/backend/custom_sort/model/article.js +++ b/Views/backend/custom_sort/model/product.js @@ -1,5 +1,5 @@ -//{block name="backend/custom_sort/model/article"} -Ext.define('Shopware.apps.CustomSort.model.Article', { +// {block name="backend/custom_sort/model/product"} +Ext.define('Shopware.apps.CustomSort.model.Product', { /** * Extend for the standard ExtJS 4 @@ -12,8 +12,8 @@ Ext.define('Shopware.apps.CustomSort.model.Article', { * @array */ fields: [ - //{block name="backend/custom_sort/model/article/fields"}{/block} - { name: 'articleID', type: 'int', useNull: true }, + // {block name="backend/custom_sort/model/product/fields"}{/block} + { name: 'productId', type: 'int', useNull: true }, { name: 'positionId', type: 'int', useNull: true }, { name: 'name', type: 'string' }, { name: 'position', type: 'int' }, @@ -39,7 +39,7 @@ Ext.define('Shopware.apps.CustomSort.model.Article', { * * @int */ - idProperty: 'articleID', + idProperty: 'productId', /** * Configure the data communication @@ -58,10 +58,10 @@ Ext.define('Shopware.apps.CustomSort.model.Article', { * @object */ api: { - read: '{url controller="CustomSort" action="getArticleList"}', - update: '{url controller="CustomSort" action="saveArticleList"}', - create: '{url controller="CustomSort" action="saveArticleList"}', - destroy: '{url controller="CustomSort" action="unpinArticle"}' + read: '{url controller="CustomSort" action="getProductList"}', + update: '{url controller="CustomSort" action="saveProductList"}', + create: '{url controller="CustomSort" action="saveProductList"}', + destroy: '{url controller="CustomSort" action="unpinProduct"}' }, /** @@ -84,4 +84,4 @@ Ext.define('Shopware.apps.CustomSort.model.Article', { } } }); -//{/block} \ No newline at end of file +// {/block} diff --git a/Views/backend/custom_sort/model/settings.js b/Views/backend/custom_sort/model/settings.js index 8944775..106ae95 100644 --- a/Views/backend/custom_sort/model/settings.js +++ b/Views/backend/custom_sort/model/settings.js @@ -1,4 +1,4 @@ -//{block name="backend/custom_sort/model/settings"} +// {block name="backend/custom_sort/model/settings"} Ext.define('Shopware.apps.CustomSort.model.Settings', { /** @@ -12,7 +12,7 @@ Ext.define('Shopware.apps.CustomSort.model.Settings', { * @array */ fields: [ - //{block name="backend/custom_sort/model/settings/fields"}{/block} + // {block name="backend/custom_sort/model/settings/fields"}{/block} { name: 'id', type: 'int', useNull: true }, { name: 'defaultSort', type: 'int' }, { name: 'categoryLink', type: 'int' }, @@ -51,4 +51,4 @@ Ext.define('Shopware.apps.CustomSort.model.Settings', { } } }); -//{/block} \ No newline at end of file +// {/block} diff --git a/Views/backend/custom_sort/store/article.js b/Views/backend/custom_sort/store/product.js similarity index 71% rename from Views/backend/custom_sort/store/article.js rename to Views/backend/custom_sort/store/product.js index 32e5acc..54e2556 100644 --- a/Views/backend/custom_sort/store/article.js +++ b/Views/backend/custom_sort/store/product.js @@ -1,5 +1,5 @@ -//{block name="backend/custom_sort/store/article"} -Ext.define('Shopware.apps.CustomSort.store.Article', { +// {block name="backend/custom_sort/store/product"} +Ext.define('Shopware.apps.CustomSort.store.Product', { /** * Extend for the standard ExtJS 4 @@ -17,7 +17,7 @@ Ext.define('Shopware.apps.CustomSort.store.Article', { * Define the used model for this store * @string */ - model: 'Shopware.apps.CustomSort.model.Article', + model: 'Shopware.apps.CustomSort.model.Product', /** * Page range of the store @@ -31,4 +31,4 @@ Ext.define('Shopware.apps.CustomSort.store.Article', { } }); -//{/block} \ No newline at end of file +// {/block} diff --git a/Views/backend/custom_sort/store/settings.js b/Views/backend/custom_sort/store/settings.js index b557ab8..520ec78 100644 --- a/Views/backend/custom_sort/store/settings.js +++ b/Views/backend/custom_sort/store/settings.js @@ -1,4 +1,4 @@ -//{block name="backend/custom_sort/store/settings"} +// {block name="backend/custom_sort/store/settings"} Ext.define('Shopware.apps.CustomSort.store.Settings', { /** @@ -20,4 +20,4 @@ Ext.define('Shopware.apps.CustomSort.store.Settings', { model: 'Shopware.apps.CustomSort.model.Settings' }); -//{/block} \ No newline at end of file +// {/block} diff --git a/Views/backend/custom_sort/store/tree.js b/Views/backend/custom_sort/store/tree.js index bcb63d8..9c19c01 100644 --- a/Views/backend/custom_sort/store/tree.js +++ b/Views/backend/custom_sort/store/tree.js @@ -1,4 +1,4 @@ -//{block name="backend/custom_sort/store/tree"} +// {block name="backend/custom_sort/store/tree"} Ext.define('Shopware.apps.CustomSort.store.Tree', { /** @@ -51,4 +51,4 @@ Ext.define('Shopware.apps.CustomSort.store.Tree', { } } }); -//{/block} +// {/block} diff --git a/Views/backend/custom_sort/view/category/tree.js b/Views/backend/custom_sort/view/category/tree.js index 9ae5eb6..a30c46b 100644 --- a/Views/backend/custom_sort/view/category/tree.js +++ b/Views/backend/custom_sort/view/category/tree.js @@ -1,5 +1,5 @@ -//{namespace name="backend/custom_sort/view/main"} -//{block name="backend/custom_sort/view/category/tree"} +// {namespace name="backend/custom_sort/view/main"} +// {block name="backend/custom_sort/view/category/tree"} Ext.define('Shopware.apps.CustomSort.view.category.Tree', { /** @@ -47,16 +47,12 @@ Ext.define('Shopware.apps.CustomSort.view.category.Tree', { * @return [array] columns - generated columns */ createColumns: function () { - var columns = [ - { - xtype: 'treecolumn', - sortable: false, - flex: 1, - dataIndex: 'text' - } - ]; - - return columns; + return [{ + xtype: 'treecolumn', + sortable: false, + flex: 1, + dataIndex: 'text' + }]; } }); -//{/block} +// {/block} diff --git a/Views/backend/custom_sort/view/main/window.js b/Views/backend/custom_sort/view/main/window.js index b04d79d..37a1c52 100644 --- a/Views/backend/custom_sort/view/main/window.js +++ b/Views/backend/custom_sort/view/main/window.js @@ -1,5 +1,5 @@ -//{namespace name="backend/custom_sort/view/main"} -//{block name="backend/custom_sort/view/main/main"} +// {namespace name="backend/custom_sort/view/main"} +// {block name="backend/custom_sort/view/main/main"} Ext.define('Shopware.apps.CustomSort.view.main.Window', { extend: 'Enlight.app.Window', @@ -46,14 +46,14 @@ Ext.define('Shopware.apps.CustomSort.view.main.Window', { flex: 0.25, store: me.treeStore }, { - xtype: 'sort-articles-view', + xtype: 'sort-products-view', region: 'center', store: me.categorySettings, treeStore: me.treeStore, - articleStore: me.articleStore + productStore: me.productStore } ]; } }); -//{/block} \ No newline at end of file +// {/block} diff --git a/Views/backend/custom_sort/view/article/list.js b/Views/backend/custom_sort/view/product/list.js similarity index 83% rename from Views/backend/custom_sort/view/article/list.js rename to Views/backend/custom_sort/view/product/list.js index 0d51dc7..04970b9 100644 --- a/Views/backend/custom_sort/view/article/list.js +++ b/Views/backend/custom_sort/view/product/list.js @@ -1,9 +1,9 @@ -//{namespace name="backend/custom_sort/main"} -//{block name="backend/custom_sort/view/article/list"} -Ext.define('Shopware.apps.CustomSort.view.article.List', { +// {namespace name="backend/custom_sort/main"} +// {block name="backend/custom_sort/view/product/list"} +Ext.define('Shopware.apps.CustomSort.view.product.List', { /** - * Define that the article list is an extension of the Ext.panel.Panel + * Define that the product list is an extension of the Ext.panel.Panel * @string */ extend: 'Ext.panel.Panel', @@ -12,7 +12,7 @@ Ext.define('Shopware.apps.CustomSort.view.article.List', { * Register the alias for this class. * @string */ - alias: 'widget.sort-articles-list', + alias: 'widget.sort-products-list', /** * Set no border for the window @@ -32,7 +32,7 @@ Ext.define('Shopware.apps.CustomSort.view.article.List', { * Set css class for this component * @string */ - cls: Ext.baseCSSPrefix + 'article-sort', + cls: Ext.baseCSSPrefix + 'product-sort', /** * The initComponent template method is an important initialization step for a Component. @@ -50,37 +50,37 @@ Ext.define('Shopware.apps.CustomSort.view.article.List', { me.viewConfig = { plugins: { ptype: 'gridviewdragdrop', - ddGroup: 'Article', + ddGroup: 'Product', enableDrop: true } }; - me.items = [me.createArticleView()]; + me.items = [me.createProductView()]; me.dockedItems = [me.getPagingBar()]; me.callParent(arguments); }, /** - * Creates the article listing based on an Ext.view.View (know as DataView) - * and binds the "Article"-store to it + * Creates the product listing based on an Ext.view.View (know as DataView) + * and binds the "Product"-store to it * * @return [object] this.dataView - created Ext.view.View */ - createArticleView: function () { + createProductView: function () { var me = this; me.dataView = Ext.create('Ext.view.View', { disabled: false, itemSelector: '.thumb', name: 'image-listing', - emptyText: '
{s name=list/no_articles}No articles found{/s}
', + emptyText: '
{s name=list/no_products}No products found{/s}
', multiSelect: true, store: me.store, loadMask: false, - tpl: me.createArticleViewTemplate(), + tpl: me.createProductViewTemplate(), listeners: { - itemclick: function (view, record, item, idx, event, opts) { + itemclick: function (view, record, item, idx, event) { if (event.target.classList.contains('remove')) { me.fireEvent('remove', me.store, record); } @@ -100,11 +100,11 @@ Ext.define('Shopware.apps.CustomSort.view.article.List', { }, /** - * Creates the template for the article view panel + * Creates the template for the product view panel * - * @return [object] generated Ext.XTemplate + * @return { Ext.XTemplate } generated Ext.XTemplate */ - createArticleViewTemplate: function () { + createProductViewTemplate: function () { var me = this; return new Ext.XTemplate( '{literal}', @@ -115,7 +115,7 @@ Ext.define('Shopware.apps.CustomSort.view.article.List', { '', '', '
', - '' , + '', '
', '{[Ext.util.Format.ellipsis(values.name, 50)]}', '', @@ -130,20 +130,20 @@ Ext.define('Shopware.apps.CustomSort.view.article.List', { '', '
{/literal}', { - //Add class if current product is first position in store list - startPage: function (article, index) { + // Add class if current product is first position in store list + startPage: function (product, index) { var store = me.store, view = me.dataView, position, record = view.getStore().getAt((index - 1)); position = store.indexOf(record) + ((store.currentPage - 1) * store.pageSize); - if (position == 0) { + if (position === 0) { return ' disabled'; } }, - //Add class if current product is on first page in store list + // Add class if current product is on first page in store list prevPage: function (index) { var store = me.store, pageSize = store.allProductsPageSize; @@ -155,7 +155,7 @@ Ext.define('Shopware.apps.CustomSort.view.article.List', { } }, - //Add class if current product is on last page in store list + // Add class if current product is on last page in store list nextPage: function (index) { var store = me.store, lastPage, @@ -169,8 +169,8 @@ Ext.define('Shopware.apps.CustomSort.view.article.List', { } }, - //Add class if current product is on last position in store list - endPage: function (article, index) { + // Add class if current product is on last position in store list + endPage: function (product, index) { var store = me.store, view = me.dataView, position, @@ -192,7 +192,7 @@ Ext.define('Shopware.apps.CustomSort.view.article.List', { var me = this; var el = me.el; - //Trigger event when "move to start" action is clicked + // Trigger event when "move to start" action is clicked el.on('click', function (event, target) { if (target.classList.contains('disabled')) { return false; @@ -203,7 +203,7 @@ Ext.define('Shopware.apps.CustomSort.view.article.List', { delegate: 'span.first' }); - //Trigger event when "move to end" action is clicked + // Trigger event when "move to end" action is clicked el.on('click', function (event, target) { if (target.classList.contains('disabled')) { return false; @@ -214,7 +214,7 @@ Ext.define('Shopware.apps.CustomSort.view.article.List', { delegate: 'span.last' }); - //Trigger event when "move to prev page" action is clicked + // Trigger event when "move to prev page" action is clicked el.on('click', function (event, target) { if (target.classList.contains('disabled')) { return false; @@ -225,7 +225,7 @@ Ext.define('Shopware.apps.CustomSort.view.article.List', { delegate: 'span.prev' }); - //Trigger event when "move to next page" action is clicked + // Trigger event when "move to next page" action is clicked el.on('click', function (event, target) { if (target.classList.contains('disabled')) { return false; @@ -279,7 +279,7 @@ Ext.define('Shopware.apps.CustomSort.view.article.List', { store: me.store }); - //Fire event when user uses paging toolbar + // Fire event when user uses paging toolbar pagingBar.on('beforechange', function () { me.fireEvent('pageChange'); }); @@ -297,9 +297,8 @@ Ext.define('Shopware.apps.CustomSort.view.article.List', { * a entry in the "number of products"-combo box. * * @event select - * @param [object] combo - Ext.form.field.ComboBox - * @param [array] records - Array of selected entries - * @return void + * @param { object } combo - Ext.form.field.ComboBox + * @param { array } records - Array of selected entries */ onPageSizeChange: function (combo, records) { var record = records[0], @@ -325,7 +324,7 @@ Ext.define('Shopware.apps.CustomSort.view.article.List', { me.dataView.on('afterrender', function (v) { var selModel = v.getSelectionModel(); me.dataView.dragZone = new Ext.dd.DragZone(v.getEl(), { - ddGroup: 'Article', + ddGroup: 'Product', getDragData: function (e) { var sourceEl = e.getTarget(v.itemSelector, 10); if (sourceEl) { @@ -340,16 +339,14 @@ Ext.define('Shopware.apps.CustomSort.view.article.List', { var d = sourceEl.cloneNode(true); d.id = Ext.id(); - var result = { + return { ddel: d, sourceEl: sourceEl, repairXY: Ext.fly(sourceEl).getXY(), sourceStore: v.store, draggedRecord: v.getRecord(sourceEl), - articleModels: selected + productModels: selected }; - - return result; } }, getRepairXY: function () { @@ -358,7 +355,7 @@ Ext.define('Shopware.apps.CustomSort.view.article.List', { }); me.dataView.dropZone = new Ext.dd.DropZone(me.dataView.getEl(), { - ddGroup: 'Article', + ddGroup: 'Product', getTargetFromEvent: function (e) { return e.getTarget(me.dataView.itemSelector); }, @@ -370,15 +367,15 @@ Ext.define('Shopware.apps.CustomSort.view.article.List', { } }, - onNodeOut: function (target, dd, e, data) { + onNodeOut: function (target) { Ext.fly(target).removeCls(me.dragOverCls); }, onNodeDrop: function (target, dd, e, data) { var draggedRecord = me.dataView.getRecord(target); - var articleModels = data.articleModels; + var productModels = data.productModels; - me.fireEvent('articleMove', me.store, articleModels, draggedRecord) + me.fireEvent('productMove', me.store, productModels, draggedRecord); } }); @@ -386,4 +383,4 @@ Ext.define('Shopware.apps.CustomSort.view.article.List', { }); } }); -//{/block} \ No newline at end of file +// {/block} diff --git a/Views/backend/custom_sort/view/article/view.js b/Views/backend/custom_sort/view/product/view.js similarity index 89% rename from Views/backend/custom_sort/view/article/view.js rename to Views/backend/custom_sort/view/product/view.js index d974564..e91fc54 100644 --- a/Views/backend/custom_sort/view/article/view.js +++ b/Views/backend/custom_sort/view/product/view.js @@ -1,9 +1,9 @@ -//{namespace name="backend/custom_sort/main"} -//{block name="backend/custom_sort/view/article/view"} -Ext.define('Shopware.apps.CustomSort.view.article.View', { +// {namespace name="backend/custom_sort/main"} +// {block name="backend/custom_sort/view/product/view"} +Ext.define('Shopware.apps.CustomSort.view.product.View', { /** - * Define that the article view is an extension of the Ext.form.Panel + * Define that the product view is an extension of the Ext.form.Panel * @string */ extend: 'Ext.form.Panel', @@ -12,7 +12,7 @@ Ext.define('Shopware.apps.CustomSort.view.article.View', { * Register the alias for this class. * @string */ - alias: 'widget.sort-articles-view', + alias: 'widget.sort-products-view', /** * The Ext.container.Container.layout for the fieldset's immediate child items. @@ -38,8 +38,8 @@ Ext.define('Shopware.apps.CustomSort.view.article.View', { me.tbar = me.createActionToolbar(); me.items = [ { - xtype: 'sort-articles-list', - store: me.articleStore + xtype: 'sort-products-list', + store: me.productStore } ]; @@ -54,7 +54,7 @@ Ext.define('Shopware.apps.CustomSort.view.article.View', { createActionToolbar: function () { var me = this; - //Create checkbox for displaying custom sort by default + // Create checkbox for displaying custom sort by default me.defaultSort = Ext.create('Ext.form.field.Checkbox', { boxLabel: '{s name=view/default_sort}Show this sort order by default{/s}', cls: 'swag-custom-sort-bold-checkbox', @@ -70,7 +70,7 @@ Ext.define('Shopware.apps.CustomSort.view.article.View', { } }); - //Create combo tree in which you can link current category to another + // Create combo tree in which you can link current category to another me.categoryTreeCombo = Ext.create('Shopware.form.field.ComboTree', { valueField: 'id', displayField: 'name', @@ -98,7 +98,7 @@ Ext.define('Shopware.apps.CustomSort.view.article.View', { } }); - //Create combo with base sorting + // Create combo with base sorting me.sorting = Ext.create('Ext.form.field.ComboBox', { editable: false, fieldLabel: '{s name=view/sorting}Base sorting{/s}', @@ -138,4 +138,4 @@ Ext.define('Shopware.apps.CustomSort.view.article.View', { ]; } }); -//{/block} \ No newline at end of file +// {/block} diff --git a/plugin.json b/plugin.json index e992991..17cd731 100644 --- a/plugin.json +++ b/plugin.json @@ -8,7 +8,7 @@ "link": "http://store.shopware.com", "author": "Shopware AG", - "currentVersion": "1.0.4", + "currentVersion": "2.0.0", "compatibility": { "minimumVersion": "5.0.0",