Completed
Pull Request — master (#410)
by Jonas
03:01
created

CategoryResolver::resolve()

Size

Total Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
nc 1
dl 0
loc 1
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
use Shopware\Components\Model\CategoryDenormalization;
18
19
abstract class CategoryResolver
20
{
21
    /**
22
     * @var ModelManager
23
     */
24
    protected $manager;
25
26
    /**
27
     * @var \Shopware\CustomModels\Connect\RemoteCategoryRepository
28
     */
29
    protected $remoteCategoryRepository;
30
31
    /**
32
     * @var \Shopware\CustomModels\Connect\ProductToRemoteCategoryRepository
33
     */
34
    protected $productToRemoteCategoryRepository;
35
36
    /**
37
     * @var \Shopware\Models\Category\Repository
38
     */
39
    protected $categoryRepository;
40
41
    /**
42
     * @var CategoryDenormalization
43
     */
44
    private $categoryDenormalization;
45
46
    public function __construct(
47
        ModelManager $manager,
48
        RemoteCategoryRepository $remoteCategoryRepository,
49
        ProductToRemoteCategoryRepository $productToRemoteCategoryRepository,
50
        CategoryRepository $categoryRepository,
51
        CategoryDenormalization $categoryDenormalization
52
    ) {
53
        $this->manager = $manager;
54
        $this->remoteCategoryRepository = $remoteCategoryRepository;
55
        $this->productToRemoteCategoryRepository = $productToRemoteCategoryRepository;
56
        $this->categoryRepository = $categoryRepository;
57
        $this->categoryDenormalization = $categoryDenormalization;
58
    }
59
60
    /**
61
     * Returns array with category entities
62
     * if they don't exist will be created
63
     *
64
     * @param array $categories
65
     * @return \Shopware\Models\Category\Category[]
66
     */
67
    abstract public function resolve(array $categories);
68
69
    /**
70
     * Generates categories tree by given array of categories
71
     *
72
     * @param array $categories
73
     * @param string $idPrefix
74
     * @return array
75
     */
76
    abstract public function generateTree(array $categories, $idPrefix = '');
77
78
    /**
79
     * Stores raw Shopware Connect categories
80
     *
81
     * @param array $categories
82
     * @param int $articleId
83
     * @return void
84
     */
85
    public function storeRemoteCategories(array $categories, $articleId)
86
    {
87
        $remoteCategories = [];
88
        foreach ($categories as $categoryKey => $category) {
89
            $remoteCategory = $this->remoteCategoryRepository->findOneBy(['categoryKey' => $categoryKey]);
90
            if (!$remoteCategory) {
91
                $remoteCategory = new RemoteCategory();
92
                $remoteCategory->setCategoryKey($categoryKey);
93
            }
94
            $remoteCategory->setLabel($category);
95
            $this->manager->persist($remoteCategory);
96
            $remoteCategories[] = $remoteCategory;
97
        }
98
99
        $this->manager->flush();
100
101
        $this->removeProductsFromNotAssignedRemoteCategories($remoteCategories, $articleId);
102
        $this->addProductToRemoteCategory($remoteCategories, $articleId);
103
104
        $this->manager->flush();
105
    }
106
107
    /**
108
     * @param RemoteCategory[] $remoteCategories
109
     * @param $articleId
110
     */
111
    private function addProductToRemoteCategory(array $remoteCategories, $articleId)
112
    {
113
        $productToCategories = $this->productToRemoteCategoryRepository->getRemoteCategoryIds($articleId);
114
        /** @var $remoteCategory \Shopware\CustomModels\Connect\RemoteCategory */
115
        foreach ($remoteCategories as $remoteCategory) {
116
            if (!in_array($remoteCategory->getId(), $productToCategories)) {
117
                $productToCategory = new ProductToRemoteCategory();
118
                $productToCategory->setArticleId($articleId);
119
                $productToCategory->setConnectCategory($remoteCategory);
120
                $this->manager->persist($productToCategory);
121
            }
122
        }
123
    }
124
125
    /**
126
     * @param \Shopware\CustomModels\Connect\RemoteCategory[] $assignedCategories
127
     * @param int $articleId
128
     */
129
    private function removeProductsFromNotAssignedRemoteCategories(array $assignedCategories, $articleId)
130
    {
131
        $currentProductCategoryIds = $this->productToRemoteCategoryRepository->getRemoteCategoryIds($articleId);
132
133
        $assignedCategoryIds = array_map(function (RemoteCategory $assignedCategory) {
134
            $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...
135
        }, $assignedCategories);
136
137
        /** @var int $currentProductCategoryId */
138
        foreach ($currentProductCategoryIds as $currentProductCategoryId) {
139
            if (!in_array($currentProductCategoryId, $assignedCategoryIds)) {
140
                $this->deleteAssignmentOfLocalCategories($currentProductCategoryId, $articleId);
141
                $this->productToRemoteCategoryRepository->deleteByConnectCategoryId($currentProductCategoryId, $articleId);
142
            }
143
        }
144
    }
145
146
    /**
147
     * @param int $currentProductCategoryId
148
     * @param int $articleId
149
     */
150
    private function deleteAssignmentOfLocalCategories($currentProductCategoryId, $articleId)
151
    {
152
        $localCategoriesIds = $this->manager->getConnection()->executeQuery(
153
            'SELECT local_category_id FROM s_plugin_connect_categories_to_local_categories WHERE remote_category_id = ?',
154
            [$currentProductCategoryId]
155
        )->fetchAll(\PDO::FETCH_COLUMN);
156
        if ($localCategoriesIds) {
157
            foreach ($localCategoriesIds as $categoryId) {
158
                $this->manager->getConnection()->executeQuery(
159
                    'DELETE FROM `s_articles_categories` WHERE `articleID` = ? AND `categoryID` = ?',
160
                    [$articleId, $categoryId]
161
                );
162
                $this->categoryDenormalization->removeAssignment($articleId, $categoryId);
163
            }
164
            $this->deleteEmptyConnectCategories($localCategoriesIds);
165
        }
166
    }
167
168
    /**
169
     * @param int[] $categoryIds
170
     */
171
    public function deleteEmptyConnectCategories($categoryIds)
172
    {
173
        foreach ($categoryIds as $categoryId) {
174
            $articleCount = (int) $this->manager->getConnection()->fetchColumn(
175
                'SELECT COUNT(id) FROM s_articles_categories WHERE categoryID = ?',
176
                [$categoryId]
177
            );
178
            if ($articleCount === 0) {
179
                $this->deleteEmptyCategory($categoryId);
180
            }
181
        }
182
    }
183
184
    /**
185
     * @param int $categoryId
186
     */
187
    private function deleteEmptyCategory($categoryId)
188
    {
189
        $connectImported = $this->manager->getConnection()->fetchColumn(
190
            'SELECT connect_imported_category FROM s_categories_attributes WHERE categoryID = ?',
191
            [$categoryId]
192
        );
193
194
        $childCount = (int) $this->manager->getConnection()->fetchColumn(
195
            'SELECT COUNT(id) FROM s_categories WHERE parent = ?',
196
            [$categoryId]
197
        );
198
199
        if ($connectImported == 1 && $childCount === 0) {
200
            $parent = (int) $this->manager->getConnection()->fetchColumn(
201
                'SELECT parent FROM s_categories WHERE `id` = ?',
202
                [$categoryId]
203
            );
204
205
            $this->manager->getConnection()->executeQuery(
206
                'DELETE FROM `s_categories` WHERE `id` = ?',
207
                [$categoryId]
208
            );
209
210
            $this->deleteEmptyCategory($parent);
211
        }
212
    }
213
214
    /**
215
     * Loop through category tree and fetch ids
216
     *
217
     * @param array $node
218
     * @param int $parentId
219
     * @param bool $returnOnlyLeafs
220
     * @param array $categories
221
     * @return array
222
     */
223
    public function convertTreeToKeys(array $node, $parentId, $returnOnlyLeafs = true, $categories = [])
224
    {
225
        foreach ($node as $category) {
226
            $categoryId = $this->checkAndCreateLocalCategory($category['name'], $category['categoryId'], $parentId);
227
228
            if ((!$returnOnlyLeafs) || (empty($category['children']))) {
229
                $categories[] = [
230
                    'categoryKey' => $categoryId,
231
                    'parentId' => $parentId,
232
                    'remoteCategory' => $category['categoryId']
233
                ];
234
            }
235
236
            if (!empty($category['children'])) {
237
                $categories = $this->convertTreeToKeys($category['children'], $categoryId, $returnOnlyLeafs, $categories);
238
            }
239
        }
240
241
        return $categories;
242
    }
243
244
    /**
245
     * @param string $categoryName
246
     * @param string $categoryKey
247
     * @param int $parentId
248
     * @return int
249
     */
250
    private function checkAndCreateLocalCategory($categoryName, $categoryKey, $parentId)
251
    {
252
        $id = $this->manager->getConnection()->fetchColumn('SELECT `id` 
253
            FROM `s_categories`
254
            WHERE `parent` = :parentId AND `description` = :description',
255
            [':parentId' => $parentId, ':description' => $categoryName]);
256
257
        if (!$id) {
258
            return $this->createLocalCategory($categoryName, $categoryKey, $parentId);
259
        }
260
261
        return $id;
262
    }
263
264
    /**
265
     * @param string $categoryName
266
     * @param string $categoryKey
267
     * @param int $parentId
268
     * @return int
269
     */
270
    public function createLocalCategory($categoryName, $categoryKey, $parentId)
271
    {
272
        $path = $this->manager->getConnection()->fetchColumn('SELECT `path` 
273
            FROM `s_categories`
274
            WHERE `id` = ?',
275
            [$parentId]);
276
        $suffix = ($path) ? "$parentId|" : "|$parentId|";
277
        $path = $path . $suffix;
278
        $now = new \DateTime('now');
279
        $timestamp = $now->format('Y-m-d H:i:s');
280
        $this->manager->getConnection()->executeQuery('INSERT INTO `s_categories` (`description`, `parent`, `path`, `active`, `added`, `changed`) 
281
            VALUES (?, ?, ?, 1, ?, ?)',
282
            [$categoryName, $parentId, $path, $timestamp, $timestamp]);
283
        $localCategoryId = $this->manager->getConnection()->fetchColumn('SELECT LAST_INSERT_ID()');
284
285
        $this->manager->getConnection()->executeQuery('INSERT INTO `s_categories_attributes` (`categoryID`, `connect_imported_category`) 
286
            VALUES (?, 1)',
287
            [$localCategoryId]);
288
289
        $remoteCategoryId = $this->manager->getConnection()->fetchColumn('SELECT `id` 
290
            FROM `s_plugin_connect_categories`
291
            WHERE `category_key` = ?',
292
            [$categoryKey]);
293
        $this->manager->getConnection()->executeQuery('INSERT INTO `s_plugin_connect_categories_to_local_categories` (`remote_category_id`, `local_category_id`) 
294
            VALUES (?, ?)',
295
            [$remoteCategoryId, $localCategoryId]);
296
297
        return $localCategoryId;
298
    }
299
}
300