Completed
Pull Request — master (#392)
by Jonas
03:25
created

CategoryResolver::deleteEmptyCategory()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 21
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 12
nc 2
nop 1
dl 0
loc 21
rs 9.3142
c 0
b 0
f 0
1
<?php
2
/**
3
 * (c) shopware AG <[email protected]>
4
 * For the full copyright and license information, please view the LICENSE
5
 * file that was distributed with this source code.
6
 */
7
8
namespace ShopwarePlugins\Connect\Components;
9
10
use Shopware\CustomModels\Connect\ProductToRemoteCategory;
11
use Shopware\CustomModels\Connect\RemoteCategory;
12
use Shopware\CustomModels\Connect\RemoteCategoryRepository;
13
use Shopware\Components\Model\ModelManager;
14
use Shopware\CustomModels\Connect\ProductToRemoteCategoryRepository;
15
use Shopware\Models\Category\Repository as CategoryRepository;
16
use Shopware\Models\Category\Category;
17
18
abstract class CategoryResolver
19
{
20
    /**
21
     * @var ModelManager
22
     */
23
    protected $manager;
24
25
    /**
26
     * @var \Shopware\CustomModels\Connect\RemoteCategoryRepository
27
     */
28
    protected $remoteCategoryRepository;
29
30
    /**
31
     * @var \Shopware\CustomModels\Connect\ProductToRemoteCategoryRepository
32
     */
33
    protected $productToRemoteCategoryRepository;
34
35
    /**
36
     * @var \Shopware\Models\Category\Repository
37
     */
38
    protected $categoryRepository;
39
40
    public function __construct(
41
        ModelManager $manager,
42
        RemoteCategoryRepository $remoteCategoryRepository,
43
        ProductToRemoteCategoryRepository $productToRemoteCategoryRepository,
44
        CategoryRepository $categoryRepository
45
    ) {
46
        $this->manager = $manager;
47
        $this->remoteCategoryRepository = $remoteCategoryRepository;
48
        $this->productToRemoteCategoryRepository = $productToRemoteCategoryRepository;
49
        $this->categoryRepository = $categoryRepository;
50
    }
51
52
    /**
53
     * Returns array with category entities
54
     * if they don't exist will be created
55
     *
56
     * @param array $categories
57
     * @return \Shopware\Models\Category\Category[]
58
     */
59
    abstract public function resolve(array $categories);
60
61
    /**
62
     * Generates categories tree by given array of categories
63
     *
64
     * @param array $categories
65
     * @param string $idPrefix
66
     * @return array
67
     */
68
    abstract public function generateTree(array $categories, $idPrefix = '');
69
70
    /**
71
     * Stores raw Shopware Connect categories
72
     *
73
     * @param array $categories
74
     * @param int $articleId
75
     * @return void
76
     */
77
    public function storeRemoteCategories(array $categories, $articleId)
78
    {
79
        $remoteCategories = [];
80
        foreach ($categories as $categoryKey => $category) {
81
            $remoteCategory = $this->remoteCategoryRepository->findOneBy(['categoryKey' => $categoryKey]);
82
            if (!$remoteCategory) {
83
                $remoteCategory = new RemoteCategory();
84
                $remoteCategory->setCategoryKey($categoryKey);
85
            }
86
            $remoteCategory->setLabel($category);
87
            $this->manager->persist($remoteCategory);
88
            $remoteCategories[] = $remoteCategory;
89
        }
90
91
        $this->manager->flush();
92
93
        $this->removeProductsFromNotAssignedRemoteCategories($remoteCategories, $articleId);
94
        $this->addProductToRemoteCategory($remoteCategories, $articleId);
95
96
        $this->manager->flush();
97
    }
98
99
    /**
100
     * @param RemoteCategory[] $remoteCategories
101
     * @param $articleId
102
     */
103
    private function addProductToRemoteCategory(array $remoteCategories, $articleId)
104
    {
105
        $productToCategories = $this->productToRemoteCategoryRepository->getRemoteCategoryIds($articleId);
106
        /** @var $remoteCategory \Shopware\CustomModels\Connect\RemoteCategory */
107
        foreach ($remoteCategories as $remoteCategory) {
108
            if (!in_array($remoteCategory->getId(), $productToCategories)) {
109
                $productToCategory = new ProductToRemoteCategory();
110
                $productToCategory->setArticleId($articleId);
111
                $productToCategory->setConnectCategory($remoteCategory);
112
                $this->manager->persist($productToCategory);
113
            }
114
        }
115
    }
116
117
    /**
118
     * @param \Shopware\CustomModels\Connect\RemoteCategory[] $assignedCategories
119
     * @param int $articleId
120
     */
121
    private function removeProductsFromNotAssignedRemoteCategories(array $assignedCategories, $articleId)
122
    {
123
        $currentProductCategoryIds = $this->productToRemoteCategoryRepository->getRemoteCategoryIds($articleId);
124
125
        $assignedCategoryIds = array_map(function (RemoteCategory $assignedCategory) {
126
            $assignedCategory->getId();
0 ignored issues
show
Unused Code introduced by
The call to the method Shopware\CustomModels\Co...RemoteCategory::getId() seems un-needed as the method has no side-effects.

PHP Analyzer performs a side-effects analysis of your code. A side-effect is basically anything that might be visible after the scope of the method is left.

Let’s take a look at an example:

class User
{
    private $email;

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }
}

If we look at the getEmail() method, we can see that it has no side-effect. Whether you call this method or not, no future calls to other methods are affected by this. As such code as the following is useless:

$user = new User();
$user->getEmail(); // This line could safely be removed as it has no effect.

On the hand, if we look at the setEmail(), this method _has_ side-effects. In the following case, we could not remove the method call:

$user = new User();
$user->setEmail('email@domain'); // This line has a side-effect (it changes an
                                 // instance variable).
Loading history...
127
        }, $assignedCategories);
128
129
        /** @var int $currentProductCategoryId */
130
        foreach ($currentProductCategoryIds as $currentProductCategoryId) {
131
            if (!in_array($currentProductCategoryId, $assignedCategoryIds)) {
132
                $this->productToRemoteCategoryRepository->deleteByConnectCategoryId($currentProductCategoryId, $articleId);
133
            }
134
        }
135
    }
136
137
    /**
138
     * Loop through category tree and fetch ids
139
     *
140
     * @param array $node
141
     * @param int $parentId
142
     * @param bool $returnOnlyLeafs
143
     * @param array $categories
144
     * @return array
145
     */
146
    public function convertTreeToKeys(array $node, $parentId, $returnOnlyLeafs = true, $categories = [])
147
    {
148
        foreach ($node as $category) {
149
            $categoryId = $this->checkAndCreateLocalCategory($category['name'], $category['categoryId'], $parentId);
150
151
            if ((!$returnOnlyLeafs) || (empty($category['children']))) {
152
                $categories[] = [
153
                    'categoryKey' => $categoryId,
154
                    'parentId' => $parentId,
155
                    'remoteCategory' => $category['categoryId']
156
                ];
157
            }
158
159
            if (!empty($category['children'])) {
160
                $categories = $this->convertTreeToKeys($category['children'], $categoryId, $returnOnlyLeafs, $categories);
161
            }
162
        }
163
164
        return $categories;
165
    }
166
167
    /**
168
     * @param string $categoryName
169
     * @param string $categoryKey
170
     * @param int $parentId
171
     * @return int
172
     */
173
    private function checkAndCreateLocalCategory($categoryName, $categoryKey, $parentId)
174
    {
175
        $id = $this->manager->getConnection()->fetchColumn('SELECT `id` 
176
            FROM `s_categories`
177
            WHERE `parent` = :parentId AND `description` = :description',
178
            [':parentId' => $parentId, ':description' => $categoryName]);
179
180
        if (!$id) {
181
            return $this->createLocalCategory($categoryName, $categoryKey, $parentId);
182
        }
183
184
        return $id;
185
    }
186
187
    /**
188
     * @param string $categoryName
189
     * @param string $categoryKey
190
     * @param int $parentId
191
     * @return int
192
     */
193
    public function createLocalCategory($categoryName, $categoryKey, $parentId)
194
    {
195
        $path = $this->manager->getConnection()->fetchColumn('SELECT `path` 
196
            FROM `s_categories`
197
            WHERE `id` = ?',
198
            [$parentId]);
199
        $suffix = ($path) ? "$parentId|" : "|$parentId|";
200
        $path = $path . $suffix;
201
        $now = new \DateTime('now');
202
        $timestamp = $now->format('Y-m-d H:i:s');
203
        $this->manager->getConnection()->executeQuery('INSERT INTO `s_categories` (`description`, `parent`, `path`, `active`, `added`, `changed`) 
204
            VALUES (?, ?, ?, 1, ?, ?)',
205
            [$categoryName, $parentId, $path, $timestamp, $timestamp]);
206
        $localCategoryId = $this->manager->getConnection()->fetchColumn('SELECT LAST_INSERT_ID()');
207
208
        $this->manager->getConnection()->executeQuery('INSERT INTO `s_categories_attributes` (`categoryID`, `connect_imported_category`) 
209
            VALUES (?, 1)',
210
            [$localCategoryId]);
211
212
        $remoteCategoryId = $this->manager->getConnection()->fetchColumn('SELECT `id` 
213
            FROM `s_plugin_connect_categories`
214
            WHERE `category_key` = ?',
215
            [$categoryKey]);
216
        $this->manager->getConnection()->executeQuery('INSERT INTO `s_plugin_connect_categories_to_local_categories` (`remote_category_id`, `local_category_id`) 
217
            VALUES (?, ?)',
218
            [$remoteCategoryId, $localCategoryId]);
219
220
        return $localCategoryId;
221
    }
222
}
223