Completed
Push — master ( 1db5db...8743f5 )
by Michael
06:44
created

bookshop_books::__construct()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 41
Code Lines 38

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 38
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 41
rs 8.8571
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 37 and the first side effect is on line 27.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
//  ------------------------------------------------------------------------ //
3
//                      BOOKSHOP - MODULE FOR XOOPS 2                        //
4
//                  Copyright (c) 2007, 2008 Instant Zero                    //
5
//                     <http://www.instant-zero.com/>                        //
6
// ------------------------------------------------------------------------- //
7
//  This program is free software; you can redistribute it and/or modify     //
8
//  it under the terms of the GNU General Public License as published by     //
9
//  the Free Software Foundation; either version 2 of the License, or        //
10
//  (at your option) any later version.                                      //
11
//                                                                           //
12
//  You may not change or alter any portion of this comment or credits       //
13
//  of supporting developers from this source code or any supporting         //
14
//  source code which is considered copyrighted (c) material of the          //
15
//  original comment or credit authors.                                      //
16
//                                                                           //
17
//  This program is distributed in the hope that it will be useful,          //
18
//  but WITHOUT ANY WARRANTY; without even the implied warranty of           //
19
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            //
20
//  GNU General Public License for more details.                             //
21
//                                                                           //
22
//  You should have received a copy of the GNU General Public License        //
23
//  along with this program; if not, write to the Free Software              //
24
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA //
25
//  ------------------------------------------------------------------------ //
26
27
defined('XOOPS_ROOT_PATH') || exit('XOOPS root path not defined');
28
29
include_once XOOPS_ROOT_PATH . '/kernel/object.php';
30
if (!class_exists('Bookshop_XoopsPersistableObjectHandler')) {
31
    include_once XOOPS_ROOT_PATH . '/modules/bookshop/class/PersistableObjectHandler.php';
32
}
33
34
/**
35
 * Class bookshop_books
36
 */
37
class bookshop_books extends Bookshop_Object
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...
38
{
39
    public function __construct()
40
    {
41
        $this->initVar('book_id', XOBJ_DTYPE_INT, null, false);
42
        $this->initVar('book_cid', XOBJ_DTYPE_INT, null, false);
43
        $this->initVar('book_title', XOBJ_DTYPE_TXTBOX, null, false);
44
        $this->initVar('book_lang_id', XOBJ_DTYPE_INT, null, false);
45
        $this->initVar('book_number', XOBJ_DTYPE_TXTBOX, null, false);
46
        $this->initVar('book_tome', XOBJ_DTYPE_TXTBOX, null, false);
47
        $this->initVar('book_format', XOBJ_DTYPE_TXTBOX, null, false);
48
        $this->initVar('book_url', XOBJ_DTYPE_TXTBOX, null, false);
49
        $this->initVar('book_image_url', XOBJ_DTYPE_TXTBOX, null, false);
50
        $this->initVar('book_thumb_url', XOBJ_DTYPE_TXTBOX, null, false);
51
        $this->initVar('book_submitter', XOBJ_DTYPE_INT, null, false);
52
        $this->initVar('book_online', XOBJ_DTYPE_INT, null, false);
53
        $this->initVar('book_date', XOBJ_DTYPE_TXTBOX, null, false);
54
        $this->initVar('book_submitted', XOBJ_DTYPE_INT, null, false);
55
        $this->initVar('book_hits', XOBJ_DTYPE_INT, null, false);
56
        $this->initVar('book_rating', XOBJ_DTYPE_INT, null, false);
57
        $this->initVar('book_votes', XOBJ_DTYPE_INT, null, false);
58
        $this->initVar('book_comments', XOBJ_DTYPE_INT, null, false);
59
        $this->initVar('book_price', XOBJ_DTYPE_TXTBOX, null, false);
60
        $this->initVar('book_shipping_price', XOBJ_DTYPE_TXTBOX, null, false);
61
        $this->initVar('book_discount_price', XOBJ_DTYPE_TXTBOX, null, false);
62
        $this->initVar('book_stock', XOBJ_DTYPE_INT, null, false);
63
        $this->initVar('book_alert_stock', XOBJ_DTYPE_INT, null, false);
64
        $this->initVar('book_summary', XOBJ_DTYPE_TXTAREA, null, false);
65
        $this->initVar('book_description', XOBJ_DTYPE_TXTAREA, null, false);
66
        $this->initVar('book_attachment', XOBJ_DTYPE_TXTBOX, null, false);
67
        $this->initVar('book_isbn', XOBJ_DTYPE_TXTBOX, null, false);
68
        $this->initVar('book_ean', XOBJ_DTYPE_TXTBOX, null, false);
69
        $this->initVar('book_vat_id', XOBJ_DTYPE_INT, null, false);
70
        $this->initVar('book_pages', XOBJ_DTYPE_INT, null, false);
71
        $this->initVar('book_pages_collection', XOBJ_DTYPE_INT, null, false);
72
        $this->initVar('book_volumes_count', XOBJ_DTYPE_INT, null, false);
73
        $this->initVar('book_recommended', XOBJ_DTYPE_TXTBOX, null, false);
74
        $this->initVar('book_metakeywords', XOBJ_DTYPE_TXTBOX, null, false);
75
        $this->initVar('book_metadescription', XOBJ_DTYPE_TXTBOX, null, false);
76
        $this->initVar('book_metatitle', XOBJ_DTYPE_TXTBOX, null, false);
77
        // Pour autoriser le html
78
        $this->initVar('dohtml', XOBJ_DTYPE_INT, 1, false);
79
    }
80
81
    /**
82
	 * Indique si le livre courant est recommandé.
83
     *
84
     * @param bool $withDescription
85
     *
86
     * @return bool|string
87
     */
88
    public function isRecommended($withDescription = false)
89
    {
90
        if ($this->getVar('book_recommended') != '0000-00-00') {
91
            return $withDescription ? _YES : true;
92
        } else {
93
            return $withDescription ? _NO : false;
94
        }
95
    }
96
97
    /**
98
	 * Place le livre courant dans l'état "recommandé"
99
     */
100
    public function setRecommended()
101
    {
102
        $this->setVar('book_recommended', date('Y-m-d'));
103
    }
104
105
    /**
106
	 * Enlève "l'attribut" recommandé d'un livre
107
     */
108
    public function unsetRecommended()
109
    {
110
        $this->setVar('book_recommended', '0000-00-00');
111
    }
112
113
    /**
114
	 * Renvoie l'image qui indique si le livre est recommandé ou pas.
115
     */
116
    public function recommendedPicture()
117
    {
118
        if ($this->isRecommended()) {
119
            return "<img src='" . BOOKSHOP_IMAGES_URL . "heart.png' alt='" . _BOOKSHOP_IS_RECOMMENDED . "' />&nbsp;";
120
        } else {
121
            return "<img src='" . BOOKSHOP_IMAGES_URL . "blank.gif' alt='' />";
122
        }
123
    }
124
125
    /**
126
     * @param string $format
127
     *
128
     * @return array
129
     */
130
    public function toArray($format = 's')
131
    {
132
        $ret = array();
133
        foreach ($this->vars as $k => $v) {
134
            $ret[$k] = $this->getVar($k, $format);
135
        }
136
        $ret['book_tooltip']             = bookshop_make_infotips($this->getVar('book_description'));
137
        $ret['book_url_rewrited']        = BookshopBookshop_booksHandler::GetBookLink($this->getVar('book_id'), $this->getVar('book_title'));
138
        $ret['book_href_title']          = bookshop_makeHrefTitle($this->getVar('book_title'));
139
        $ret['book_recommended']         = $this->isRecommended();
140
        $ret['book_recommended_picture'] = $this->recommendedPicture();
141
142
        return $ret;
143
    }
144
}
145
146
/**
147
 * Class BookshopBookshop_booksHandler
148
 */
149
class BookshopBookshop_booksHandler extends Bookshop_XoopsPersistableObjectHandler
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
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...
150
{
151
    /**
152
     * @param $db
153
     */
154
    public function __construct($db)
155
    {    //                                             Table               Classe           Id
156
        parent::__construct($db, 'bookshop_books', 'bookshop_books', 'book_id');
157
    }
158
159
    /**
160
     * Renvoie la liste des x livres les plus vus par les visiteurs
161
     *
162
	 * @param integer $start		Début des données
163
	 * @param integer $limit		Nombre maximum d'enregistrements à renvoyer
164
	 * @param integer $category Identifiant de la catégorie (évenutellement)
165
     * @return array   Tableau de livres (sous la forme d'objets)
166
     */
167 View Code Duplication
    public function getMostViewedBooks($start = 0, $limit = 0, $category = 0)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
168
    {
169
        $tbl_datas = array();
170
        $criteria  = new CriteriaCompo();
171
        $criteria->add(new Criteria('book_online', 1, '='));
172
		if(bookshop_getmoduleoption('show_unpublished') == 0) {	// Ne pas afficher les livres qui ne sont pas publiés
173
            $criteria->add(new Criteria('book_submitted', time(), '<='));
174
        }
175
        if (bookshop_getmoduleoption('nostock_display') == 0) {    // Se limiter aux seuls livres encore en stock
176
            $criteria->add(new Criteria('book_stock', 0, '>'));
177
        }
178
        if (is_array($category)) {
179
            $criteria->add(new Criteria('book_cid', '(' . implode(',', $category) . ')', 'IN'));
180
        } elseif ($category != 0) {
181
            $criteria->add(new Criteria('book_cid', (int)$category, '='));
182
        }
183
		// On se limite aux livres qui ont été vraiment vus !
184
        $criteria->add(new Criteria('book_hits', 0, '>'));
185
        $criteria->setLimit($limit);
186
        $criteria->setStart($start);
187
        $criteria->setSort('book_hits');
188
        $criteria->setOrder('DESC');
189
        $tbl_datas =& $this->getObjects($criteria, true);
190
191
        return $tbl_datas;
192
    }
193
194
    /**
195
	 * Renvoie la liste des x livres les mieux notés par les visiteurs
196
     *
197
	 * @param integer $start		Début des données
198
	 * @param integer $limit		Nombre maximum d'enregistrements à renvoyer
199
	 * @param integer $category Identifiant de la catégorie (évenutellement)
200
     * @return array   Tableau de livres (sous la forme d'objets)
201
     */
202 View Code Duplication
    public function getBestRatedBooks($start = 0, $limit = 0, $category = 0)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
203
    {
204
        $tbl_datas = array();
205
        $criteria  = new CriteriaCompo();
206
        $criteria->add(new Criteria('book_online', 1, '='));
207
		if(bookshop_getmoduleoption('show_unpublished') == 0) {	// Ne pas afficher les livres qui ne sont pas publiés
208
            $criteria->add(new Criteria('book_submitted', time(), '<='));
209
        }
210
        if (bookshop_getmoduleoption('nostock_display') == 0) {    // Se limiter aux seuls livres encore en stock
211
            $criteria->add(new Criteria('book_stock', 0, '>'));
212
        }
213
        if (is_array($category)) {
214
            $criteria->add(new Criteria('book_cid', '(' . implode(',', $category) . ')', 'IN'));
215
        } elseif ($category != 0) {
216
            $criteria->add(new Criteria('book_cid', (int)$category, '='));
217
        }
218
        $criteria->setLimit($limit);
219
        $criteria->setStart($start);
220
        $criteria->setSort('book_rating');
221
        $criteria->setOrder('DESC');
222
        $tbl_datas =& $this->getObjects($criteria, true);
223
224
        return $tbl_datas;
225
    }
226
227
    /**
228
	 * Renvoie la liste des x derniers livres recommandés
229
     *
230
	 * @param integer $start		Indice de départ
231
	 * @param integer $limit		Nombre maximum d'enregistrements à renvoyer
232
	 * @param integer $category Identifiant de la catégorie (évenutellement)
233
     * @return array   Tableau de livres (sous la forme d'objets)
234
     */
235 View Code Duplication
    public function getRecentRecommendedBooks($start = 0, $limit = 0, $category = 0)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
236
    {
237
        $tbl_datas = array();
238
        $criteria  = new CriteriaCompo();
239
        $criteria->add(new Criteria('book_online', 1, '='));
240
        $criteria->add(new Criteria('book_recommended', '0000-00-00', '<>'));
241
		if(bookshop_getmoduleoption('show_unpublished') == 0) {	// Ne pas afficher les livres qui ne sont pas publiés
242
            $criteria->add(new Criteria('book_submitted', time(), '<='));
243
        }
244
        if (bookshop_getmoduleoption('nostock_display') == 0) {    // Se limiter aux seuls livres encore en stock
245
            $criteria->add(new Criteria('book_stock', 0, '>'));
246
        }
247
        if (is_array($category)) {
248
            $criteria->add(new Criteria('book_cid', '(' . implode(',', $category) . ')', 'IN'));
249
        } elseif ($category != 0) {
250
            $criteria->add(new Criteria('book_cid', (int)$category, '='));
251
        }
252
        $criteria->setLimit($limit);
253
        $criteria->setStart($start);
254
        $criteria->setSort('book_recommended');
255
        $criteria->setOrder('DESC');
256
        $tbl_datas =& $this->getObjects($criteria, true);
257
258
        return $tbl_datas;
259
    }
260
261
    /**
262
	 * Renvoie le nombre total de livres recommandés
263
     *
264
	 * @return integer Le nombre total de livres recommandés
265
     */
266 View Code Duplication
    public function getRecommendedCount()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
267
    {
268
        $criteria = new CriteriaCompo();
269
        $criteria->add(new Criteria('book_online', 1, '='));
270
        $criteria->add(new Criteria('book_recommended', '0000-00-00', '<>'));
271
		if(bookshop_getmoduleoption('show_unpublished') == 0) {	// Ne pas afficher les livres qui ne sont pas publiés
272
            $criteria->add(new Criteria('book_submitted', time(), '<='));
273
        }
274
        if (bookshop_getmoduleoption('nostock_display') == 0) {    // Se limiter aux seuls livres encore en stock
275
            $criteria->add(new Criteria('book_stock', 0, '>'));
276
        }
277
278
        return $this->getCount($criteria);
279
    }
280
281
    /**
282
	 * Renvoie la liste des x derniers livres parus toutes catégories confondues ou dans une catégorie spécifique
283
     *
284
	 * @param integer $start		Début des données
285
	 * @param integer $limit		Nombre maximum d'enregistrements à renvoyer
286
	 * @param integer $category Identifiant de la catégorie (évenutellement)
287
     * @param  string  $sortField
288
     * @return array   Tableau de livres (sous la forme d'objets)
289
     */
290 View Code Duplication
    public function getRecentBooks($start = 0, $limit = 0, $category = 0, $sortField = 'book_submitted DESC, book_title')
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
291
    {
292
        $tbl_datas = array();
293
        $criteria  = new CriteriaCompo();
294
        $criteria->add(new Criteria('book_online', 1, '='));
295
		if(bookshop_getmoduleoption('show_unpublished') == 0) {	// Ne pas afficher les livres qui ne sont pas publiés
296
            $criteria->add(new Criteria('book_submitted', time(), '<='));
297
        }
298
        if (bookshop_getmoduleoption('nostock_display') == 0) {    // Se limiter aux seuls livres encore en stock
299
            $criteria->add(new Criteria('book_stock', 0, '>'));
300
        }
301
        if (is_array($category)) {
302
            $criteria->add(new Criteria('book_cid', '(' . implode(',', $category) . ')', 'IN'));
303
        } elseif ($category > 0) {
304
            $criteria->add(new Criteria('book_cid', (int)$category, '='));
305
        }
306
        $criteria->setLimit($limit);
307
        $criteria->setStart($start);
308
        $criteria->setSort($sortField);
309
        $tbl_datas =& $this->getObjects($criteria, true);
310
311
        return $tbl_datas;
312
    }
313
314
    /**
315
     * @param     $startingDate
316
     * @param     $endingDate
317
     * @param int $category
318
     * @param int $start
319
     * @param int $limit
320
     *
321
     * @return array
322
     */
323 View Code Duplication
    public function getBooksForNewsletter($startingDate, $endingDate, $category = 0, $start = 0, $limit = 0)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
324
    {
325
        $tblDatas = array();
326
        $criteria = new CriteriaCompo();
327
        $criteria->add(new Criteria('book_online', 1, '='));
328
        $criteria->add(new Criteria('book_submitted', $startingDate, '>='));
329
        $criteria->add(new Criteria('book_submitted', $endingDate, '<='));
330
		if(bookshop_getmoduleoption('show_unpublished') == 0) {	// Ne pas afficher les livres qui ne sont pas publiés
331
            $criteria->add(new Criteria('book_submitted', time(), '<='));
332
        }
333
        if (bookshop_getmoduleoption('nostock_display') == 0) {    // Se limiter aux seuls livres encore en stock
334
            $criteria->add(new Criteria('book_stock', 0, '>'));
335
        }
336
        if (is_array($category)) {
337
            $criteria->add(new Criteria('book_cid', '(' . implode(',', $category) . ')', 'IN'));
338
        } elseif ($category > 0) {
339
            $criteria->add(new Criteria('book_cid', (int)$category, '='));
340
        }
341
        $criteria->setLimit($limit);
342
        $criteria->setStart($start);
343
        $criteria->setSort('book_title');
344
        $tblDatas =& $this->getObjects($criteria, true);
345
346
        return $tblDatas;
347
    }
348
349
    /**
350
	 * Renvoie le nombre total de livres publiés dans la base en tenant compte des préférences du module
351
     *
352
	 * @param intefer $book_cid Catégorie du livre
0 ignored issues
show
Documentation introduced by
Should the type for parameter $book_cid not be integer?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
353
	 * @return integer Le nombre de livres publiés
354
     */
355 View Code Duplication
    public function getTotalPublishedBooksCount($book_cid = 0)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
356
    {
357
        $criteria = new CriteriaCompo();
358
        $criteria->add(new Criteria('book_online', 1, '='));
359
		if(bookshop_getmoduleoption('show_unpublished') == 0) {	// Ne pas afficher les livres qui ne sont pas publiés
360
            $criteria->add(new Criteria('book_submitted', time(), '<='));
361
        }
362
        if (bookshop_getmoduleoption('nostock_display') == 0) {    // Se limiter aux seuls livres encore en stock
363
            $criteria->add(new Criteria('book_stock', 0, '>'));
364
        }
365
        if ($book_cid > 0) {
366
            $criteria->add(new Criteria('book_cid', (int)$book_cid, '='));
367
        }
368
369
        return $this->getCount($criteria);
370
    }
371
372
    /**
373
	 * Récupération de l'ID et du titre d'une série de livres répondants à un critère
374
     *
375
	 * @param object $criteria	critère de sélection
376
	 * @return array Tableau dont la clé = ID livre et la valeur le titre du livre
377
     */
378
    public function getIdTitle($criteria)
379
    {
380
        global $myts;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
381
        $ret = array();
382
        $sql = 'SELECT book_id, book_title FROM ' . $this->table;
383 View Code Duplication
        if (isset($criteria) && is_subclass_of($criteria, 'criteriaelement')) {
0 ignored issues
show
Bug introduced by
Due to PHP Bug #53727, is_subclass_of returns inconsistent results on some PHP versions for interfaces; you could instead use ReflectionClass::implementsInterface.
Loading history...
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...
384
            $sql .= ' ' . $criteria->renderWhere();
385
            if ($criteria->getSort() != '') {
386
                $sql .= ' ORDER BY ' . $criteria->getSort() . ' ' . $criteria->getOrder();
387
            }
388
            $limit = $criteria->getLimit();
389
            $start = $criteria->getStart();
390
        }
391
        $result = $this->db->query($sql, $limit, $start);
0 ignored issues
show
Bug introduced by
The variable $limit does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
Bug introduced by
The variable $start does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
392
        if (!$result) {
393
            return $ret;
394
        }
395
        while ($myrow = $this->db->fetchArray($result)) {
396
            $ret[$myrow['book_id']] = $myts->htmlSpecialChars($myrow['book_title']);
397
        }
398
399
        return $ret;
400
    }
401
402
    /**
403
	 * Renvoie l'URL à utiliser pour accéder à un livre en tenant compte des préférences du module
404
     *
405
     * @param  integer $book_id    Identifiant du livre
406
     * @param  string  $book_title Titre du livre
407
     * @return string  L'URL
408
     */
409 View Code Duplication
    public static function GetBookLink($book_id, $book_title)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
410
    {
411
        $url = '';
0 ignored issues
show
Unused Code introduced by
$url 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...
412
        if (bookshop_getmoduleoption('urlrewriting') == 1) {    // On utilise l'url rewriting
413
            $url = BOOKSHOP_URL . 'book-' . $book_id . bookshop_makeSEOurl($book_title) . '.html';
414
        } else {    // Pas d'utilisation de l'url rewriting
415
            $url = BOOKSHOP_URL . 'book.php?book_id=' . $book_id;
416
        }
417
418
        return $url;
419
    }
420
421
    /**
422
	 * Mise à jour du compteur de lectures du livre
423
     *
424
	 * @param integer $book_id L'identifiant du livre dont il faut mettre à jour le compteur de lectures
425
	 * @return boolean Le résultat de la mise à jour
426
     */
427
    public function addCounter($book_id)
428
    {
429
        $sql = 'UPDATE ' . $this->table . ' SET book_hits = book_hits + 1 WHERE book_id= ' . (int)$book_id;
430
431
        return $this->db->queryF($sql);
432
    }
433
434
    /**
435
     * Mise � jour de la notation d'un livre
436
     *
437
     * @param  integer $book_id Identifiant du livre
438
     * @param  float   $rating  la notation
439
     * @param  integer $votes   Le nombre de votes du livre
440
	 * @return boolean Le résultat de la mise à jour
441
     */
442
    public function updateRating($book_id, $rating, $votes)
443
    {
444
        $sql = 'UPDATE ' . $this->table . " SET book_rating = $rating, book_votes = $votes WHERE book_id = " . (int)$book_id;
445
446
        return $this->db->queryF($sql);
447
    }
448
449
    /**
450
	 * Mise à jour du nombre de commentaires d'un livre
451
     *
452
     * @param integer $book_id       Identifiant du livre
453
     * @param integer $commentsCount Nombre total de commentaires
454
     */
455
    public function updateCommentsCount($book_id, $commentsCount)
456
    {
457
        $book = null;
458
        $book =& $this->get($book_id);
459
        if (is_object($book)) {
460
            $criteria = new Criteria('book_id', $book_id, '=');
461
            $this->updateAll('book_comments', $commentsCount, $criteria, true);
462
        }
463
    }
464
465
    /**
466
     * Renvoie x livres au hasard
467
     *
468
	 * @param integer $start		Début des données
469
	 * @param integer $limit		Nombre maximum d'enregistrements à renvoyer
470
	 * @param integer $category Identifiant de la catégorie (évenutellement)
471
     * @return array   Tableau de livres (sous la forme d'objets)
472
     */
473 View Code Duplication
    public function getRandomBooks($start = 0, $limit = 0, $category = 0)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
474
    {
475
        $tbl_datas = array();
476
        $criteria  = new CriteriaCompo();
477
        $criteria->add(new Criteria('book_online', 1, '='));
478
		if(bookshop_getmoduleoption('show_unpublished') == 0) {	// Ne pas afficher les livres qui ne sont pas publiés
479
            $criteria->add(new Criteria('book_submitted', time(), '<='));
480
        }
481
        if (bookshop_getmoduleoption('nostock_display') == 0) {    // Se limiter aux seuls livres encore en stock
482
            $criteria->add(new Criteria('book_stock', 0, '>'));
483
        }
484
        if (is_array($category)) {
485
            $criteria->add(new Criteria('book_cid', '(' . implode(',', $category) . ')', 'IN'));
486
        } elseif ($category != 0) {
487
            $criteria->add(new Criteria('book_cid', (int)$category, '='));
488
        }
489
        $criteria->setLimit($limit);
490
        $criteria->setStart($start);
491
        $criteria->setSort('RAND()');
492
        $tbl_datas =& $this->getObjects($criteria, true);
493
494
        return $tbl_datas;
495
    }
496
497
    /**
498
     * Renvoie x livres en promo
499
     *
500
	 * @param integer $start		Début des données
501
	 * @param integer $limit		Nombre maximum d'enregistrements à renvoyer
502
	 * @param integer $category Identifiant de la catégorie (évenutellement)
503
     * @return array   Tableau de livres (sous la forme d'objets)
504
     */
505 View Code Duplication
    public function getPromotionalBooks($start = 0, $limit = 0, $category = 0)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
506
    {
507
        $tbl_datas = array();
508
        $criteria  = new CriteriaCompo();
509
        $criteria->add(new Criteria('book_online', 1, '='));
510
		if(bookshop_getmoduleoption('show_unpublished') == 0) {	// Ne pas afficher les livres qui ne sont pas publiés
511
            $criteria->add(new Criteria('book_submitted', time(), '<='));
512
        }
513
        if (bookshop_getmoduleoption('nostock_display') == 0) {    // Se limiter aux seuls livres encore en stock
514
            $criteria->add(new Criteria('book_stock', 0, '>'));
515
        }
516
        if (is_array($category)) {
517
            $criteria->add(new Criteria('book_cid', '(' . implode(',', $category) . ')', 'IN'));
518
        } elseif ($category != 0) {
519
            $criteria->add(new Criteria('book_cid', (int)$category, '='));
520
        }
521
        $criteria->add(new Criteria('book_discount_price', 0, '>'));
522
        $criteria->setLimit($limit);
523
        $criteria->setStart($start);
524
        $criteria->setSort('book_title');
525
        $criteria->setOrder('DESC');
526
        $tbl_datas =& $this->getObjects($criteria, true);
527
528
        return $tbl_datas;
529
    }
530
531
    /**
532
     * Renvoie les livres dont les stocks sont bas
533
     *
534
	 * @param integer $start		Début des données
535
	 * @param integer $limit		Nombre maximum d'enregistrements à renvoyer
536
     * @return array   Tableau de livres (sous la forme d'objets)
537
     */
538
    public function getLowStocks($start = 0, $limit = 0)
539
    {
540
        $ret = array();
541
        $sql = 'SELECT * FROM ' . $this->table . ' WHERE book_online = 1';
542
        if (bookshop_getmoduleoption('show_unpublished') == 0) {    // Ne pas afficher les livres qui ne sont pas publi�s
543
            $sql .= ' AND book_submitted <= ' . time();
544
        }
545
        $sql .= ' AND book_stock <= book_alert_stock ';
546
        $sql .= ' AND book_alert_stock > 0';
547
        $sql .= ' ORDER BY book_stock';
548
        $result = $this->db->query($sql, $limit, $start);
549
        if (!$result) {
550
            return $ret;
551
        }
552
553
        $ret = $this->convertResultSet($result, true, true);
554
555
        return $ret;
556
    }
557
558
    /**
559
	 * Retourne le nombre de livres dont la quantité en stock est inférieure ou égale à la quantité d'alerte
560
     *
561
     * @return array|bool
562
     */
563
    public function getLowStocksCount()
564
    {
565
        $ret = array();
566
        $sql = 'SELECT Count(*) as cpt FROM ' . $this->table . ' WHERE book_online = 1';
567
        if (bookshop_getmoduleoption('show_unpublished') == 0) {    // Ne pas afficher les livres qui ne sont pas publi�s
568
            $sql .= ' AND book_submitted <= ' . time();
569
        }
570
        $sql .= ' AND book_stock <= book_alert_stock ';
571
        $sql .= ' AND book_alert_stock > 0';
572
        $result = $this->db->query($sql);
573
        if (!$result) {
574
            return $ret;
575
        }
576
        $count = 0;
577
        list($count) = $this->db->fetchRow($result);
578
579
        return $count;
580
    }
581
582
    /**
583
	 * Augmente les quantités en stock d'un livre
584
     *
585
	 * @param object $book Objet livre
586
	 * @param $quantity $quantity Quantité à rajouter
0 ignored issues
show
Documentation introduced by
The doc-type $quantity could not be parsed: Unknown type name "$quantity" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
587
     *
588
     * @return bool
589
     */
590
    public function increaseStock(XoopsObject $book, $quantity = 1)
591
    {
592
        $book->setVar('book_stock', $book->getVar('book_stock') + 1);
593
        $this->insert($book, true);
594
595
        return true;
596
    }
597
598
    /**
599
	 * Diminue les quantités en stock d'un livre
600
     *
601
     * @param XoopsObject  $book     Objet livre
602
	 * @param $quantity $quantity Quantité à soustraire
0 ignored issues
show
Documentation introduced by
The doc-type $quantity could not be parsed: Unknown type name "$quantity" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
603
     *
604
     * @return bool
605
     */
606
    public function decreaseStock(XoopsObject $book, $quantity = 1)
607
    {
608
        if ($book->getVar('book_stock') - $quantity > 0) {
609
            $book->setVar('book_stock', $book->getVar('book_stock') - $quantity);
610
            $this->insert($book, true);
611
        } else {
612
            $book->setVar('book_stock', 0);
613
        }
614
615
        return true;
616
    }
617
618
    /**
619
	 * Indique si la quantité d'alerte d'un livre est atteinte
620
     *
621
	 * @param object $book L'objet livre concerné
622
	 * @return boolean Vrai si la quantité d'alerte est atteinte, sinon faux
623
     */
624
    public function isAlertStockReached(&$book)
625
    {
626
        if ($book->getVar('book_stock') < $book->getVar('book_alert_stock')) {
627
            return true;
628
        } else {
629
            return false;
630
        }
631
    }
632
633
    /**
634
	 * Méthode chargée de vérifier si le stock d'alerte est atteint et si c'est le cas, d'envoyer une alerte
635
     *
636
	 * @param object $book Livre dont il faut faire la vérification
637
	 * @return boolean vrai si l'alerte à du être générée sinon faux
638
     */
639
    public function verifyLowStock(&$book)
640
    {
641
        if ($this->isAlertStockReached($book)) {
642
            $msg                    = array();
643
            $msg['BOOK_NAME']       = $book->getVar('book_title');
644
            $msg['ACTUAL_QUANTITY'] = $book->getVar('book_stock');
645
            $msg['ALERT_QUANTITY']  = $book->getVar('book_alert_stock');
646
            $msg['PUBLIC_URL']      = static::GetBookLink($book->getVar('book_id'), $book->getVar('book_title'));
647
            $msg['ADMIN_URL']       = BOOKSHOP_URL . 'admin/index.php?op=editbook&id=' . $book->getVar('book_id');
648
            bookshop_send_email_from_tpl('shop_lowstock.tpl', bookshop_getEmailsFromGroup(bookshop_getmoduleoption('stock_alert_email')), _BOOKSHOP_STOCK_ALERT, $msg);
0 ignored issues
show
Documentation introduced by
bookshop_getmoduleoption('stock_alert_email') is of type boolean, but the function expects a integer.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
649
650
            return true;
651
        } else {
652
            return false;
653
        }
654
    }
655
656
    /**
657
	 * Renvoie la plus petite date de création d'un livre ainsi que la "plus grande" date de création d'un livre
658
     *
659
	 * @param integer $minDate Date mini (parmètre de sortie)
660
	 * @param integer $maxDate Date maxi (paramètre de sortie)
661
	 * @return boolean Vrai si on a pu récupérer ces valeurs, faux sinon
662
     */
663
    public function getMinMaxPublishedDate(&$minDate, &$maxDate)
664
    {
665
        $sql    = 'SELECT Min(book_submitted) as minDate, Max(book_submitted) as maxDate FROM ' . $this->table . ' WHERE book_online=1';
666
        $result = $this->db->query($sql);
667
        if (!$result) {
668
            return false;
669
        }
670
        $myrow   = $this->db->fetchArray($result);
671
        $minDate = $myrow['minDate'];
672
        $maxDate = $myrow['maxDate'];
673
674
        return true;
675
    }
676
}
677