Passed
Push — master ( e643a0...1f75e2 )
by Michael
03:19
created

Shelf   B

Complexity

Total Complexity 47

Size/Duplication

Total Lines 369
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 47
eloc 205
dl 0
loc 369
rs 8.64
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 2 1
A deleteProduct() 0 50 1
B getRelatedProductsFromProductsIds() 0 28 8
A getProductsCount() 0 13 2
F getProducts() 0 227 34
A initHandlers() 0 2 1

How to fix   Complexity   

Complex Class

Complex classes like Shelf often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Shelf, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace XoopsModules\Oledrion;
4
5
/*
6
 You may not change or alter any portion of this comment or credits
7
 of supporting developers from this source code or any supporting source code
8
 which is considered copyrighted (c) material of the original comment or credit authors.
9
10
 This program is distributed in the hope that it will be useful,
11
 but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13
*/
14
15
/**
16
 * oledrion
17
 *
18
 * @copyright   {@link https://xoops.org/ XOOPS Project}
19
 * @license     {@link http://www.fsf.org/copyleft/gpl.html GNU public license}
20
 * @author      Hervé Thouzard (http://www.herve-thouzard.com/)
21
 */
22
23
/**
24
 * Facade pour les produits
25
 */
26
27
// defined('XOOPS_ROOT_PATH') || die('Restricted access');
28
29
use XoopsModules\Oledrion;
30
31
require_once dirname(__DIR__) . '/preloads/autoloader.php';
32
require_once dirname(__DIR__) . '/include/common.php';
33
34
/**
35
 * Class Shelf
36
 */
37
class Shelf
38
{
39
    //mb    private $handlers;
40
41
    /**
42
     * Shelf constructor.
43
     */
44
    public function __construct()
45
    {
46
        //mb        $this->initHandlers();
47
    }
48
49
    /**
50
     * Chargement des handlers
51
     */
52
    private function initHandlers()
0 ignored issues
show
Unused Code introduced by
The method initHandlers() is not used, and could be removed.

This check looks for private methods that have been defined, but are not used inside the class.

Loading history...
53
    {
54
        //mb        $this->handlers = HandlerManager::getInstance();
55
    }
56
57
    /**
58
     * Retourne le nombre de produits d'un certain type
59
     *
60
     * @param  string $type Le type de produits dont on veut récupérer le nombre
61
     * @param  int    $category
62
     * @param  int    $excluded
63
     * @return int
64
     */
65
    public function getProductsCount($type = 'recent', $category = 0, $excluded = 0)
66
    {
67
        switch (mb_strtolower($type)) {
68
            case 'recent':
69
70
                $db              = \XoopsDatabaseFactory::getDatabaseConnection();
0 ignored issues
show
Bug introduced by
The type XoopsDatabaseFactory was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
71
                $productsHandler = new Oledrion\ProductsHandler($db);
72
73
                return $productsHandler->getRecentProductsCount($category, $excluded);
74
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
75
        }
76
77
        return 0;
78
    }
79
80
    /**
81
     * Supprime un produit (et tout ce qui lui est relatif)
82
     * @param Products $product
83
     * @return mixed
84
     */
85
    public function deleteProduct(Products $product)
86
    {
87
        global $xoopsModule;
88
        $id = $product->getVar('product_id');
89
90
        // On commence par supprimer les commentaires
91
        $mid = $xoopsModule->getVar('mid');
92
        xoops_comment_delete($mid, $id);
0 ignored issues
show
Bug introduced by
The function xoops_comment_delete was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

92
        /** @scrutinizer ignore-call */ 
93
        xoops_comment_delete($mid, $id);
Loading history...
93
94
        // Puis les votes
95
        $votedataHandler = new \XoopsModules\Oledrion\VotedataHandler();
96
        $votedataHandler->deleteProductRatings($id);
97
98
        // Puis les produits relatifs
99
        $relatedHandler = new \XoopsModules\Oledrion\RelatedHandler();
100
        $relatedHandler->deleteProductRelatedProducts($id);
101
102
        // Les images (la grande et la miniature)
103
        $product->deletePictures();
104
105
        // Le fichier attaché
106
        $product->deleteAttachment();
107
108
        // Les fichiers attachés
109
        $filesHandler = new \XoopsModules\Oledrion\FilesHandler();
110
        $filesHandler->deleteProductFiles($id);
111
112
        // Suppression dans les paniers persistants enregistrés
113
        $persistentCartHandler = new \XoopsModules\Oledrion\PersistentCartHandler();
114
        $persistentCartHandler->deleteProductForAllCarts($id);
115
116
        // Les attributs qui lui sont rattachés
117
        $attributesHandler = new \XoopsModules\Oledrion\AttributesHandler();
118
        $attributesHandler->deleteProductAttributes($id);
119
120
        // Le produit dans les listes
121
        $productsListHandler = new \XoopsModules\Oledrion\ProductsListHandler();
122
        $productsListHandler->deleteProductFromLists($id);
123
124
        // La relation entre le produit et le fabricant
125
        $productsmanuHandler = new \XoopsModules\Oledrion\productsmanuHandler();
126
        $productsmanuHandler->removeManufacturerProduct($id);
127
128
        // Le produit dans les remises
129
        $discountsHandler = new \XoopsModules\Oledrion\DiscountsHandler();
130
        $discountsHandler->removeProductFromDiscounts($id);
131
132
        // Et le produit en lui même, à la fin
133
        $productsHandler = new \XoopsModules\Oledrion\ProductsHandler();
134
        return $productsHandler->delete($product, true);
135
    }
136
137
    /**
138
     * Cherche et retourne la liste de produits relatifs à une liste de produits
139
     *
140
     * @param  array $productsIds La liste des produits dont on cherche les produits relatifs
141
     * @return array Clé = ID Produit, valeurs (deuxième dimension) = liste des produits relatifs
142
     */
143
    private function getRelatedProductsFromProductsIds($productsIds)
144
    {
145
        $relatedProducts = $relatedProductsIds = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $relatedProductsIds is dead and can be removed.
Loading history...
146
        $db              = \XoopsDatabaseFactory::getDatabaseConnection();
147
        $relatedHandler  = new Oledrion\RelatedHandler($db);
148
        $productsHandler = new Oledrion\ProductsHandler($db);
149
        if (is_array($productsIds) && count($productsIds) > 0) {
150
            $relatedProductsIds = $relatedHandler->getRelatedProductsFromProductsIds($productsIds);
151
            if (count($relatedProductsIds) > 0) {
152
                $tmp = [];
153
                foreach ($relatedProductsIds as $relatedProductId) {
154
                    $tmp[] = $relatedProductId->getVar('related_product_related');
155
                }
156
                $tmp = array_unique($tmp);
157
                sort($tmp);
158
                if (count($tmp) > 0) {
159
                    $tempRelatedProducts = $productsHandler->getProductsFromIDs($tmp);
160
                    /** @var \XoopsModules\Oledrion\Products $relatedProductId */
161
                    foreach ($relatedProductsIds as $relatedProductId) {
162
                        if (isset($tempRelatedProducts[$relatedProductId->getVar('related_product_related')])) {
163
                            $relatedProducts[$relatedProductId->getVar('related_product_id')][] = $tempRelatedProducts[$relatedProductId->getVar('related_product_related')];
164
                        }
165
                    }
166
                }
167
            }
168
        }
169
170
        return $relatedProducts;
171
    }
172
173
    /**
174
     * Retourne une liste de produits selon certains critères
175
     *
176
     * @param  ShelfParameters $parameters Les paramètres de filtrage
177
     * @return array                     Tableau prêt à être utilisé dans les templates
178
     */
179
    public function getProducts(ShelfParameters $parameters)
180
    {
181
        $db              = \XoopsDatabaseFactory::getDatabaseConnection();
182
        $productsHandler = new Oledrion\ProductsHandler($db);
183
        $vendorsHandler  = new Oledrion\VendorsHandler($db);
0 ignored issues
show
Unused Code introduced by
The assignment to $vendorsHandler is dead and can be removed.
Loading history...
184
        $caddyHandler    = new Oledrion\CaddyHandler($db);
185
186
        $parametersValues    = $parameters->getParameters();
187
        $productType         = $parametersValues['productsType'];
188
        $start               = $parametersValues['start'];
189
        $limit               = $parametersValues['limit'];
190
        $category            = $parametersValues['category'];
191
        $sort                = $parametersValues['sort'];
192
        $order               = $parametersValues['order'];
193
        $excluded            = $parametersValues['excluded'];
194
        $withXoopsUser       = $parametersValues['withXoopsUser'];
195
        $withRelatedProducts = $parametersValues['withRelatedProducts'];
196
        $withQuantity        = $parametersValues['withQuantity'];
197
        $thisMonthOnly       = $parametersValues['thisMonthOnly'];
198
        $ret                 = $xoopsUsersIDs = $users = $relatedProducts = $productsManufacturers = $manufacturersPerProduct = $products = $productsIds = $categoriesIds = $vendorsIds = $manufacturersIds = $manufacturers = $categories = $vendors = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $productsManufacturers is dead and can be removed.
Loading history...
Unused Code introduced by
The assignment to $productsIds is dead and can be removed.
Loading history...
199
        // On commence par récupérer la liste des produits
200
        switch (mb_strtolower($productType)) {
201
            case 'recent':
202
203
                $products = $productsHandler->getRecentProducts(new Oledrion\Parameters([
204
                                                                                            'start'         => $start,
205
                                                                                            'limit'         => $limit,
206
                                                                                            'category'      => $category,
207
                                                                                            'sort'          => $sort,
208
                                                                                            'order'         => $order,
209
                                                                                            'excluded'      => $excluded,
210
                                                                                            'thisMonthOnly' => $thisMonthOnly,
211
                                                                                        ]));
212
213
                break;
214
            case 'mostsold':
215
216
                $tempProductsIds = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $tempProductsIds is dead and can be removed.
Loading history...
217
                $tempProductsIds = $caddyHandler->getMostSoldProducts($start, $limit, $category, $withQuantity);
218
                if (count($tempProductsIds) > 0) {
219
                    $products = $productsHandler->getProductsFromIDs(array_keys($tempProductsIds));
220
                }
221
222
                break;
223
            case 'recentlysold':
224
225
                $tempProductsIds = [];
226
                $tempProductsIds = $caddyHandler->getRecentlySoldProducts($start, $limit);
227
                if (count($tempProductsIds) > 0) {
228
                    $tempProductsIds = array_unique($tempProductsIds);
229
                }
230
                if (count($tempProductsIds) > 0) {
231
                    $products = $productsHandler->getProductsFromIDs(array_keys($tempProductsIds));
232
                }
233
234
                break;
235
            case 'mostviewed':
236
237
                $products = $productsHandler->getMostViewedProducts(new Oledrion\Parameters([
238
                                                                                                'start'    => $start,
239
                                                                                                'limit'    => $limit,
240
                                                                                                'category' => $category,
241
                                                                                                'sort'     => $sort,
242
                                                                                                'order'    => $order,
243
                                                                                            ]));
244
245
                break;
246
            case 'bestrated':
247
248
                $products = $productsHandler->getBestRatedProducts(new Oledrion\Parameters([
249
                                                                                               'start'    => $start,
250
                                                                                               'limit'    => $limit,
251
                                                                                               'category' => $category,
252
                                                                                               'sort'     => $sort,
253
                                                                                               'order'    => $order,
254
                                                                                           ]));
255
256
                break;
257
            case 'recommended':
258
259
                $products = $productsHandler->getRecentRecommended(new Oledrion\Parameters([
260
                                                                                               'start'    => $start,
261
                                                                                               'limit'    => $limit,
262
                                                                                               'category' => $category,
263
                                                                                               'sort'     => $sort,
264
                                                                                               'order'    => $order,
265
                                                                                           ]));
266
267
                break;
268
            case 'promotional':
269
270
                $products = $productsHandler->getPromotionalProducts(new Oledrion\Parameters([
271
                                                                                                 'start'    => $start,
272
                                                                                                 'limit'    => $limit,
273
                                                                                                 'category' => $category,
274
                                                                                                 'sort'     => $sort,
275
                                                                                                 'order'    => $order,
276
                                                                                             ]));
277
278
                break;
279
            case 'random':
280
281
                $products = $productsHandler->getRandomProducts(new Oledrion\Parameters([
282
                                                                                            'start'         => $start,
283
                                                                                            'limit'         => $limit,
284
                                                                                            'category'      => $category,
285
                                                                                            'sort'          => $sort,
286
                                                                                            'order'         => $order,
287
                                                                                            'thisMonthOnly' => $thisMonthOnly,
288
                                                                                        ]));
289
        }
290
291
        if (count($products) > 0) {
292
            $productsIds = array_keys($products);
293
        } else {
294
            return $ret;
295
        }
296
297
        // Recherche des Id des catégories et des vendeurs
298
        foreach ($products as $product) {
299
            $categoriesIds[] = $product->getVar('product_cid');
300
            $vendorsIds[]    = $product->getVar('product_vendor_id');
301
            if ($withXoopsUser) {
302
                $xoopsUsersIDs[] = $product->getVar('product_submitter');
303
            }
304
        }
305
306
        $db                    = \XoopsDatabaseFactory::getDatabaseConnection();
307
        $productsmanuHandler   = new Oledrion\ProductsmanuHandler($db);
308
        $categoryHandler       = new Oledrion\CategoryHandler($db);
309
        $productsManufacturers = $productsmanuHandler->getFromProductsIds($productsIds);
310
        $vendorsHandler        = new Oledrion\VendorsHandler($db);
311
        $manufacturerHandler   = new Oledrion\ManufacturerHandler($db);
312
        // Regroupement des fabricants par produit
313
        foreach ($productsManufacturers as $item) {
314
            $manufacturersIds[]                                        = $item->getVar('pm_manu_id');
315
            $manufacturersPerProduct[$item->getVar('pm_product_id')][] = $item;
316
        }
317
        // On récupère la liste des personnes qui ont soumis les produits
318
        if ($withXoopsUser) {
319
            $users = Oledrion\Utility::getUsersFromIds($xoopsUsersIDs);
320
        }
321
322
        // Il faut récupérer la liste des produits relatifs
323
        if ($withRelatedProducts) {
324
            $relatedProducts = $this->getRelatedProductsFromProductsIds($productsIds);
325
        }
326
327
        $categoriesIds = array_unique($categoriesIds);
328
        sort($categoriesIds);
329
330
        $vendorsIds = array_unique($vendorsIds);
331
        sort($vendorsIds);
332
333
        $manufacturersIds = array_unique($manufacturersIds);
334
        sort($manufacturersIds);
335
336
        // Récupération des fabricants, des vendeurs et des catégories
337
        if (count($manufacturersIds) > 0) {
338
            $manufacturers = $manufacturerHandler->getManufacturersFromIds($manufacturersIds);
339
        }
340
        if (count($categoriesIds) > 0) {
341
            //mb            $categories = $this->handlers->h_oledrion_cat->getCategoriesFromIds($categoriesIds);
342
            $categories = $categoryHandler->getCategoriesFromIds($categoriesIds);
343
        }
344
        if (count($vendorsIds) > 0) {
345
            $vendors = $vendorsHandler->getVendorsFromIds($vendorsIds);
346
        }
347
348
        $count     = 1;
349
        $lastTitle = '';
350
        foreach ($products as $product) {
351
            $tmp       = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $tmp is dead and can be removed.
Loading history...
352
            $tmp       = $product->toArray();
353
            $lastTitle = $product->getVar('product_title');
354
            // Le vendeur
355
            if (isset($vendors[$product->getVar('product_vendor_id')])) {
356
                $tmp['product_vendor'] = $vendors[$product->getVar('product_vendor_id')]->toArray();
357
            }
358
            // La catégorie
359
            if (isset($categories[$product->getVar('product_cid')])) {
360
                $tmp['product_category'] = $categories[$product->getVar('product_cid')]->toArray();
361
            }
362
            // Les produits relatifs
363
            if ($withRelatedProducts) {
364
                if (isset($relatedProducts[$product->getVar('product_id')])) {
365
                    $productsRelatedToThisOne = $relatedProducts[$product->getVar('product_id')];
366
                    foreach ($productsRelatedToThisOne as $oneRelatedProdut) {
367
                        $tmp['product_related_products'][] = $oneRelatedProdut->toArray();
368
                    }
369
                }
370
            }
371
            // Les fabricants du produit
372
            if (isset($manufacturersPerProduct[$product->getVar('product_id')])) {
373
                $productManufacturers = $manufacturersPerProduct[$product->getVar('product_id')];
374
                $tmpManufacturersList = [];
375
                foreach ($productManufacturers as $productManufacturer) {
376
                    if (isset($manufacturers[$productManufacturer->getVar('pm_manu_id')])) {
377
                        $manufacturer                   = $manufacturers[$productManufacturer->getVar('pm_manu_id')];
378
                        $tmp['product_manufacturers'][] = $manufacturer->toArray();
379
                        $tmpManufacturersList[]         = $manufacturer->getVar('manu_commercialname') . ' ' . $manufacturer->getVar('manu_name');
380
                    }
381
                }
382
                if (count($tmpManufacturersList) > 0) {
383
                    $tmp['product_joined_manufacturers'] = implode(OLEDRION_STRING_TO_JOIN_MANUFACTURERS, $tmpManufacturersList);
384
                }
385
            }
386
387
            // L'utilisateur Xoops (éventuellement)
388
            if ($withXoopsUser && isset($users[$product->getVar('product_submitter')])) {
389
                $thisUser = $users[$product->getVar('product_submitter')];
390
                if ('' !== xoops_trim($thisUser->getVar('name'))) {
0 ignored issues
show
Bug introduced by
The function xoops_trim was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

390
                if ('' !== /** @scrutinizer ignore-call */ xoops_trim($thisUser->getVar('name'))) {
Loading history...
391
                    $name = $thisUser->getVar('name');
392
                } else {
393
                    $name = $thisUser->getVar('uname');
394
                }
395
                $tmp['product_submiter_name'] = $name;
396
                $userLink                     = '<a href="' . XOOPS_URL . '/userinfo.php?uid=' . $thisUser->getVar('uid') . '">' . $name . '</a>';
0 ignored issues
show
Bug introduced by
The constant XoopsModules\Oledrion\XOOPS_URL was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
397
                $tmp['product_submiter_link'] = $userLink;
398
            }
399
            $tmp['product_count'] = $count; // Compteur pour les templates (pour gérer les colonnes)
400
            $ret[]                = $tmp;
401
            ++$count;
402
        }
403
        $ret['lastTitle'] = $lastTitle;
404
405
        return $ret;
406
    }
407
}
408