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

OledrionOledrion_catHandler   A

Complexity

Total Complexity 19

Size/Duplication

Total Lines 178
Duplicated Lines 5.62 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
dl 10
loc 178
rs 10
c 0
b 0
f 0
wmc 19
lcom 1
cbo 3

9 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getAllCategories() 0 19 1
B _makeLi() 0 15 5
A getUlMenu() 0 15 2
A deleteCategory() 0 8 1
A getCategoryProductsCount() 0 21 4
A getCategoriesFromIds() 10 10 3
A getMotherCategories() 0 9 1
A getCategoriesCount() 0 6 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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 29 and the first side effect is on line 24.

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
 You may not change or alter any portion of this comment or credits
4
 of supporting developers from this source code or any supporting source code
5
 which is considered copyrighted (c) material of the original comment or credit authors.
6
7
 This program is distributed in the hope that it will be useful,
8
 but WITHOUT ANY WARRANTY; without even the implied warranty of
9
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10
*/
11
12
/**
13
 * oledrion
14
 *
15
 * @copyright   {@link http://xoops.org/ XOOPS Project}
16
 * @license     {@link http://www.fsf.org/copyleft/gpl.html GNU public license}
17
 * @author      Hervé Thouzard (http://www.herve-thouzard.com/)
18
 */
19
20
/**
21
 * Gestion des catégories de produits
22
 */
23
24
require __DIR__ . '/classheader.php';
25
26
/**
27
 * Class Oledrion_cat
28
 */
29
class Oledrion_cat extends Oledrion_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...
30
{
31
    /**
32
     * constructor
33
     *
34
     * normally, this is called from child classes only
35
     *
36
     * @access public
37
     */
38
    public function __construct()
39
    {
40
        $this->initVar('cat_cid', XOBJ_DTYPE_INT, null, false);
41
        $this->initVar('cat_pid', XOBJ_DTYPE_INT, null, false);
42
        $this->initVar('cat_title', XOBJ_DTYPE_TXTBOX, null, false);
43
        $this->initVar('cat_imgurl', XOBJ_DTYPE_TXTBOX, null, false);
44
        $this->initVar('cat_description', XOBJ_DTYPE_TXTAREA, null, false);
45
        $this->initVar('cat_advertisement', XOBJ_DTYPE_TXTAREA, null, false);
46
        $this->initVar('cat_metakeywords', XOBJ_DTYPE_TXTBOX, null, false);
47
        $this->initVar('cat_metadescription', XOBJ_DTYPE_TXTBOX, null, false);
48
        $this->initVar('cat_metatitle', XOBJ_DTYPE_TXTBOX, null, false);
49
        $this->initVar('cat_footer', XOBJ_DTYPE_TXTAREA, null, false);
50
        // Pour autoriser le html
51
        $this->initVar('dohtml', XOBJ_DTYPE_INT, 1, false);
52
    }
53
54
    /**
55
     * Retourne l'URL de l'image de la catégorie courante
56
     * @return string L'URL
57
     */
58
    public function getPictureUrl()
59
    {
60
        return OLEDRION_PICTURES_URL . '/' . $this->getVar('cat_imgurl');
61
    }
62
63
    /**
64
     * Retourne le chemin de l'image de la catégorie courante
65
     * @return string Le chemin
66
     */
67
    public function getPicturePath()
68
    {
69
        return OLEDRION_PICTURES_PATH . '/' . $this->getVar('cat_imgurl');
70
    }
71
72
    /**
73
     * Indique si l'image de la catégorie existe
74
     *
75
     * @return boolean Vrai si l'image existe sinon faux
76
     */
77 View Code Duplication
    public function pictureExists()
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...
78
    {
79
        $return = false;
80
        if (xoops_trim($this->getVar('cat_imgurl')) != ''
81
            && file_exists(OLEDRION_PICTURES_PATH . '/' . $this->getVar('cat_imgurl'))
82
        ) {
83
            $return = true;
84
        }
85
86
        return $return;
87
    }
88
89
    /**
90
     * Supprime l'image associée à une catégorie
91
     * @return void
92
     */
93 View Code Duplication
    public function deletePicture()
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...
94
    {
95
        if ($this->pictureExists()) {
96
            @unlink(OLEDRION_PICTURES_PATH . '/' . $this->getVar('cat_imgurl'));
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
97
        }
98
        $this->setVar('cat_imgurl', '');
99
    }
100
101
    /**
102
     * Retourne l'url à utiliser pour accéder à la catégorie en tenant compte des préférences du module
103
     *
104
     * @return string L'url à utiliser
105
     */
106 View Code Duplication
    public function getLink()
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...
107
    {
108
        include_once XOOPS_ROOT_PATH . '/modules/oledrion/include/common.php';
109
        $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...
110
        if (Oledrion_utils::getModuleOption('urlrewriting') == 1) { // On utilise l'url rewriting
111
            $url = OLEDRION_URL . 'category-' . $this->getVar('cat_cid') . Oledrion_utils::makeSeoUrl($this->getVar('cat_title', 'n')) . '.html';
112
        } else { // Pas d'utilisation de l'url rewriting
113
            $url = OLEDRION_URL . 'category.php?cat_cid=' . $this->getVar('cat_cid');
114
        }
115
116
        return $url;
117
    }
118
119
    /**
120
     * Rentourne la chaine à envoyer dans une balise <a> pour l'attribut href
121
     *
122
     * @return string
123
     */
124
    public function getHrefTitle()
125
    {
126
        return Oledrion_utils::makeHrefTitle($this->getVar('cat_title'));
127
    }
128
129
    /**
130
     * Retourne les éléments du produits formatés pour affichage
131
     *
132
     * @param  string $format
133
     * @return array
134
     */
135
    public function toArray($format = 's')
136
    {
137
        $ret                     = array();
0 ignored issues
show
Unused Code introduced by
$ret 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...
138
        $ret                     = parent::toArray($format);
139
        $ret['cat_full_imgurl']  = $this->getPictureUrl();
140
        $ret['cat_href_title']   = $this->getHrefTitle();
141
        $ret['cat_url_rewrited'] = $this->getLink();
142
143
        return $ret;
144
    }
145
}
146
147
/**
148
 * Class OledrionOledrion_catHandler
149
 */
150
class OledrionOledrion_catHandler extends Oledrion_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...
151
{
152
    /**
153
     * OledrionOledrion_catHandler constructor.
154
     * @param XoopsDatabase|null $db
155
     */
156
    public function __construct(XoopsDatabase $db)
157
    { //                        Table               Classe       Id       Libellé
158
        parent::__construct($db, 'oledrion_cat', 'oledrion_cat', 'cat_cid', 'cat_title');
159
    }
160
161
    /**
162
     * Renvoie (sous forme d'objets) la liste de toutes les catégories
163
     *
164
     * @param  Oledrion_parameters $parameters
165
     * @return array               Taleau d'objets (catégories)
166
     * @internal param int $start Indice de début de recherche
167
     * @internal param int $limit Nombre maximum d'enregsitrements à renvoyer
168
     * @internal param string $sort Champ à utiliser pour le tri
169
     * @internal param string $order Ordre du tire (asc ou desc)
170
     * @internal param bool $idaskey Indique s'il faut renvoyer un tableau dont la clé est l'identifiant de l'enregistrement
171
     */
172
    public function getAllCategories(Oledrion_parameters $parameters)
173
    {
174
        $parameters = $parameters->extend(new Oledrion_parameters(array(
0 ignored issues
show
Documentation introduced by
new \Oledrion_parameters...C', 'idaskey' => true)) is of type object<Oledrion_parameters>, but the function expects a object<self>.

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...
175
                                                                      'start'   => 0,
176
                                                                      'limit'   => 0,
177
                                                                      'sort'    => 'cat_title',
178
                                                                      'order'   => 'ASC',
179
                                                                      'idaskey' => true
180
                                                                  )));
181
        $critere    = new Criteria('cat_cid', 0, '<>');
182
        $critere->setLimit($parameters['limit']);
183
        $critere->setStart($parameters['start']);
184
        $critere->setSort($parameters['sort']);
185
        $critere->setOrder($parameters['order']);
186
        $categories = array();
0 ignored issues
show
Unused Code introduced by
$categories 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...
187
        $categories = $this->getObjects($critere, $parameters['idaskey']);
188
189
        return $categories;
190
    }
191
192
    /**
193
     * Fonction interne pour faire une vue développée des catégories
194
     *
195
     * @param  string $fieldName
196
     * @param  string $key
197
     * @param  string $ret
198
     * @param  object $tree
199
     * @return string
0 ignored issues
show
Documentation introduced by
Should the return type not be string|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
200
     */
201
    private function _makeLi($fieldName, $key, &$ret, $tree)
202
    {
203
        if ($key > 0) {
204
            $ret .= '<li><a href="';
205
            $ret .= $tree[$key]['obj']->getLink() . '">' . $tree[$key]['obj']->getVar('cat_title') . '</a>';
206
        }
207
        if (isset($tree[$key]['child']) && !empty($tree[$key]['child'])) {
208
            $ret .= "\n<ul>\n";
209
            foreach ($tree[$key]['child'] as $childkey) {
210
                $this->_makeLi($fieldName, $childkey, $ret, $tree);
211
            }
212
            $ret .= "</ul>\n";
213
        }
214
        $ret .= "</li>\n";
215
    }
216
217
    /**
218
     * Make a menu from the categories list
219
     *
220
     * @param  string  $fieldName Name of the member variable from the node objects that should be used as the title for the options.
221
     * @param  integer $key       ID of the object to display as the root of select options
222
     * @return string  HTML select box
223
     */
224
    public function getUlMenu($fieldName, $key = 0)
225
    {
226
        include_once XOOPS_ROOT_PATH . '/class/tree.php';
227
        $items      = $this->getAllCategories(new Oledrion_parameters());
228
        $treeObject = new XoopsObjectTree($items, 'cat_cid', 'cat_pid');
229
        $tree       =& $treeObject->getTree();
230
231
        $ret = '';
232
        $this->_makeLi($fieldName, $key, $ret, $tree);
233
        if (xoops_trim($ret) != '') {
234
            $ret = substr($ret, 0, -6);
235
        }
236
237
        return $ret;
238
    }
239
240
    /**
241
     * Supprime une catégorie (et tout ce qui lui est relatif)
242
     *
243
     * @param  Oledrion_cat $category
244
     * @return boolean      Le résultat de la suppression
245
     */
246
    public function deleteCategory(Oledrion_cat $category)
247
    {
248
        global $xoopsModule;
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...
249
        $category->deletePicture();
250
        xoops_notification_deletebyitem($xoopsModule->getVar('mid'), 'new_category', $category->getVar('cat_cid'));
251
252
        return $this->delete($category, true);
253
    }
254
255
    /**
256
     * Retourne le nombre de produits d'une ou de plusieurs catégories
257
     *
258
     * @param  integer $cat_cid    L'identifiant de la catégorie dont on veut récupérer le nombre de produits
259
     * @param  boolean $withNested Faut il inclure les sous-catégories ?
260
     * @return integer Le nombre de produits
261
     */
262
    public function getCategoryProductsCount($cat_cid, $withNested = true)
263
    {
264
        global $h_oledrion_products;
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...
265
        $childsIDs   = array();
266
        $childsIDs[] = $cat_cid;
267
268
        if ($withNested) { // Recherche des sous catégories de cette catégorie
269
            $items = $childs = array();
0 ignored issues
show
Unused Code introduced by
$childs 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...
Unused Code introduced by
$items 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...
270
            include_once XOOPS_ROOT_PATH . '/class/tree.php';
271
            $items  = $this->getAllCategories(new Oledrion_parameters());
272
            $mytree = new XoopsObjectTree($items, 'cat_cid', 'cat_pid');
273
            $childs = $mytree->getAllChild($cat_cid);
274
            if (count($childs) > 0) {
275
                foreach ($childs as $onechild) {
276
                    $childsIDs[] = $onechild->getVar('cat_cid');
277
                }
278
            }
279
        }
280
281
        return $h_oledrion_products->getCategoryProductsCount($childsIDs);
282
    }
283
284
    /**
285
     * Retourne des catégories selon leur ID
286
     *
287
     * @param  array $ids Les ID des catégories à retrouver
288
     * @return array Objets de type Oledrion_cat
289
     */
290 View Code Duplication
    public function getCategoriesFromIds($ids)
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
        $ret = array();
293
        if (is_array($ids) && count($ids) > 0) {
294
            $criteria = new Criteria('cat_cid', '(' . implode(',', $ids) . ')', 'IN');
295
            $ret      = $this->getObjects($criteria, true, true, '*', false);
296
        }
297
298
        return $ret;
299
    }
300
301
    /**
302
     * Retourne la liste des catégories mères (sous forme d'un tableau d'objets)
303
     *
304
     * @return array Objets de type Oledrion_cat
305
     */
306
    public function getMotherCategories()
307
    {
308
        $ret      = array();
0 ignored issues
show
Unused Code introduced by
$ret 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...
309
        $criteria = new Criteria('cat_pid', 0, '=');
310
        $criteria->setSort('cat_title');
311
        $ret = $this->getObjects($criteria);
312
313
        return $ret;
314
    }
315
316
    /**
317
     * Get category count
318
     *
319
     * @return int number of category
320
     */
321
    public function getCategoriesCount()
322
    {
323
        $criteria = new CriteriaCompo();
324
325
        return $this->getCount($criteria);
326
    }
327
}
328