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

CategoryHandler   A

Complexity

Total Complexity 19

Size/Duplication

Total Lines 178
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 19
eloc 62
dl 0
loc 178
rs 10
c 0
b 0
f 0

9 Methods

Rating   Name   Duplication   Size   Complexity  
A getUlMenu() 0 14 2
A getMotherCategories() 0 8 1
A getCategoryProductsCount() 0 21 4
A getCategoriesCount() 0 5 1
A __construct() 0 4 1
A deleteCategory() 0 7 1
A getAllCategories() 0 18 1
A getCategoriesFromIds() 0 9 3
A _makeLi() 0 14 5
1
<?php
2
3
namespace XoopsModules\Oledrion;
4
5
/*
6
 You may not change or alter any portion of this comment or credits
7
 of supporting developers from this source code or any supporting source code
8
 which is considered copyrighted (c) material of the original comment or credit authors.
9
10
 This program is distributed in the hope that it will be useful,
11
 but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13
*/
14
15
/**
16
 * oledrion
17
 *
18
 * @copyright   {@link https://xoops.org/ XOOPS Project}
19
 * @license     {@link http://www.fsf.org/copyleft/gpl.html GNU public license}
20
 * @author      Hervé Thouzard (http://www.herve-thouzard.com/)
21
 */
22
23
use XoopsModules\Oledrion;
24
25
/**
26
 * Gestion des catégories de produits
27
 */
28
29
/**
30
 * Class CategoryHandler
31
 */
32
class CategoryHandler extends OledrionPersistableObjectHandler
33
{
34
    /**
35
     * CategoryHandler constructor.
36
     * @param \XoopsDatabase|null $db
37
     */
38
    public function __construct(\XoopsDatabase $db = null)
39
    {
40
        //                        Table               Classe       Id       Libellé
41
        parent::__construct($db, 'oledrion_cat', Category::class, 'cat_cid', 'cat_title');
0 ignored issues
show
Bug introduced by
It seems like $db can also be of type null; however, parameter $db of XoopsModules\Oledrion\Ol...tHandler::__construct() does only seem to accept XoopsDatabase, maybe add an additional type check? ( Ignorable by Annotation )

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

41
        parent::__construct(/** @scrutinizer ignore-type */ $db, 'oledrion_cat', Category::class, 'cat_cid', 'cat_title');
Loading history...
42
    }
43
44
    /**
45
     * Renvoie (sous forme d'objets) la liste de toutes les catégories
46
     *
47
     * @param  Parameters $parameters
48
     * @return array               Taleau d'objets (catégories)
49
     * @internal param int $start Indice de début de recherche
50
     * @internal param int $limit Nombre maximum d'enregsitrements à renvoyer
51
     * @internal param string $sort Champ à utiliser pour le tri
52
     * @internal param string $order Ordre du tire (asc ou desc)
53
     * @internal param bool $idaskey Indique s'il faut renvoyer un tableau dont la clé est l'identifiant de l'enregistrement
54
     */
55
    public function getAllCategories(Parameters $parameters)
56
    {
57
        $parameters = $parameters->extend(new Oledrion\Parameters([
58
                                                                      'start'   => 0,
59
                                                                      'limit'   => 0,
60
                                                                      'sort'    => 'cat_title',
61
                                                                      'order'   => 'ASC',
62
                                                                      'idaskey' => true,
63
                                                                  ]));
64
        $critere    = new \Criteria('cat_cid', 0, '<>');
65
        $critere->setLimit($parameters['limit']);
66
        $critere->setStart($parameters['start']);
67
        $critere->setSort($parameters['sort']);
68
        $critere->setOrder($parameters['order']);
69
        $categories = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $categories is dead and can be removed.
Loading history...
70
        $categories = $this->getObjects($critere, $parameters['idaskey']);
71
72
        return $categories;
73
    }
74
75
    /**
76
     * Internal function to make an expanded view of categories via <li>
77
     *
78
     * @param  string $fieldName
79
     * @param  string $key
80
     * @param  string $ret
81
     * @param  array  $tree
82
     * @return string
83
     */
84
    private function _makeLi($fieldName, $key, &$ret, $tree)
85
    {
86
        if ($key > 0) {
87
            $ret .= '<li><a href="';
88
            $ret .= $tree[$key]['obj']->getLink() . '">' . $tree[$key]['obj']->getVar('cat_title') . '</a>';
89
        }
90
        if (isset($tree[$key]['child']) && !empty($tree[$key]['child'])) {
91
            $ret .= "\n<ul>\n";
92
            foreach ($tree[$key]['child'] as $childkey) {
93
                $this->_makeLi($fieldName, $childkey, $ret, $tree);
94
            }
95
            $ret .= "</ul>\n";
96
        }
97
        $ret .= "</li>\n";
98
    }
99
100
    /**
101
     * Make a menu from the categories list
102
     *
103
     * @param  string $fieldName Name of the member variable from the node objects that should be used as the title for the options.
104
     * @param int     $key       ID of the object to display as the root of select options
105
     * @return string  HTML select box
106
     */
107
    public function getUlMenu($fieldName, $key = 0)
108
    {
109
        //        require_once XOOPS_ROOT_PATH . '/class/tree.php';
110
        $items      = $this->getAllCategories(new Oledrion\Parameters());
111
        $treeObject = new Oledrion\XoopsObjectTree($items, 'cat_cid', 'cat_pid');
112
        $tree       = $treeObject->getTree();
113
114
        $ret = '';
115
        $this->_makeLi($fieldName, $key, $ret, $tree);
116
        if ('' !== xoops_trim($ret)) {
117
            $ret = mb_substr($ret, 0, -6);
118
        }
119
120
        return $ret;
121
    }
122
123
    /**
124
     * Supprime une catégorie (et tout ce qui lui est relatif)
125
     *
126
     * @param  Category $category
127
     * @return bool      Le résultat de la suppression
128
     */
129
    public function deleteCategory(Category $category)
130
    {
131
        global $xoopsModule;
132
        $category->deletePicture();
133
        xoops_notification_deletebyitem($xoopsModule->getVar('mid'), 'new_category', $category->getVar('cat_cid'));
134
135
        return $this->delete($category, true);
136
    }
137
138
    /**
139
     * Retourne le nombre de produits d'une ou de plusieurs catégories
140
     *
141
     * @param int   $cat_cid    L'identifiant de la catégorie dont on veut récupérer le nombre de produits
142
     * @param  bool $withNested Faut il inclure les sous-catégories ?
143
     * @return int Le nombre de produits
144
     */
145
    public function getCategoryProductsCount($cat_cid, $withNested = true)
146
    {
147
        global $productsHandler;
148
        $childsIDs   = [];
149
        $childsIDs[] = $cat_cid;
150
151
        if ($withNested) {
152
            // Recherche des sous catégories de cette catégorie
153
            $items = $childs = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $childs is dead and can be removed.
Loading history...
Unused Code introduced by
The assignment to $items is dead and can be removed.
Loading history...
154
            require_once XOOPS_ROOT_PATH . '/class/tree.php';
155
            $items  = $this->getAllCategories(new Oledrion\Parameters());
156
            $mytree = new Oledrion\XoopsObjectTree($items, 'cat_cid', 'cat_pid');
157
            $childs = $mytree->getAllChild($cat_cid);
158
            if (count($childs) > 0) {
159
                foreach ($childs as $onechild) {
160
                    $childsIDs[] = $onechild->getVar('cat_cid');
161
                }
162
            }
163
        }
164
165
        return $productsHandler->getCategoryProductsCount($childsIDs);
166
    }
167
168
    /**
169
     * Retourne des catégories selon leur ID
170
     *
171
     * @param  array $ids Les ID des catégories à retrouver
172
     * @return array Objets de type Category
173
     */
174
    public function getCategoriesFromIds($ids)
175
    {
176
        $ret = [];
177
        if ($ids && is_array($ids)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $ids of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

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

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

Loading history...
178
            $criteria = new \Criteria('cat_cid', '(' . implode(',', $ids) . ')', 'IN');
179
            $ret      = $this->getObjects($criteria, true, true, '*', false);
0 ignored issues
show
Unused Code introduced by
The call to XoopsPersistableObjectHandler::getObjects() has too many arguments starting with '*'. ( Ignorable by Annotation )

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

179
            /** @scrutinizer ignore-call */ 
180
            $ret      = $this->getObjects($criteria, true, true, '*', false);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
180
        }
181
182
        return $ret;
183
    }
184
185
    /**
186
     * Retourne la liste des catégories mères (sous forme d'un tableau d'objets)
187
     *
188
     * @return array Objets de type Category
189
     */
190
    public function getMotherCategories()
191
    {
192
        $ret      = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $ret is dead and can be removed.
Loading history...
193
        $criteria = new \Criteria('cat_pid', 0, '=');
194
        $criteria->setSort('cat_title');
195
        $ret = $this->getObjects($criteria);
196
197
        return $ret;
198
    }
199
200
    /**
201
     * Get category count
202
     *
203
     * @return int number of category
204
     */
205
    public function getCategoriesCount()
206
    {
207
        $criteria = new \CriteriaCompo();
208
209
        return $this->getCount($criteria);
210
    }
211
}
212