Passed
Pull Request — master (#14)
by Michael
04:13
created

class/Shelf.php (1 issue)

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()
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();
71
                $productsHandler = new Oledrion\ProductsHandler($db);
72
73
                return $productsHandler->getRecentProductsCount($category, $excluded);
74
                break;
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
        /** @var \XoopsDatabase $db */
90
        $db = \XoopsDatabaseFactory::getDatabaseConnection();
91
92
93
        // On commence par supprimer les commentaires
94
        $mid = $xoopsModule->getVar('mid');
95
        xoops_comment_delete($mid, $id);
96
97
        // Puis les votes
98
        $votedataHandler = new \XoopsModules\Oledrion\VotedataHandler($db);
99
        $votedataHandler->deleteProductRatings($id);
100
101
        // Puis les produits relatifs
102
        $relatedHandler = new \XoopsModules\Oledrion\RelatedHandler($db);
103
        $relatedHandler->deleteProductRelatedProducts($id);
104
105
        // Les images (la grande et la miniature)
106
        $product->deletePictures();
107
108
        // Le fichier attaché
109
        $product->deleteAttachment();
110
111
        // Les fichiers attachés
112
        $filesHandler = new \XoopsModules\Oledrion\FilesHandler($db);
113
        $filesHandler->deleteProductFiles($id);
114
115
        // Suppression dans les paniers persistants enregistrés
116
        $persistentCartHandler = new \XoopsModules\Oledrion\PersistentCartHandler($db);
117
        $persistentCartHandler->deleteProductForAllCarts($id);
118
119
        // Les attributs qui lui sont rattachés
120
        $attributesHandler = new \XoopsModules\Oledrion\AttributesHandler($db);
121
        $attributesHandler->deleteProductAttributes($id);
122
123
        // Le produit dans les listes
124
        $productsListHandler = new \XoopsModules\Oledrion\ProductsListHandler($db);
125
        $productsListHandler->deleteProductFromLists($id);
126
127
        // La relation entre le produit et le fabricant
128
        $productsmanuHandler = new \XoopsModules\Oledrion\productsmanuHandler($db);
129
        $productsmanuHandler->removeManufacturerProduct($id);
130
131
        // Le produit dans les remises
132
        $discountsHandler = new \XoopsModules\Oledrion\DiscountsHandler($db);
133
        $discountsHandler->removeProductFromDiscounts($id);
134
135
        // Et le produit en lui même, à la fin
136
        $productsHandler = new \XoopsModules\Oledrion\ProductsHandler($db);
137
138
        return $productsHandler->delete($product, true);
139
    }
140
141
    /**
142
     * Cherche et retourne la liste de produits relatifs à une liste de produits
143
     *
144
     * @param  array $productsIds La liste des produits dont on cherche les produits relatifs
145
     * @return array Clé = ID Produit, valeurs (deuxième dimension) = liste des produits relatifs
146
     */
147
    private function getRelatedProductsFromProductsIds($productsIds)
148
    {
149
        $relatedProducts = $relatedProductsIds = [];
150
        $db              = \XoopsDatabaseFactory::getDatabaseConnection();
151
        $relatedHandler  = new Oledrion\RelatedHandler($db);
152
        $productsHandler = new Oledrion\ProductsHandler($db);
153
        if ($productsIds && is_array($productsIds)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $productsIds of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
154
            $relatedProductsIds = $relatedHandler->getRelatedProductsFromProductsIds($productsIds);
155
            if (count($relatedProductsIds) > 0) {
156
                $tmp = [];
157
                foreach ($relatedProductsIds as $relatedProductId) {
158
                    $tmp[] = $relatedProductId->getVar('related_product_related');
159
                }
160
                $tmp = array_unique($tmp);
161
                sort($tmp);
162
                if (count($tmp) > 0) {
163
                    $tempRelatedProducts = $productsHandler->getProductsFromIDs($tmp);
164
                    /** @var \XoopsModules\Oledrion\Products $relatedProductId */
165
                    foreach ($relatedProductsIds as $relatedProductId) {
166
                        if (isset($tempRelatedProducts[$relatedProductId->getVar('related_product_related')])) {
167
                            $relatedProducts[$relatedProductId->getVar('related_product_id')][] = $tempRelatedProducts[$relatedProductId->getVar('related_product_related')];
168
                        }
169
                    }
170
                }
171
            }
172
        }
173
174
        return $relatedProducts;
175
    }
176
177
    /**
178
     * Retourne une liste de produits selon certains critères
179
     *
180
     * @param  ShelfParameters $parameters Les paramètres de filtrage
181
     * @return array                     Tableau prêt à être utilisé dans les templates
182
     */
183
    public function getProducts(ShelfParameters $parameters)
184
    {
185
        $db              = \XoopsDatabaseFactory::getDatabaseConnection();
186
        $productsHandler = new Oledrion\ProductsHandler($db);
187
        $vendorsHandler  = new Oledrion\VendorsHandler($db);
188
        $caddyHandler    = new Oledrion\CaddyHandler($db);
189
190
        $parametersValues    = $parameters->getParameters();
191
        $productType         = $parametersValues['productsType'];
192
        $start               = $parametersValues['start'];
193
        $limit               = $parametersValues['limit'];
194
        $category            = $parametersValues['category'];
195
        $sort                = $parametersValues['sort'];
196
        $order               = $parametersValues['order'];
197
        $excluded            = $parametersValues['excluded'];
198
        $withXoopsUser       = $parametersValues['withXoopsUser'];
199
        $withRelatedProducts = $parametersValues['withRelatedProducts'];
200
        $withQuantity        = $parametersValues['withQuantity'];
201
        $thisMonthOnly       = $parametersValues['thisMonthOnly'];
202
        $ret                 = $xoopsUsersIDs = $users = $relatedProducts = $productsManufacturers = $manufacturersPerProduct = $products = $productsIds = $categoriesIds = $vendorsIds = $manufacturersIds = $manufacturers = $categories = $vendors = [];
203
        // On commence par récupérer la liste des produits
204
        switch (mb_strtolower($productType)) {
205
            case 'recent':
206
207
                $products = $productsHandler->getRecentProducts(new Oledrion\Parameters([
208
                                                                                            'start'         => $start,
209
                                                                                            'limit'         => $limit,
210
                                                                                            'category'      => $category,
211
                                                                                            'sort'          => $sort,
212
                                                                                            'order'         => $order,
213
                                                                                            'excluded'      => $excluded,
214
                                                                                            'thisMonthOnly' => $thisMonthOnly,
215
                                                                                        ]));
216
217
                break;
218
            case 'mostsold':
219
220
                $tempProductsIds = [];
221
                $tempProductsIds = $caddyHandler->getMostSoldProducts($start, $limit, $category, $withQuantity);
222
                if (count($tempProductsIds) > 0) {
223
                    $products = $productsHandler->getProductsFromIDs(array_keys($tempProductsIds));
224
                }
225
226
                break;
227
            case 'recentlysold':
228
229
                $tempProductsIds = [];
230
                $tempProductsIds = $caddyHandler->getRecentlySoldProducts($start, $limit);
231
                if (count($tempProductsIds) > 0) {
232
                    $tempProductsIds = array_unique($tempProductsIds);
233
                }
234
                if (count($tempProductsIds) > 0) {
235
                    $products = $productsHandler->getProductsFromIDs(array_keys($tempProductsIds));
236
                }
237
238
                break;
239
            case 'mostviewed':
240
241
                $products = $productsHandler->getMostViewedProducts(new Oledrion\Parameters([
242
                                                                                                'start'    => $start,
243
                                                                                                'limit'    => $limit,
244
                                                                                                'category' => $category,
245
                                                                                                'sort'     => $sort,
246
                                                                                                'order'    => $order,
247
                                                                                            ]));
248
249
                break;
250
            case 'bestrated':
251
252
                $products = $productsHandler->getBestRatedProducts(new Oledrion\Parameters([
253
                                                                                               'start'    => $start,
254
                                                                                               'limit'    => $limit,
255
                                                                                               'category' => $category,
256
                                                                                               'sort'     => $sort,
257
                                                                                               'order'    => $order,
258
                                                                                           ]));
259
260
                break;
261
            case 'recommended':
262
263
                $products = $productsHandler->getRecentRecommended(new Oledrion\Parameters([
264
                                                                                               'start'    => $start,
265
                                                                                               'limit'    => $limit,
266
                                                                                               'category' => $category,
267
                                                                                               'sort'     => $sort,
268
                                                                                               'order'    => $order,
269
                                                                                           ]));
270
271
                break;
272
            case 'promotional':
273
274
                $products = $productsHandler->getPromotionalProducts(new Oledrion\Parameters([
275
                                                                                                 'start'    => $start,
276
                                                                                                 'limit'    => $limit,
277
                                                                                                 'category' => $category,
278
                                                                                                 'sort'     => $sort,
279
                                                                                                 'order'    => $order,
280
                                                                                             ]));
281
282
                break;
283
            case 'random':
284
285
                $products = $productsHandler->getRandomProducts(new Oledrion\Parameters([
286
                                                                                            'start'         => $start,
287
                                                                                            'limit'         => $limit,
288
                                                                                            'category'      => $category,
289
                                                                                            'sort'          => $sort,
290
                                                                                            'order'         => $order,
291
                                                                                            'thisMonthOnly' => $thisMonthOnly,
292
                                                                                        ]));
293
        }
294
295
        if (count($products) > 0) {
296
            $productsIds = array_keys($products);
297
        } else {
298
            return $ret;
299
        }
300
301
        // Recherche des Id des catégories et des vendeurs
302
        foreach ($products as $product) {
303
            $categoriesIds[] = $product->getVar('product_cid');
304
            $vendorsIds[]    = $product->getVar('product_vendor_id');
305
            if ($withXoopsUser) {
306
                $xoopsUsersIDs[] = $product->getVar('product_submitter');
307
            }
308
        }
309
310
        $db                    = \XoopsDatabaseFactory::getDatabaseConnection();
311
        $productsmanuHandler   = new Oledrion\ProductsmanuHandler($db);
312
        $categoryHandler       = new Oledrion\CategoryHandler($db);
313
        $productsManufacturers = $productsmanuHandler->getFromProductsIds($productsIds);
314
        $vendorsHandler        = new Oledrion\VendorsHandler($db);
315
        $manufacturerHandler   = new Oledrion\ManufacturerHandler($db);
316
        // Regroupement des fabricants par produit
317
        foreach ($productsManufacturers as $item) {
318
            $manufacturersIds[]                                        = $item->getVar('pm_manu_id');
319
            $manufacturersPerProduct[$item->getVar('pm_product_id')][] = $item;
320
        }
321
        // On récupère la liste des personnes qui ont soumis les produits
322
        if ($withXoopsUser) {
323
            $users = Oledrion\Utility::getUsersFromIds($xoopsUsersIDs);
324
        }
325
326
        // Il faut récupérer la liste des produits relatifs
327
        if ($withRelatedProducts) {
328
            $relatedProducts = $this->getRelatedProductsFromProductsIds($productsIds);
329
        }
330
331
        $categoriesIds = array_unique($categoriesIds);
332
        sort($categoriesIds);
333
334
        $vendorsIds = array_unique($vendorsIds);
335
        sort($vendorsIds);
336
337
        $manufacturersIds = array_unique($manufacturersIds);
338
        sort($manufacturersIds);
339
340
        // Récupération des fabricants, des vendeurs et des catégories
341
        if (count($manufacturersIds) > 0) {
342
            $manufacturers = $manufacturerHandler->getManufacturersFromIds($manufacturersIds);
343
        }
344
        if (count($categoriesIds) > 0) {
345
            //mb            $categories = $this->handlers->h_oledrion_cat->getCategoriesFromIds($categoriesIds);
346
            $categories = $categoryHandler->getCategoriesFromIds($categoriesIds);
347
        }
348
        if (count($vendorsIds) > 0) {
349
            $vendors = $vendorsHandler->getVendorsFromIds($vendorsIds);
350
        }
351
352
        $count     = 1;
353
        $lastTitle = '';
354
        foreach ($products as $product) {
355
            $tmp       = [];
356
            $tmp       = $product->toArray();
357
            $lastTitle = $product->getVar('product_title');
358
            // Le vendeur
359
            if (isset($vendors[$product->getVar('product_vendor_id')])) {
360
                $tmp['product_vendor'] = $vendors[$product->getVar('product_vendor_id')]->toArray();
361
            }
362
            // La catégorie
363
            if (isset($categories[$product->getVar('product_cid')])) {
364
                $tmp['product_category'] = $categories[$product->getVar('product_cid')]->toArray();
365
            }
366
            // Les produits relatifs
367
            if ($withRelatedProducts) {
368
                if (isset($relatedProducts[$product->getVar('product_id')])) {
369
                    $productsRelatedToThisOne = $relatedProducts[$product->getVar('product_id')];
370
                    foreach ($productsRelatedToThisOne as $oneRelatedProdut) {
371
                        $tmp['product_related_products'][] = $oneRelatedProdut->toArray();
372
                    }
373
                }
374
            }
375
            // Les fabricants du produit
376
            if (isset($manufacturersPerProduct[$product->getVar('product_id')])) {
377
                $productManufacturers = $manufacturersPerProduct[$product->getVar('product_id')];
378
                $tmpManufacturersList = [];
379
                foreach ($productManufacturers as $productManufacturer) {
380
                    if (isset($manufacturers[$productManufacturer->getVar('pm_manu_id')])) {
381
                        $manufacturer                   = $manufacturers[$productManufacturer->getVar('pm_manu_id')];
382
                        $tmp['product_manufacturers'][] = $manufacturer->toArray();
383
                        $tmpManufacturersList[]         = $manufacturer->getVar('manu_commercialname') . ' ' . $manufacturer->getVar('manu_name');
384
                    }
385
                }
386
                if (count($tmpManufacturersList) > 0) {
387
                    $tmp['product_joined_manufacturers'] = implode(OLEDRION_STRING_TO_JOIN_MANUFACTURERS, $tmpManufacturersList);
388
                }
389
            }
390
391
            // L'utilisateur Xoops (éventuellement)
392
            if ($withXoopsUser && isset($users[$product->getVar('product_submitter')])) {
393
                $thisUser = $users[$product->getVar('product_submitter')];
394
                if ('' !== xoops_trim($thisUser->getVar('name'))) {
395
                    $name = $thisUser->getVar('name');
396
                } else {
397
                    $name = $thisUser->getVar('uname');
398
                }
399
                $tmp['product_submiter_name'] = $name;
400
                $userLink                     = '<a href="' . XOOPS_URL . '/userinfo.php?uid=' . $thisUser->getVar('uid') . '">' . $name . '</a>';
401
                $tmp['product_submiter_link'] = $userLink;
402
            }
403
            $tmp['product_count'] = $count; // Compteur pour les templates (pour gérer les colonnes)
404
            $ret[]                = $tmp;
405
            ++$count;
406
        }
407
        $ret['lastTitle'] = $lastTitle;
408
409
        return $ret;
410
    }
411
}
412