Passed
Push — EXTRACT_CLASSES ( ff35ec...a2ff75 )
by Rafael
48:13
created

PartnershipType::getNomUrl()   F

Complexity

Conditions 37
Paths > 20000

Size

Total Lines 105
Code Lines 68

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 37
eloc 68
nc 20736
nop 5
dl 0
loc 105
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity   

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:

1
<?php
2
3
/* Copyright (C) 2002       Rodolphe Quiedeville        <[email protected]>
4
 * Copyright (C) 2004-2008	Laurent Destailleur		    <[email protected]>
5
 * Copyright (C) 2009-2017	Regis Houssin			    <[email protected]>
6
 * Copyright (C) 2016		Charlie Benke			    <[email protected]>
7
 * Copyright (C) 2018-2019  Thibault Foucart		    <[email protected]>
8
 * Copyright (C) 2021     	Waël Almoman                <[email protected]>
9
 * Copyright (C) 2024       Frédéric France             <[email protected]>
10
 * Copyright (C) 2024		MDW							<[email protected]>
11
 * Copyright (C) 2024       Rafael San José             <[email protected]>
12
 *
13
 * This program is free software; you can redistribute it and/or modify
14
 * it under the terms of the GNU General Public License as published by
15
 * the Free Software Foundation; either version 3 of the License, or
16
 * (at your option) any later version.
17
 *
18
 * This program is distributed in the hope that it will be useful,
19
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21
 * GNU General Public License for more details.
22
 *
23
 * You should have received a copy of the GNU General Public License
24
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
25
 */
26
27
namespace Dolibarr\Code\Partnerships\Classes;
28
29
use Dolibarr\Core\Base\CommonObject;
30
31
/**
32
 *  \file       htdocs/partnership/class/partnership_type.class.php
33
 *  \ingroup    partnership
34
 *  \brief      File of class to manage partnership types
35
 */
36
37
/**
38
 *  Class to manage partnership type
39
 */
40
class PartnershipType extends CommonObject
41
{
42
    /**
43
     * @var string Name of table without prefix where object is stored
44
     */
45
    public $table_element = 'c_partnership_type';
46
47
    /**
48
     * @var string ID to identify managed object
49
     */
50
    public $element = 'partnership_type';
51
52
    /**
53
     * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png
54
     */
55
    public $picto = 'generic';
56
57
    /**
58
     * @var string Partnership code
59
     */
60
    public $code;
61
62
    /**
63
     * @var string Partnership type label
64
     */
65
    public $label;
66
67
    public $active;
68
69
70
    public $fields = array(
71
        'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 10),
72
        'entity' => array('type' => 'integer', 'label' => 'Entity', 'default' => '1', 'enabled' => 1, 'visible' => -2, 'notnull' => 1, 'position' => 15, 'index' => 1),
73
        'code' => array('type' => 'varchar(32)', 'label' => 'Code', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 20),
74
        'label' => array('type' => 'varchar(64)', 'label' => 'Label', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 25, 'showoncombobox' => 1),
75
        'active' => array('type' => 'integer', 'label' => 'Active', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 30),
76
    );
77
78
79
80
    /**
81
     * Constructor
82
     *
83
     * @param DoliDB $db Database handler
84
     */
85
    public function __construct(DoliDB $db)
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\Partnerships\Classes\DoliDB was not found. Did you mean DoliDB? If so, make sure to prefix the type with \.
Loading history...
86
    {
87
        global $conf, $langs;
88
89
        $this->db = $db;
90
91
        $this->ismultientitymanaged = 1;
92
93
        if (!getDolGlobalString('MAIN_SHOW_TECHNICAL_ID') && isset($this->fields['rowid'])) {
94
            $this->fields['rowid']['visible'] = 0;
95
        }
96
        if (!isModEnabled('multicompany') && isset($this->fields['entity'])) {
97
            $this->fields['entity']['enabled'] = 0;
98
        }
99
100
        // Example to show how to set values of fields definition dynamically
101
        /*if ($user->hasRight('mymodule', 'myobject', 'read')) {
102
         $this->fields['myfield']['visible'] = 1;
103
         $this->fields['myfield']['noteditable'] = 0;
104
         }*/
105
106
        // Unset fields that are disabled
107
        foreach ($this->fields as $key => $val) {
108
            if (isset($val['enabled']) && empty($val['enabled'])) {
109
                unset($this->fields[$key]);
110
            }
111
        }
112
113
        // Translate some data of arrayofkeyval
114
        if (is_object($langs)) {
115
            foreach ($this->fields as $key => $val) {
116
                if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
117
                    foreach ($val['arrayofkeyval'] as $key2 => $val2) {
118
                        $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
119
                    }
120
                }
121
            }
122
        }
123
    }
124
125
    /**
126
     * Create object into database
127
     *
128
     * @param  User $user      User that creates
129
     * @param  int  $notrigger 0=launch triggers after, 1=disable triggers
130
     * @return int             Return integer <0 if KO, Id of created object if OK
131
     */
132
    public function create(User $user, $notrigger = 0)
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\Partnerships\Classes\User was not found. Did you mean User? If so, make sure to prefix the type with \.
Loading history...
133
    {
134
        $resultcreate = $this->createCommon($user, $notrigger);
135
        return $resultcreate;
136
    }
137
138
    /**
139
     * Load object in memory from the database
140
     *
141
     * @param int    $id   Id object
142
     * @param string $ref  Ref
143
     * @return int         Return integer <0 if KO, 0 if not found, >0 if OK
144
     */
145
    public function fetch($id, $ref = null)
146
    {
147
        $result = $this->fetchCommon($id, $ref);
148
        return $result;
149
    }
150
151
    /**
152
     * Load list of objects in memory from the database.
153
     *
154
     * @param  string       $sortorder      Sort Order
155
     * @param  string       $sortfield      Sort field
156
     * @param  int          $limit          limit
157
     * @param  int          $offset         Offset
158
     * @param  string       $filter         Filter as an Universal Search string.
159
     *                                      Example: '((client:=:1) OR ((client:>=:2) AND (client:<=:3))) AND (client:!=:8) AND (nom:like:'a%')'
160
     * @param  string       $filtermode     No more used
161
     * @return array|int                    int <0 if KO, array of pages if OK
162
     */
163
    public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, $filter = '', $filtermode = 'AND')
164
    {
165
        global $conf;
166
167
        dol_syslog(__METHOD__, LOG_DEBUG);
168
169
        $records = array();
170
171
        $sql = "SELECT ";
172
        $sql .= $this->getFieldList('t');
173
        $sql .= " FROM " . MAIN_DB_PREFIX . $this->table_element . " as t";
174
        if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
175
            $sql .= " WHERE t.entity IN (" . getEntity($this->element) . ")";
176
        } else {
177
            $sql .= " WHERE 1 = 1";
178
        }
179
180
        // Manage filter
181
        $errormessage = '';
182
        $sql .= forgeSQLFromUniversalSearchCriteria($filter, $errormessage);
183
        if ($errormessage) {
184
            $this->errors[] = $errormessage;
185
            dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
186
            return -1;
187
        }
188
189
        if (!empty($sortfield)) {
190
            $sql .= $this->db->order($sortfield, $sortorder);
191
        }
192
        if (!empty($limit)) {
193
            $sql .= $this->db->plimit($limit, $offset);
194
        }
195
196
        $resql = $this->db->query($sql);
197
        if ($resql) {
198
            $num = $this->db->num_rows($resql);
199
            $i = 0;
200
            while ($i < ($limit ? min($limit, $num) : $num)) {
201
                $obj = $this->db->fetch_object($resql);
202
203
                $record = new self($this->db);
204
                $record->setVarsFromFetchObj($obj);
205
206
                $records[$record->id] = $record;
207
208
                $i++;
209
            }
210
            $this->db->free($resql);
211
212
            return $records;
213
        } else {
214
            $this->errors[] = 'Error ' . $this->db->lasterror();
215
            dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
216
217
            return -1;
218
        }
219
    }
220
221
    /**
222
     * Update object into database
223
     *
224
     * @param  User $user      User that modifies
225
     * @param  int  $notrigger 0=launch triggers after, 1=disable triggers
226
     * @return int             Return integer <0 if KO, >0 if OK
227
     */
228
    public function update(User $user, $notrigger = 0)
229
    {
230
        return $this->updateCommon($user, $notrigger);
231
    }
232
233
    /**
234
     * Delete object in database
235
     *
236
     * @param User $user        User that deletes
237
     * @param int   $notrigger  0=launch triggers after, 1=disable triggers
238
     * @return int              Return integer <0 if KO, >0 if OK
239
     */
240
    public function delete(User $user, $notrigger = 0)
241
    {
242
        return $this->deleteCommon($user, $notrigger);
243
    }
244
245
    /**
246
     *  Return a link to the object card (with optionally the picto)
247
     *
248
     *  @param  int     $withpicto                  Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
249
     *  @param  string  $option                     On what the link point to ('nolink', ...)
250
     *  @param  int     $notooltip                  1=Disable tooltip
251
     *  @param  string  $morecss                    Add more css on link
252
     *  @param  int     $save_lastsearch_value      -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
253
     *  @return string                              String with URL
254
     */
255
    public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
256
    {
257
        global $conf, $langs, $hookmanager;
258
259
        if (!empty($conf->dol_no_mouse_hover)) {
260
            $notooltip = 1; // Force disable tooltips
261
        }
262
263
        $result = '';
264
265
        $label = img_picto('', $this->picto) . ' <u>' . $langs->trans("PartnershipType") . '</u>';
266
        if (isset($this->status)) {
267
            $label .= ' ' . $this->getLibStatut(5);
268
        }
269
        $label .= '<br>';
270
        $label .= '<b>' . $langs->trans('Code') . ':</b> ' . $this->code;
271
        $label .= '<br><b>' . $langs->trans('Label') . ':</b> ' . $this->label;
272
273
        //$url = dol_buildpath('/partnership/partnership_card.php', 1).'?id='.$this->id;
274
        $url = '';
275
276
        if ($option != 'nolink') {
277
            // Add param to save lastsearch_values or not
278
            $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
279
            if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
280
                $add_save_lastsearch_values = 1;
281
            }
282
            if ($url && $add_save_lastsearch_values) {
283
                $url .= '&save_lastsearch_values=1';
284
            }
285
        }
286
287
        $linkclose = '';
288
        if (empty($notooltip)) {
289
            if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
290
                $label = $langs->trans("ShowMyObject");
291
                $linkclose .= ' alt="' . dol_escape_htmltag($label, 1) . '"';
292
            }
293
            $linkclose .= ' title="' . dol_escape_htmltag($label, 1) . '"';
294
            $linkclose .= ' class="classfortooltip' . ($morecss ? ' ' . $morecss : '') . '"';
295
        } else {
296
            $linkclose = ($morecss ? ' class="' . $morecss . '"' : '');
297
        }
298
299
        if ($option == 'nolink' || empty($url)) {
300
            $linkstart = '<span';
301
        } else {
302
            $linkstart = '<a href="' . $url . '"';
303
        }
304
        $linkstart .= $linkclose . '>';
305
        if ($option == 'nolink' || empty($url)) {
306
            $linkend = '</span>';
307
        } else {
308
            $linkend = '</a>';
309
        }
310
311
        $result .= $linkstart;
312
313
        if (empty($this->showphoto_on_popup)) {
314
            if ($withpicto) {
315
                $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="' . (($withpicto != 2) ? 'paddingright ' : '') . 'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
316
            }
317
        } else {
318
            if ($withpicto) {
319
                require_once constant('DOL_DOCUMENT_ROOT') . '/core/lib/files.lib.php';
320
321
                list($class, $module) = explode('@', $this->picto);
322
                $upload_dir = $conf->$module->multidir_output[$conf->entity] . "/$class/" . dol_sanitizeFileName($this->ref);
323
                $filearray = dol_dir_list($upload_dir, "files");
324
                $filename = $filearray[0]['name'];
325
                if (!empty($filename)) {
326
                    $pospoint = strpos($filearray[0]['name'], '.');
327
328
                    $pathtophoto = $class . '/' . $this->ref . '/thumbs/' . substr($filename, 0, $pospoint) . '_mini' . substr($filename, $pospoint);
329
                    if (!getDolGlobalString(strtoupper($module . '_' . $class) . '_FORMATLISTPHOTOSASUSERS')) {
330
                        $result .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref"><img class="photo' . $module . '" alt="No photo" border="0" src="' . constant('BASE_URL') . '/viewimage.php?modulepart=' . $module . '&entity=' . $conf->entity . '&file=' . urlencode($pathtophoto) . '"></div></div>';
331
                    } else {
332
                        $result .= '<div class="floatleft inline-block valignmiddle divphotoref"><img class="photouserphoto userphoto" alt="No photo" border="0" src="' . constant('BASE_URL') . '/viewimage.php?modulepart=' . $module . '&entity=' . $conf->entity . '&file=' . urlencode($pathtophoto) . '"></div>';
333
                    }
334
335
                    $result .= '</div>';
336
                } else {
337
                    $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="' . (($withpicto != 2) ? 'paddingright ' : '') . 'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
338
                }
339
            }
340
        }
341
342
        if ($withpicto != 2) {
343
            $result .= $this->ref;
344
        }
345
346
        $result .= $linkend;
347
        //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
348
349
        global $action, $hookmanager;
350
        $hookmanager->initHooks(array('myobjectdao'));
351
        $parameters = array('id' => $this->id, 'getnomurl' => &$result);
352
        $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
353
        if ($reshook > 0) {
354
            $result = $hookmanager->resPrint;
355
        } else {
356
            $result .= $hookmanager->resPrint;
357
        }
358
359
        return $result;
360
    }
361
362
    /**
363
     *  Return the label of the status
364
     *
365
     *  @param  int     $mode          0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
366
     *  @return string                 Label of status
367
     */
368
    public function getLibStatut($mode = 0)
369
    {
370
        return '';
371
    }
372
373
    /**
374
     *  Load the info information in the object
375
     *
376
     *  @param  int     $id       Id of object
377
     *  @return void
378
     */
379
    public function info($id)
380
    {
381
        $sql = "SELECT rowid, date_creation as datec, tms as datem,";
382
        $sql .= " fk_user_creat, fk_user_modif";
383
        $sql .= " FROM " . MAIN_DB_PREFIX . $this->table_element . " as t";
384
        $sql .= " WHERE t.rowid = " . ((int) $id);
385
386
        $result = $this->db->query($sql);
387
        if ($result) {
388
            if ($this->db->num_rows($result)) {
389
                $obj = $this->db->fetch_object($result);
390
391
                $this->id = $obj->rowid;
392
393
                $this->user_creation_id = $obj->fk_user_creat;
394
                $this->user_modification_id = $obj->fk_user_modif;
395
                $this->date_creation     = $this->db->jdate($obj->datec);
396
                $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
397
            }
398
399
            $this->db->free($result);
400
        } else {
401
            dol_print_error($this->db);
402
        }
403
    }
404
405
    /**
406
     * Initialise object with example values
407
     * Id must be 0 if object instance is a specimen
408
     *
409
     * @return int
410
     */
411
    public function initAsSpecimen()
412
    {
413
        // Set here init that are not commonf fields
414
        // $this->property1 = ...
415
        // $this->property2 = ...
416
417
        return $this->initAsSpecimenCommon();
418
    }
419
}
420