Completed
Pull Request — master (#410)
by Jonas
02:59
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
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
            $this->manager->getConnection()->executeQuery(
158
                'DELETE FROM `s_articles_categories` WHERE `articleID` = ? AND `categoryID` IN (?)',
159
                [$articleId, $localCategoriesIds],
160
                [\PDO::PARAM_INT, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY]
161
            );
162
            foreach ($localCategoriesIds as $categoryId) {
163
                $this->categoryDenormalization->removeAssignment($articleId, $categoryId);
164
            }
165
166
            $this->deleteEmptyConnectCategories($localCategoriesIds);
167
        }
168
    }
169
170
    /**
171
     * @param int[] $categoryIds
172
     */
173
    public function deleteEmptyConnectCategories(array $categoryIds)
174
    {
175
        foreach ($categoryIds as $categoryId) {
176
            $articleCount = (int) $this->manager->getConnection()->fetchColumn(
177
                'SELECT COUNT(id) FROM s_articles_categories WHERE categoryID = ?',
178
                [$categoryId]
179
            );
180
            if ($articleCount === 0) {
181
                $this->deleteEmptyCategory($categoryId);
182
            }
183
        }
184
    }
185
186
    /**
187
     * @param int $categoryId
188
     */
189
    private function deleteEmptyCategory($categoryId)
190
    {
191
        $connectImported = $this->manager->getConnection()->fetchColumn(
192
            'SELECT connect_imported_category FROM s_categories_attributes WHERE categoryID = ?',
193
            [$categoryId]
194
        );
195
196
        if ($connectImported == 1 && $this->countChildCategories($categoryId) === 0) {
197
            $parent = (int) $this->manager->getConnection()->fetchColumn(
198
                'SELECT parent FROM s_categories WHERE `id` = ?',
199
                [$categoryId]
200
            );
201
202
            $this->manager->getConnection()->executeQuery(
203
                'DELETE FROM `s_categories` WHERE `id` = ?',
204
                [$categoryId]
205
            );
206
207
            $this->deleteEmptyCategory($parent);
208
        }
209
    }
210
211
    /**
212
     * Loop through category tree and fetch ids
213
     *
214
     * @param array $node
215
     * @param int $parentId
216
     * @param bool $returnOnlyLeafs
217
     * @param array $categories
218
     * @return array
219
     */
220
    public function convertTreeToKeys(array $node, $parentId, $returnOnlyLeafs = true, $categories = [])
221
    {
222
        foreach ($node as $category) {
223
            $categoryId = $this->checkAndCreateLocalCategory($category['name'], $category['categoryId'], $parentId);
224
225
            if ((!$returnOnlyLeafs) || (empty($category['children']))) {
226
                $categories[] = [
227
                    'categoryKey' => $categoryId,
228
                    'parentId' => $parentId,
229
                    'remoteCategory' => $category['categoryId']
230
                ];
231
            }
232
233
            if (!empty($category['children'])) {
234
                $categories = $this->convertTreeToKeys($category['children'], $categoryId, $returnOnlyLeafs, $categories);
235
            }
236
        }
237
238
        return $categories;
239
    }
240
241
    /**
242
     * @param string $categoryName
243
     * @param string $categoryKey
244
     * @param int $parentId
245
     * @return int
246
     */
247
    private function checkAndCreateLocalCategory($categoryName, $categoryKey, $parentId)
248
    {
249
        $id = $this->manager->getConnection()->fetchColumn('SELECT `id` 
250
            FROM `s_categories`
251
            WHERE `parent` = :parentId AND `description` = :description',
252
            [':parentId' => $parentId, ':description' => $categoryName]);
253
254
        if (!$id) {
255
            return $this->createLocalCategory($categoryName, $categoryKey, $parentId);
256
        }
257
258
        return $id;
259
    }
260
261
    /**
262
     * @param string $categoryName
263
     * @param string $categoryKey
264
     * @param int $parentId
265
     * @return int
266
     */
267
    public function createLocalCategory($categoryName, $categoryKey, $parentId)
268
    {
269
        $path = $this->manager->getConnection()->fetchColumn('SELECT `path` 
270
            FROM `s_categories`
271
            WHERE `id` = ?',
272
            [$parentId]);
273
        $suffix = ($path) ? "$parentId|" : "|$parentId|";
274
        $path = $path . $suffix;
275
        $now = new \DateTime('now');
276
        $timestamp = $now->format('Y-m-d H:i:s');
277
        $this->manager->getConnection()->executeQuery('INSERT INTO `s_categories` (`description`, `parent`, `path`, `active`, `added`, `changed`) 
278
            VALUES (?, ?, ?, 1, ?, ?)',
279
            [$categoryName, $parentId, $path, $timestamp, $timestamp]);
280
        $localCategoryId = $this->manager->getConnection()->fetchColumn('SELECT LAST_INSERT_ID()');
281
282
        $this->manager->getConnection()->executeQuery('INSERT INTO `s_categories_attributes` (`categoryID`, `connect_imported_category`) 
283
            VALUES (?, 1)',
284
            [$localCategoryId]);
285
286
        $remoteCategoryId = $this->manager->getConnection()->fetchColumn('SELECT `id` 
287
            FROM `s_plugin_connect_categories`
288
            WHERE `category_key` = ?',
289
            [$categoryKey]);
290
        $this->manager->getConnection()->executeQuery('INSERT INTO `s_plugin_connect_categories_to_local_categories` (`remote_category_id`, `local_category_id`) 
291
            VALUES (?, ?)',
292
            [$remoteCategoryId, $localCategoryId]);
293
294
        return $localCategoryId;
295
    }
296
297
    /**
298
     * @param $categoryId
299
     * @return int
300
     */
301
    private function countChildCategories($categoryId)
302
    {
303
        return (int) $this->manager->getConnection()->fetchColumn(
304
            'SELECT COUNT(id) FROM s_categories WHERE parent = ?',
305
            [$categoryId]
306
        );
307
    }
308
}
309