Completed
Push — master ( 00e474...9d3fbd )
by Michael
04:26
created

Oledrion_reductions::computeCart()   F

Complexity

Conditions 88
Paths > 20000

Size

Total Lines 388
Code Lines 238

Duplication

Lines 4
Ratio 1.03 %

Importance

Changes 0
Metric Value
cc 88
eloc 238
nc 95674378
nop 9
dl 4
loc 388
rs 2
c 0
b 0
f 0

How to fix   Long Method    Complexity    Many Parameters   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

1
<?php
2
/**
3
 * ****************************************************************************
4
 * oledrion - MODULE FOR XOOPS
5
 * Copyright (c) Hervé Thouzard of Instant Zero (http://www.instant-zero.com)
6
 *
7
 * You may not change or alter any portion of this comment or credits
8
 * of supporting developers from this source code or any supporting source code
9
 * which is considered copyrighted (c) material of the original comment or credit authors.
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
 * @copyright       Hervé Thouzard of Instant Zero (http://www.instant-zero.com)
15
 * @license         http://www.fsf.org/copyleft/gpl.html GNU public license
16
 * @package         oledrion
17
 * @author          Hervé Thouzard of Instant Zero (http://www.instant-zero.com)
18
 *
19
 * Version :
20
 * ****************************************************************************
21
 */
22
23
/**
24
 * Calcul du panier et de ses réductions en fonction des règles de remises
25
 * Cette classe ne gère pas de fichier (elle sert uniquement aux calculs)
26
 *
27
 * Détail des tableaux :
28
 * categoriesProductsCount => Nombre de produits par catégorie
29
 * [clé] = Id Catégorie, [valeur] = Nombre de produits
30
 *
31
 * categoriesProductsQuantities => Quantités de produits par catégorie
32
 * [clé] = Id Catégorie, [valeur] = Quantité de produits
33
 *
34
 * totalProductsQuantities => Quantité totale de tous les produits
35
 *
36
 * associatedManufacturers => Contient la liste des ID uniques de produits
37
 * [clé] = Id Produit, [valeur] = Id produit
38
 *
39
 * associatedVendors => Contient la liste des vendeurs de produits
40
 * [clé] = Id Vendeur, [valeur] = Id Vendeur
41
 *
42
 * associatedAttributesPerProduct => Contient les attributs de chaque produit
43
 * [clé] = Id Produit, [valeurS] = Tous les attributs du produit sous la forme d'objets de type Attributs
44
 *
45
 * associatedCategories => Contient la liste des ID de catégories
46
 * [clé] = Id Catégorie, [valeur] = Id Catégorie
47
 *
48
 * totalAmountBeforeDiscounts => Montant total de la commande avant les réductions
49
 *
50
 * associatedManufacturersPerProduct => Contient la liste des ID des fabricants par produit
51
 * [clé] = Id produit, [valeur] = array(Ids des fabricants)
52
 *
53
 * Les 3 tableaux suivants évoluent ensuite comme ceci :
54
 * associatedManufacturers => Tableau d'objets de type Fabricants
55
 * [clé] = id Fabricant [valeur] = Fabricant sous la forme d'un objet
56
 *
57
 * associatedVendors => Tableau d'ojets de type Vendeurs
58
 * [clé] = Id Vendeur [valeur] = Vendeur sous la forme d'un objet
59
 *
60
 * associatedCategories => Tableau d'objets de type Categories
61
 * [clé] = Id Catégorie [valeur] = Catéagorie sous la forme d'un objet
62
 *
63
 */
64
class Oledrion_reductions
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
65
{
66
    // Ne contient que la liste des règles actives au moment du calcul
67
    private $allActiveRules = array();
68
69
    // Nombre de produits par catégorie
70
    private $categoriesProductsCount = array();
71
72
    // Quantité de produits par catégorie
73
    private $categoriesProductsQuantities = array();
74
75
    /**
76
     * le caddy en mémoire
77
     *  $cart['number'] = Indice du produit
78
     *  $cart['id'] = Identifiant du produit
79
     *  $cart['qty'] = Quantité voulue
80
     *  $cart['product'] = L'objet produit correspondant au panier
81
     */
82
    private $cart = array();
83
84
    /**
85
     * Le caddy pour le template. Consulter les détails du caddy dans la métode ComputeCart
86
     */
87
    private $cartForTemplate = array();
88
89
    /**
90
     * Les règles à appliquer à la fin, sur l'intégralité du panier
91
     */
92
    private $rulesForTheWhole = array();
93
94
    // Le total des quantités de produits avant les réductions
95
    private $totalProductsQuantities = 0;
96
    // Montant total de la commande avant les réductions
97
    private $totalAmountBeforeDiscounts = 0;
98
99
    // Handlers vers les tables du module
100
    private $handlers;
101
102
    // Les fabricants associés aux produits du panier
103
    private $associatedManufacturers = array();
104
105
    // Les vendeur associés aux produits du panier
106
    private $associatedVendors = array();
107
108
    // Les catégories associées aux produits du panier
109
    private $associatedCategories = array();
110
111
    // Fabricants associés par produit du panier
112
    private $associatedManufacturersPerProduct = array();
113
114
    // Attributs par produit du panier
115
    private $associatedAttributesPerProduct = array();
116
117
    /**
118
     * Chargement des handlers et des règles actives
119
     */
120
    public function __construct()
121
    {
122
        $this->initHandlers();
123
        $this->loadAllActiveRules();
124
    }
125
126
    /**
127
     * Chargement des handlers
128
     */
129
    private function initHandlers()
130
    {
131
        $this->handlers = OledrionHandler::getInstance();
132
    }
133
134
    /**
135
     * Chargement de toutes les règles actives de réductions (sans date définie ou avec une période correspondante à aujourd'hui)
136
     */
137
    public function loadAllActiveRules()
138
    {
139
        $critere  = new CriteriaCompo();
140
        $critere1 = new CriteriaCompo();
141
        $critere1->add(new Criteria('disc_date_from', 0, '='));
142
        $critere1->add(new Criteria('disc_date_to', 0, '='));
143
        $critere->add($critere1);
144
145
        $critere2 = new CriteriaCompo();
146
        $critere2->add(new Criteria('disc_date_from', time(), '<='));
147
        $critere2->add(new Criteria('disc_date_to', time(), '>='));
148
        $critere->add($critere2, 'OR');
149
150
        $this->allActiveRules = $this->handlers->h_oledrion_discounts->getObjects($critere);
0 ignored issues
show
Documentation introduced by
The property h_oledrion_discounts does not exist on object<OledrionHandler>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
151
    }
152
153
    /**
154
     * Calcul des quantités de produits par catégorie et du nombre de produits par catégorie
155
     *
156
     * @param oledrion_products $product
157
     * @param integer           $quantity
158
     */
159
    public function computePerCategories(Oledrion_products $product, $quantity)
160
    {
161
        // Nombre de produits par catégories
162 View Code Duplication
        if (isset($this->categoriesProductsCount[$product->product_cid])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
163
            ++$this->categoriesProductsCount[$product->product_cid];
164
        } else {
165
            $this->categoriesProductsCount[$product->product_cid] = 1;
166
        }
167
168
        // Mise à jour des quantités par catégories
169 View Code Duplication
        if (isset($this->categoriesProductsQuantities[$product->product_cid])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
170
            $this->categoriesProductsQuantities[$product->product_cid] += $quantity;
171
        } else {
172
            $this->categoriesProductsQuantities[$product->product_cid] = $quantity;
173
        }
174
        $this->totalProductsQuantities += $quantity;
175
        // Quantité totale de tous les produits
176
    }
177
178
    /**
179
     * Ajoute à un tableau interne, le fabricant associé à un produit
180
     *
181
     * @param oledrion_products $product
182
     */
183
    private function addAssociatedManufacturers(Oledrion_products $product)
184
    {
185
        if (!isset($this->associatedManufacturers[$product->product_id])) {
186
            $this->associatedManufacturers[$product->product_id] = $product->product_id;
187
        }
188
    }
189
190
    /**
191
     * Recherche des attributs associés à chaque produit
192
     *
193
     * @param oledrion_products $product
194
     * @param attray            $attributes
195
     * @since 2.3
196
     */
197
    private function addAssociatedAttributes(Oledrion_products $product, $attributes)
198
    {
199
        if (!isset($this->associatedAttributesPerProduct[$product->product_id])) {
200
            $this->associatedAttributesPerProduct[$product->product_id] = $product->getProductsAttributesList($attributes);
201
        }
202
    }
203
204
    /**
205
     * Ajoute à un tableau interne, le vendeur associé à un produit
206
     *
207
     * @param oledrion_products $product
208
     */
209
    private function addAssociatedVendors(Oledrion_products $product)
210
    {
211
        if (!isset($this->associatedVendors[$product->product_vendor_id])) {
212
            $this->associatedVendors[$product->product_vendor_id] = $product->product_vendor_id;
213
        }
214
    }
215
216
    /**
217
     * Ajoute à un tableau interne, la catégorie associée à un produit
218
     *
219
     * @param oledrion_products $product
220
     */
221
    private function addAssociatedCategories(Oledrion_products $product)
222
    {
223
        if (!isset($this->associatedCategories[$product->product_cid])) {
224
            $this->associatedCategories[$product->product_cid] = $product->product_cid;
225
        }
226
    }
227
228
    /**
229
     * Charge les fabricants associés aux produits du panier
230
     */
231
    private function loadAssociatedManufacturers()
232
    {
233
        if (count($this->associatedManufacturers) > 0) {
234
            sort($this->associatedManufacturers);
235
            $productsIds                   = $this->associatedManufacturers;
236
            $this->associatedManufacturers = array();
237
            // au cas où cela échouerait
238
            $productsManufacturers = $manufacturersIds = array();
0 ignored issues
show
Unused Code introduced by
$productsManufacturers is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
239
            $productsManufacturers = $this->handlers->h_oledrion_productsmanu->getFromProductsIds($productsIds);
0 ignored issues
show
Documentation introduced by
The property h_oledrion_productsmanu does not exist on object<OledrionHandler>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
240
            if (count($productsManufacturers) > 0) {
241
                foreach ($productsManufacturers as $productManufacturer) {
242
                    if (!isset($manufacturersIds[$productManufacturer->pm_manu_id])) {
243
                        $manufacturersIds[$productManufacturer->pm_manu_id] = $productManufacturer->pm_manu_id;
244
                    }
245
                    $this->associatedManufacturersPerProduct[$productManufacturer->pm_product_id][] = $productManufacturer->pm_manu_id;
246
                }
247
                if (count($manufacturersIds) > 0) {
248
                    sort($manufacturersIds);
249
                    $this->associatedManufacturers = $this->handlers->h_oledrion_manufacturer->getManufacturersFromIds($manufacturersIds);
0 ignored issues
show
Documentation introduced by
The property h_oledrion_manufacturer does not exist on object<OledrionHandler>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
250
                }
251
            }
252
        }
253
    }
254
255
    /**
256
     * Charge la liste des vendeurs associés aux produits
257
     */
258
    private function loadAssociatedVendors()
259
    {
260
        if (count($this->associatedVendors) > 0) {
261
            sort($this->associatedVendors);
262
            $ids                     = $this->associatedVendors;
263
            $this->associatedVendors = $this->handlers->h_oledrion_vendors->getVendorsFromIds($ids);
0 ignored issues
show
Documentation introduced by
The property h_oledrion_vendors does not exist on object<OledrionHandler>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
264
        }
265
    }
266
267
    /**
268
     * Charge les catégories associées aux produits du panier
269
     */
270
    private function loadAssociatedCategories()
271
    {
272
        if (count($this->associatedCategories) > 0) {
273
            sort($this->associatedCategories);
274
            $ids                        = $this->associatedCategories;
275
            $this->associatedCategories = $this->handlers->h_oledrion_cat->getCategoriesFromIds($ids);
0 ignored issues
show
Documentation introduced by
The property h_oledrion_cat does not exist on object<OledrionHandler>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
276
        }
277
    }
278
279
    /**
280
     * Recherche les fabricants, catégories et vendeurs associés à chaque produit
281
     */
282
    public function loadElementsAssociatedToProducts()
283
    {
284
        $this->loadAssociatedManufacturers();
285
        $this->loadAssociatedVendors();
286
        $this->loadAssociatedCategories();
287
    }
288
289
    /**
290
     * Recherche les (objets) produits associés à chaque produit du panier (et lance le calcul des quantités)
291
     */
292
    public function loadProductsAssociatedToCart()
293
    {
294
        $newCart = array();
295
        foreach ($this->cart as $cartProduct) {
296
            $data               = array();
297
            $data['id']         = $cartProduct['id'];
298
            $data['number']     = $cartProduct['number'];
299
            $data['qty']        = $cartProduct['qty'];
300
            $data['attributes'] = $cartProduct['attributes'];
301
302
            $product = null;
0 ignored issues
show
Unused Code introduced by
$product is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
303
            $product = $this->handlers->h_oledrion_products->get($data['id']);
0 ignored issues
show
Documentation introduced by
The property h_oledrion_products does not exist on object<OledrionHandler>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
304
            if (!is_object($product)) {
305
                trigger_error(_OLEDRION_ERROR9);
306
                continue;
307
                // Pour éviter le cas de la suppression d'un produit (dans l'admin) alors qu'un client l'a toujours dans son panier (et donc en session)
308
            }
309
            $data['product'] = $product;
310
            // Mise à jour des calculs par catégorie
311
            $this->computePerCategories($product, $data['qty']);
312
            // Recherche des éléments associés à chaque produit
313
            $this->addAssociatedManufacturers($product);
314
            $this->addAssociatedVendors($product);
315
            $this->addAssociatedAttributes($product, $data['attributes']);
316
            $this->addAssociatedCategories($product);
317
318
            // Calcul du total de la commande avant réductions
319 View Code Duplication
            if ((float)$product->getVar('product_discount_price', 'n') > 0) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
320
                $ht = (float)$product->getVar('product_discount_price', 'n');
321
            } else {
322
                $ht = (float)$product->getVar('product_price', 'n');
323
            }
324
            // S'il y a des options, on rajoute leur montant
325 View Code Duplication
            if (is_array($data['attributes']) && count($data['attributes']) > 0) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
326
                $ht += $this->handlers->h_oledrion_attributes->getProductOptionsPrice($data['attributes'], $product->getVar('product_vat_id'));
0 ignored issues
show
Documentation introduced by
The property h_oledrion_attributes does not exist on object<OledrionHandler>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
327
            }
328
329
            $this->totalAmountBeforeDiscounts += ($data['qty'] * $ht);
330
331
            $newCart[] = $data;
332
        }
333
        $this->loadElementsAssociatedToProducts();
334
        $this->cart = $newCart;
335
    }
336
337
    /**
338
     * Calcul du montant HT auquel on applique un pourcentage de réduction
339
     *
340
     * @param  float   $price    Le prix auquel appliquer la réduction
341
     * @param  integer $discount Le pourcentage de réduction
342
     * @return float   Le montant réduit
343
     */
344
    private function getDiscountedPrice($price, $discount)
345
    {
346
        return (float)($price - ($price * ($discount / 100)));
347
    }
348
349
    /**
350
     * Remise à zéro des membres internes
351
     */
352
    private function initializePrivateData()
353
    {
354
        $this->totalProductsQuantities           = 0;
355
        $this->totalAmountBeforeDiscounts        = 0;
356
        $this->rulesForTheWhole                  = array();
357
        $this->cartForTemplate                   = array();
358
        $this->associatedManufacturers           = array();
359
        $this->associatedVendors                 = array();
360
        $this->associatedCategories              = array();
361
        $this->associatedManufacturersPerProduct = array();
362
        $this->associatedAttributesPerProduct    = array();
363
    }
364
365
    /**
366
     * Calcul de la facture en fonction du panier
367
     * Contenu du panier en session :
368
     *
369
     *  $datas['number'] = Indice du produit dans le panier
370
     *  $datas['id'] = Identifiant du produit dans la base
371
     *  $datas['qty'] = Quantité voulue
372
     *  $datas['attributes'] = Attributs produit array('attr_id' => id attribut, 'values' => array(valueId1, valueId2 ...))
373
     *
374
     * En variable privé, le panier (dans $cart) contient la même chose + un objet 'oledrion_products' dans la clé 'product'
375
     *
376
     * @param array   $cartForTemplate      Contenu du caddy à passer au template (en fait la liste des produits)
377
     * @param         boolean               emptyCart Indique si le panier est vide ou pas
378
     * @param float   $shippingAmount       Montant des frais de port
379
     * @param float   $commandAmount        Montant HT de la commande
380
     * @param float   $vatAmount            Montant de la TVA
381
     * @param string  $goOn                 Adresse vers laquelle renvoyer le visiteur après qu'il ait ajouté un produit dans son panier (cela correspond en fait à la catégorie du dernier produit ajouté dans le panier)
382
     * @param float   $commandAmountTTC     Montant TTC de la commande
383
     * @param array   $discountsDescription Descriptions des remises GLOBALES appliquées (et pas les remises par produit !)
384
     * @param integer $discountsCount       Le nombre TOTAL de réductions appliquées (individuellement ou sur la globalité du panier)
385
     *
386
     * TODO: Passer les paramètres sous forme d'objet
387
     * @return bool
388
     */
389
    public function computeCart(
0 ignored issues
show
Coding Style introduced by
computeCart uses the super-global variable $_SESSION which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
Coding Style introduced by
computeCart uses the super-global variable $_POST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
390
        &$cartForTemplate,
391
        &$emptyCart,
392
        &$shippingAmount,
393
        &$commandAmount,
394
        &$vatAmount,
395
        &$goOn,
396
        &$commandAmountTTC,
397
        &$discountsDescription,
398
        &$discountsCount
399
    ) {
400
        $emptyCart      = false;
401
        $goOn           = '';
402
        $vats           = array();
0 ignored issues
show
Unused Code introduced by
$vats is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
403
        $cpt            = 0;
404
        $discountsCount = 0;
405
        $this->cart     = isset($_SESSION[OledrionOledrion_caddyHandler::CADDY_NAME]) ? $_SESSION[OledrionOledrion_caddyHandler::CADDY_NAME] : array();
406
        $cartCount      = count($this->cart);
407
        if ($cartCount == 0) {
408
            $emptyCart = true;
409
410
            return true;
411
        }
412
413
        // Réinitialisation des données privées
414
        $this->initializePrivateData();
415
        // Chargement des objets produits associés aux produits du panier et calcul des quantités par catégorie
416
        $this->loadProductsAssociatedToCart();
417
        // Chargement des TVA
418
        if (!isset($_POST['cmd_country']) || empty($_POST['cmd_country'])) {
419
            $_POST['cmd_country'] = OLEDRION_DEFAULT_COUNTRY;
420
        }
421
        $vats              = $this->handlers->h_oledrion_vat->getCountryVats($_POST['cmd_country']);
0 ignored issues
show
Documentation introduced by
The property h_oledrion_vat does not exist on object<OledrionHandler>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
422
        $oledrion_Currency = &Oledrion_Currency::getInstance();
423
        $caddyCount        = count($this->cart);
424
425
        // Initialisation des totaux généraux (ht, tva et frais de port)
426
        $totalHT = $totalVAT = $totalShipping = 0.0;
427
428
        // Boucle sur tous les produits et sur chacune des règles pour calculer le prix du produit (et ses frais de port) et voir si on doit y appliquer une réduction
429
        foreach ($this->cart as $cartProduct) {
430
            if ((float)$cartProduct['product']->getVar('product_discount_price', 'n') > 0) {
431
                $ht = (float)$cartProduct['product']->getVar('product_discount_price', 'n');
432
            } else {
433
                $ht = (float)$cartProduct['product']->getVar('product_price', 'n');
434
            }
435
            // S'il y a des options, on rajoute leur montant
436
            $productAttributes = array();
437 View Code Duplication
            if (is_array($cartProduct['attributes']) && count($cartProduct['attributes']) > 0) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
438
                $ht += $this->handlers->h_oledrion_attributes->getProductOptionsPrice($cartProduct['attributes'], $cartProduct['product']->getVar('product_vat_id'), $productAttributes);
0 ignored issues
show
Documentation introduced by
The property h_oledrion_attributes does not exist on object<OledrionHandler>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
439
            }
440
441
            $discountedPrice = $ht;
442
            $quantity        = (int)$cartProduct['qty'];
443
444
            if (Oledrion_utils::getModuleOption('shipping_quantity')) {
445
                $discountedShipping = (float)($cartProduct['product']->getVar('product_shipping_price', 'n') * $quantity);
446
            } else {
447
                $discountedShipping = (float)$cartProduct['product']->getVar('product_shipping_price', 'n');
448
            }
449
            $totalPrice = 0.0;
0 ignored issues
show
Unused Code introduced by
$totalPrice is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
450
            $reduction  = '';
451
452
            ++$cpt;
453
            if ($cpt == $caddyCount) {
454
                // On arrive sur le dernier produit
455
                $category = null;
0 ignored issues
show
Unused Code introduced by
$category is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
456
                $category = $this->handlers->h_oledrion_cat->get($cartProduct['product']->getVar('product_cid'));
0 ignored issues
show
Documentation introduced by
The property h_oledrion_cat does not exist on object<OledrionHandler>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
457
                if (is_object($category)) {
458
                    $goOn = $category->getLink();
459
                }
460
            }
461
462
            // Boucle sur les règles
463
            foreach ($this->allActiveRules as $rule) {
464
                $applyRule = false;
465
                if (($rule->disc_group != 0 && Oledrion_utils::isMemberOfGroup($rule->disc_group))
466
                    || $rule->disc_group == 0
467
                ) {
468
                    if (($rule->disc_cat_cid != 0
469
                         && $cartProduct['product']->getVar('product_cid') == $rule->disc_cat_cid)
470
                        || $rule->disc_cat_cid == 0
471
                    ) {
472
                        if (($rule->disc_vendor_id != 0
473
                             && $cartProduct['product']->getVar('disc_vendor_id') == $rule->disc_vendor_id)
474
                            || $rule->disc_vendor_id == 0
475
                        ) {
476
                            if (($rule->disc_product_id != 0
477
                                 && $cartProduct['product']->getVar('product_id') == $rule->disc_product_id)
478
                                || $rule->disc_product_id == 0
479
                            ) {
480
                                // Dans quel cas appliquer la réduction ?
481
                                switch ($rule->disc_price_case) {
482
                                    case OLEDRION_DISCOUNT_PRICE_CASE_ALL :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
483
                                        // Dans tous les cas
484
                                        $applyRule = true;
485
                                        break;
486
                                    case OLEDRION_DISCOUNT_PRICE_CASE_FIRST_BUY :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
487
                                        // Si c'est le premier achat de l'utilisateur sur le site
488
                                        if ($this->handlers->h_oledrion_commands->isFirstCommand()) {
0 ignored issues
show
Documentation introduced by
The property h_oledrion_commands does not exist on object<OledrionHandler>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
489
                                            $applyRule = true;
490
                                        }
491
                                        break;
492
                                    case OLEDRION_DISCOUNT_PRICE_CASE_PRODUCT_NEVER :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
493
                                        // Si le produit n'a jamais été acheté par le client
494
                                        if (!$this->handlers->h_oledrion_commands->productAlreadyBought(0, $cartProduct['product']->getVar('product_id'))) {
0 ignored issues
show
Documentation introduced by
The property h_oledrion_commands does not exist on object<OledrionHandler>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
495
                                            $applyRule = true;
496
                                        }
497
                                        break;
498
                                    case OLEDRION_DISCOUNT_PRICE_CASE_QTY_IS :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
499
                                        // Si la quantité de produit est ... à ...
500
                                        switch ($rule->disc_price_case_qty_cond) {
501
                                            case OLEDRION_DISCOUNT_PRICE_QTY_COND1 :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
502
                                                // >
503
                                                if ($cartProduct['qty'] > $rule->disc_price_case_qty_value) {
504
                                                    $applyRule = true;
505
                                                }
506
                                                break;
507
                                            case OLEDRION_DISCOUNT_PRICE_QTY_COND2 :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
508
                                                // >=
509
                                                if ($cartProduct['qty'] >= $rule->disc_price_case_qty_value) {
510
                                                    $applyRule = true;
511
                                                }
512
                                                break;
513
                                            case OLEDRION_DISCOUNT_PRICE_QTY_COND3 :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
514
                                                // <
515
                                                if ($cartProduct['qty'] < $rule->disc_price_case_qty_value) {
516
                                                    $applyRule = true;
517
                                                }
518
                                                break;
519
                                            case OLEDRION_DISCOUNT_PRICE_QTY_COND4 :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
520
                                                // <=
521
                                                if ($cartProduct['qty'] <= $rule->disc_price_case_qty_value) {
522
                                                    $applyRule = true;
523
                                                }
524
                                                break;
525
                                            case OLEDRION_DISCOUNT_PRICE_QTY_COND5 :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
526
                                                // ==
527
                                                if ($cartProduct['qty'] == $rule->disc_price_case_qty_value) {
528
                                                    $applyRule = true;
529
                                                }
530
                                                break;
531
                                        }
532
                                }
533
                            }
534
                        }
535
                    }
536
                }
537
                if ($applyRule) {
538
                    // Il faut appliquer la règle
539
                    // On calcule le nouveau prix ht du produit
540
                    switch ($rule->disc_price_type) {
541
                        case OLEDRION_DISCOUNT_PRICE_TYPE1 :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
542
                            // Montant dégressif selon les quantités
543
                            if ($quantity >= $rule->disc_price_degress_l1qty1
544
                                && $quantity <= $rule->disc_price_degress_l1qty2
545
                            ) {
546
                                $discountedPrice = (float)$rule->getVar('disc_price_degress_l1total', 'n');
547
                            }
548
                            if ($quantity >= $rule->disc_price_degress_l2qty1
549
                                && $quantity <= $rule->disc_price_degress_l2qty2
550
                            ) {
551
                                $discountedPrice = (float)$rule->getVar('disc_price_degress_l2total', 'n');
552
                            }
553
                            if ($quantity >= $rule->disc_price_degress_l3qty1
554
                                && $quantity <= $rule->disc_price_degress_l3qty2
555
                            ) {
556
                                $discountedPrice = (float)$rule->getVar('disc_price_degress_l3total', 'n');
557
                            }
558
                            if ($quantity >= $rule->disc_price_degress_l4qty1
559
                                && $quantity <= $rule->disc_price_degress_l4qty2
560
                            ) {
561
                                $discountedPrice = (float)$rule->getVar('disc_price_degress_l4total', 'n');
562
                            }
563
                            if ($quantity >= $rule->disc_price_degress_l5qty1
564
                                && $quantity <= $rule->disc_price_degress_l5qty2
565
                            ) {
566
                                $discountedPrice = (float)$rule->getVar('disc_price_degress_l5total', 'n');
567
                            }
568
                            $reduction = $rule->disc_description;
569
                            ++$discountsCount;
570
                            break;
571
572
                        case OLEDRION_DISCOUNT_PRICE_TYPE2 :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
573
                            // D'un montant ou d'un pourcentage
574
                            if ($rule->disc_price_amount_on == OLEDRION_DISCOUNT_PRICE_AMOUNT_ON_PRODUCT) {
575
                                // Réduction sur le produit
576
                                if ($rule->disc_price_amount_type == OLEDRION_DISCOUNT_PRICE_REDUCE_PERCENT) {
577
                                    // Réduction en pourcentage
578
                                    $discountedPrice = $this->getDiscountedPrice($discountedPrice, $rule->getVar('disc_price_amount_amount', 'n'));
579
                                } elseif ($rule->disc_price_amount_type == OLEDRION_DISCOUNT_PRICE_REDUCE_MONEY) {
580
                                    // Réduction d'un montant en euros
581
                                    $discountedPrice -= (float)$rule->getVar('disc_price_amount_amount', 'n');
582
                                }
583
584
                                // Pas de montants négatifs
585
                                Oledrion_utils::doNotAcceptNegativeAmounts($discountedPrice);
586
                                $reduction = $rule->disc_description;
587
                                ++$discountsCount;
588
                            } elseif ($rule->disc_price_amount_on == OLEDRION_DISCOUNT_PRICE_AMOUNT_ON_CART) {
589
                                // Règle à appliquer sur le panier
590
                                if (!isset($this->rulesForTheWhole[$rule->disc_id])) {
591
                                    $this->rulesForTheWhole[$rule->disc_id] = $rule;
592
                                }
593
                            }
594
                            break;
595
                    }
596
597
                    // On passe au montant des frais de port
598
                    switch ($rule->disc_shipping_type) {
599
                        case OLEDRION_DISCOUNT_SHIPPING_TYPE1 :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
600
                            // A payer dans leur intégralité, rien à faire
601
                            break;
602
                        case OLEDRION_DISCOUNT_SHIPPING_TYPE2 :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
603
                            // Totalement gratuits si le client commande plus de X euros d'achat
604
                            if ($this->totalAmountBeforeDiscounts > $rule->disc_shipping_free_morethan) {
605
                                $discountedShipping = 0.0;
606
                            }
607
                            break;
608
                        case OLEDRION_DISCOUNT_SHIPPING_TYPE3 :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
609
                            // Frais de port réduits de X euros si la commande est > x
610
                            if ($this->totalAmountBeforeDiscounts > $rule->disc_shipping_reduce_cartamount) {
611
                                $discountedShipping -= (float)$rule->getVar('disc_shipping_reduce_amount', 'n');
612
                            }
613
                            // Pas de montants négatifs
614
                            Oledrion_utils::doNotAcceptNegativeAmounts($discountedShipping);
615
                            break;
616
                        case OLEDRION_DISCOUNT_SHIPPING_TYPE4 :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
617
                            // Frais de port dégressifs
618
                            if ($quantity >= $rule->disc_shipping_degress_l1qty1
619
                                && $quantity <= $rule->disc_shipping_degress_l1qty2
620
                            ) {
621
                                $discountedShipping = (float)$rule->getVar('disc_shipping_degress_l1total', 'n');
622
                            }
623
                            if ($quantity >= $rule->disc_shipping_degress_l2qty1
624
                                && $quantity <= $rule->disc_shipping_degress_l2qty2
625
                            ) {
626
                                $discountedShipping = (float)$rule->getVar('disc_shipping_degress_l2total', 'n');
627
                            }
628
                            if ($quantity >= $rule->disc_shipping_degress_l3qty1
629
                                && $quantity <= $rule->disc_shipping_degress_l3qty2
630
                            ) {
631
                                $discountedShipping = (float)$rule->getVar('disc_shipping_degress_l3total', 'n');
632
                            }
633
                            if ($quantity >= $rule->disc_shipping_degress_l4qty1
634
                                && $quantity <= $rule->disc_shipping_degress_l4qty2
635
                            ) {
636
                                $discountedShipping = (float)$rule->getVar('disc_shipping_degress_l4total', 'n');
637
                            }
638
                            if ($quantity >= $rule->disc_shipping_degress_l5qty1
639
                                && $quantity <= $rule->disc_shipping_degress_l5qty2
640
                            ) {
641
                                $discountedShipping = (float)$rule->getVar('disc_shipping_degress_l5total', 'n');
642
                            }
643
                            break;
644
                    }    // Sélection du type de réduction sur les frais de port
645
                }    // Il faut appliquer la règle de réduction
646
            }// Boucle sur les réductions
647
648
            // Calcul de la TVA du produit
649
            $vatId = $cartProduct['product']->getVar('product_vat_id');
650
            if (is_array($vats) && isset($vats[$vatId])) {
651
                $vatRate   = (float)$vats[$vatId]->getVar('vat_rate', 'n');
652
                $vatAmount = Oledrion_utils::getVAT($discountedPrice * $quantity, $vatRate);
653
            } else {
654
                $vatRate   = 0.0;
655
                $vatAmount = 0.0;
656
            }
657
658
            // Calcul du TTC du produit ((ht * qte) + tva + frais de port)
659
            $totalPrice = (float)(($discountedPrice * $quantity) + $vatAmount + $discountedShipping);
660
661
            // Les totaux généraux
662
            $totalHT += ($discountedPrice * $quantity);
663
            $totalVAT += $vatAmount;
664
            $totalShipping += $discountedShipping;
665
666
            // Recherche des éléments associés au produit
667
            $associatedVendor      = $associatedCategory = $associatedManufacturers = array();
668
            $manufacturersJoinList = '';
669
            // Le vendeur
670
            if (isset($this->associatedVendors[$cartProduct['product']->product_vendor_id])) {
671
                $associatedVendor = $this->associatedVendors[$cartProduct['product']->product_vendor_id]->toArray();
672
            }
673
674
            // La catégorie
675
            if (isset($this->associatedCategories[$cartProduct['product']->product_cid])) {
676
                $associatedCategory = $this->associatedCategories[$cartProduct['product']->product_cid]->toArray();
677
            }
678
679
            // Les fabricants
680
            $product_id = $cartProduct['product']->product_id;
681
            if (isset($this->associatedManufacturersPerProduct[$product_id])) {
682
                // Recherche de la liste des fabricants associés à ce produit
683
                $manufacturers     = $this->associatedManufacturersPerProduct[$product_id];
684
                $manufacturersList = array();
685
                foreach ($manufacturers as $manufacturer_id) {
686
                    if (isset($this->associatedManufacturers[$manufacturer_id])) {
687
                        $associatedManufacturers[] = $this->associatedManufacturers[$manufacturer_id]->toArray();
688
                    }
689
                    $manufacturersList[] = $this->associatedManufacturers[$manufacturer_id]->manu_commercialname . ' ' . $this->associatedManufacturers[$manufacturer_id]->manu_name;
690
                }
691
                $manufacturersJoinList = implode(OLEDRION_STRING_TO_JOIN_MANUFACTURERS, $manufacturersList);
692
            }
693
            $productTemplate                = array();
0 ignored issues
show
Unused Code introduced by
$productTemplate is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
694
            $productTemplate                = $cartProduct['product']->toArray();
695
            $productTemplate['attributes']  = $productAttributes;
696
            $productTemplate['number']      = $cartProduct['number'];
697
            $productTemplate['id']          = $cartProduct['id'];
698
            $productTemplate['product_qty'] = $cartProduct['qty'];
699
700
            $productTemplate['unitBasePrice'] = $ht;
701
            // Prix unitaire HT SANS réduction
702
            $productTemplate['discountedPrice'] = $discountedPrice;
703
            // Prix unitaire HT AVEC réduction
704
            $productTemplate['discountedPriceWithQuantity'] = $discountedPrice * $quantity;
705
            // Prix HT AVEC réduction et la quantité
706
            // Les même prix mais formatés
707
            $productTemplate['unitBasePriceFormated'] = $oledrion_Currency->amountForDisplay($ht);
708
            // Prix unitaire HT SANS réduction
709
            $productTemplate['discountedPriceFormated'] = $oledrion_Currency->amountForDisplay($discountedPrice);
710
            // Prix unitaire HT AVEC réduction
711
            $productTemplate['discountedPriceWithQuantityFormated'] = $oledrion_Currency->amountForDisplay($discountedPrice * $quantity);
712
            // Prix HT AVEC réduction et la quantité
713
714
            // Add by voltan
715
            $productTemplate['discountedPriceFormatedOrg'] = $oledrion_Currency->amountForDisplay($ht - $discountedPrice);
716
            $productTemplate['discountedPriceOrg']         = $ht - $discountedPrice;
717
718
            $productTemplate['vatRate']            = $oledrion_Currency->amountInCurrency($vatRate);
719
            $productTemplate['vatAmount']          = $vatAmount;
720
            $productTemplate['normalShipping']     = $cartProduct['product']->getVar('product_shipping_price', 'n');
721
            $productTemplate['discountedShipping'] = $discountedShipping;
722
            $productTemplate['totalPrice']         = $totalPrice;
723
            $productTemplate['reduction']          = $reduction;
724
            $productTemplate['templateProduct']    = $cartProduct['product']->toArray();
725
726
            $productTemplate['vatAmountFormated']          = $oledrion_Currency->amountInCurrency($vatAmount);
727
            $productTemplate['normalShippingFormated']     = $oledrion_Currency->amountForDisplay($cartProduct['product']->getVar('product_shipping_price', 'n'));
728
            $productTemplate['discountedShippingFormated'] = $oledrion_Currency->amountForDisplay($discountedShipping);
729
            $productTemplate['totalPriceFormated']         = $oledrion_Currency->amountInCurrency($totalPrice);
730
            $productTemplate['templateCategory']           = $associatedCategory;
731
            $productTemplate['templateVendor']             = $associatedVendor;
732
            $productTemplate['templateManufacturers']      = $associatedManufacturers;
733
            $productTemplate['manufacturersJoinList']      = $manufacturersJoinList;
734
            $this->cartForTemplate[]                       = $productTemplate;
735
        }// foreach sur les produits du panier
736
737
        // Traitement des règles générales s'il y en a
738
        if (count($this->rulesForTheWhole) > 0) {
739
            // $discountsDescription
740
            foreach ($this->rulesForTheWhole as $rule) {
741
                switch ($rule->disc_price_type) {
742
                    case OLEDRION_DISCOUNT_PRICE_TYPE2 :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
743
                        // D'un montant ou d'un pourcentage
744
                        if ($rule->disc_price_amount_on == OLEDRION_DISCOUNT_PRICE_AMOUNT_ON_CART) {
745
                            // Règle à appliquer sur le panier
746
                            if ($rule->disc_price_amount_type == OLEDRION_DISCOUNT_PRICE_REDUCE_PERCENT) {
747
                                // Réduction en pourcentage
748
                                $totalHT  = $this->getDiscountedPrice($totalHT, $rule->getVar('disc_price_amount_amount'));
749
                                $totalVAT = $this->getDiscountedPrice($totalVAT, $rule->getVar('disc_price_amount_amount'));
750
                            } elseif ($rule->disc_price_amount_type == OLEDRION_DISCOUNT_PRICE_REDUCE_MONEY) {
751
                                // Réduction d'un montant en euros
752
                                $totalHT -= (float)$rule->getVar('disc_price_amount_amount');
753
                                $totalVAT -= (float)$rule->getVar('disc_price_amount_amount');
754
                            }
755
756
                            // Pas de montants négatifs
757
                            Oledrion_utils::doNotAcceptNegativeAmounts($totalHT);
758
                            Oledrion_utils::doNotAcceptNegativeAmounts($totalVAT);
759
                            $discountsDescription[] = $rule->disc_description;
760
                            ++$discountsCount;
761
                        }// Règle à appliquer sur le panier
762
                        break;
763
                }    // Switch
764
            }    // Foreach
765
        }// S'il y a des règles globales
766
        // Les totaux "renvoyés" à l'appelant
767
        $shippingAmount = $totalShipping;
768
        $commandAmount  = $totalHT;
769
770
        $vatAmount        = $totalVAT;
771
        $commandAmountTTC = $totalHT + $totalVAT + $totalShipping;
772
773
        $cartForTemplate = $this->cartForTemplate;
774
775
        return true;
776
    }
777
}
778