Completed
Branch develop (a0152f)
by
unknown
34:49
created

MyObject::LibStatut()   D

Complexity

Conditions 19
Paths 192

Size

Total Lines 44
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 19
eloc 24
nc 192
nop 2
dl 0
loc 44
rs 4.6463
c 0
b 0
f 0

How to fix   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
/* Copyright (C) 2017  Laurent Destailleur <[email protected]>
3
 * Copyright (C) ---Put here your own copyright and developer email---
4
 *
5
 * This program is free software; you can redistribute it and/or modify
6
 * it under the terms of the GNU General Public License as published by
7
 * the Free Software Foundation; either version 3 of the License, or
8
 * (at your option) any later version.
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.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17
 */
18
19
/**
20
 * \file        htdocs/modulebuilder/template/class/myobject.class.php
21
 * \ingroup     mymodule
22
 * \brief       This file is a CRUD class file for MyObject (Create/Read/Update/Delete)
23
 */
24
25
// Put here all includes required by your class file
26
require_once DOL_DOCUMENT_ROOT . '/core/class/commonobject.class.php';
27
//require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
28
//require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
29
30
/**
31
 * Class for MyObject
32
 */
33
class MyObject extends CommonObject
34
{
35
	/**
36
	 * @var string ID to identify managed object
37
	 */
38
	public $element = 'myobject';
39
	/**
40
	 * @var string Name of table without prefix where object is stored
41
	 */
42
	public $table_element = 'mymodule_myobject';
43
	/**
44
	 * @var int  Does myobject support multicompany module ? 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
45
	 */
46
	public $ismultientitymanaged = 0;
47
	/**
48
	 * @var int  Does myobject support extrafields ? 0=No, 1=Yes
49
	 */
50
	public $isextrafieldmanaged = 1;
51
	/**
52
	 * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png
53
	 */
54
	public $picto = 'myobject@mymodule';
55
56
57
	/**
58
	 *  'type' if the field format.
59
	 *  'label' the translation key.
60
	 *  'enabled' is a condition when the field must be managed.
61
	 *  'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only. Using a negative value means field is not shown by default on list but can be selected for viewing)
62
	 *  'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
63
	 *  'default' is a default value for creation (can still be replaced by the global setup of default values)
64
	 *  'index' if we want an index in database.
65
	 *  'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
66
	 *  'position' is the sort order of field.
67
	 *  'searchall' is 1 if we want to search in this field when making a search from the quick search button.
68
	 *  'isameasure' must be set to 1 if you want to have a total on list for this field. Field type must be summable like integer or double(24,8).
69
	 *  'help' is a string visible as a tooltip on field
70
	 *  'comment' is not used. You can store here any text of your choice. It is not used by application.
71
	 *  'showoncombobox' if value of the field must be visible into the label of the combobox that list record
72
	 *  'arraykeyval' to set list of value if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel")
73
	 */
74
75
	// BEGIN MODULEBUILDER PROPERTIES
76
	/**
77
     * @var array  Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
78
     */
79
	public $fields=array(
80
	    'rowid'         =>array('type'=>'integer',      'label'=>'TechnicalID',      'enabled'=>1, 'visible'=>-2, 'notnull'=>1,  'index'=>1, 'position'=>1, 'comment'=>'Id'),
81
		'ref'           =>array('type'=>'varchar(128)', 'label'=>'Ref',              'enabled'=>1, 'visible'=>1,  'notnull'=>1,  'showoncombobox'=>1, 'index'=>1, 'position'=>10, 'searchall'=>1, 'comment'=>'Reference of object'),
82
	    'entity'        =>array('type'=>'integer',      'label'=>'Entity',           'enabled'=>1, 'visible'=>0,  'default'=>1, 'notnull'=>1,  'index'=>1, 'position'=>20),
83
	    'label'         =>array('type'=>'varchar(255)', 'label'=>'Label',            'enabled'=>1, 'visible'=>1,  'position'=>30,  'searchall'=>1, 'css'=>'minwidth200', 'help'=>'Help text', 'showoncombobox'=>1),
84
	    'amount'        =>array('type'=>'double(24,8)', 'label'=>'Amount',           'enabled'=>1, 'visible'=>1,  'default'=>'null', 'position'=>40,  'searchall'=>0, 'isameasure'=>1, 'help'=>'Help text'),
85
		'fk_soc' 		=>array('type'=>'integer:Societe:societe/class/societe.class.php', 'label'=>'ThirdParty', 'visible'=>1, 'enabled'=>1, 'position'=>50, 'notnull'=>-1, 'index'=>1, 'help'=>'LinkToThirparty'),
86
		'description'   =>array('type'=>'text',			'label'=>'Descrption',		 'enabled'=>1, 'visible'=>0,  'position'=>60),
87
		'note_public'   =>array('type'=>'html',			'label'=>'NotePublic',		 'enabled'=>1, 'visible'=>0,  'position'=>61),
88
		'note_private'  =>array('type'=>'html',			'label'=>'NotePrivate',		 'enabled'=>1, 'visible'=>0,  'position'=>62),
89
		'date_creation' =>array('type'=>'datetime',     'label'=>'DateCreation',     'enabled'=>1, 'visible'=>-2, 'notnull'=>1,  'position'=>500),
90
	    'tms'           =>array('type'=>'timestamp',    'label'=>'DateModification', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1,  'position'=>501),
91
		//'date_valid'    =>array('type'=>'datetime',     'label'=>'DateCreation',     'enabled'=>1, 'visible'=>-2, 'position'=>502),
92
		'fk_user_creat' =>array('type'=>'integer',      'label'=>'UserAuthor',       'enabled'=>1, 'visible'=>-2, 'notnull'=>1,  'position'=>510, 'foreignkey'=>'llx_user.rowid'),
93
		'fk_user_modif' =>array('type'=>'integer',      'label'=>'UserModif',        'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>511),
94
		//'fk_user_valid' =>array('type'=>'integer',      'label'=>'UserValidation',        'enabled'=>1, 'visible'=>-1, 'position'=>512),
95
		'import_key'    =>array('type'=>'varchar(14)',  'label'=>'ImportId',         'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'index'=>0,  'position'=>1000),
96
	    'status'        =>array('type'=>'integer',      'label'=>'Status',           'enabled'=>1, 'visible'=>1,  'notnull'=>1, 'default'=>0, 'index'=>1,  'position'=>1000, 'arrayofkeyval'=>array(0=>'Draft', 1=>'Active', -1=>'Cancel')),
97
	);
98
99
	public $rowid;
100
	public $ref;
101
	public $entity;
102
	public $label;
103
	public $amount;
104
	public $status;
105
	public $date_creation;
106
	public $tms;
107
	public $fk_user_creat;
108
	public $fk_user_modif;
109
	public $import_key;
110
	// END MODULEBUILDER PROPERTIES
111
112
113
114
	// If this object has a subtable with lines
115
116
	/**
117
	 * @var int    Name of subtable line
118
	 */
119
	//public $table_element_line = 'myobjectdet';
120
	/**
121
	 * @var int    Field with ID of parent key if this field has a parent
122
	 */
123
	//public $fk_element = 'fk_myobject';
124
	/**
125
	 * @var int    Name of subtable class that manage subtable lines
126
	 */
127
	//public $class_element_line = 'MyObjectline';
128
	/**
129
	 * @var array  Array of child tables (child tables to delete before deleting a record)
130
	 */
131
	//protected $childtables=array('myobjectdet');
132
	/**
133
	 * @var MyObjectLine[]     Array of subtable lines
134
	 */
135
	//public $lines = array();
136
137
138
139
	/**
140
	 * Constructor
141
	 *
142
	 * @param DoliDb $db Database handler
143
	 */
144
	public function __construct(DoliDB $db)
145
	{
146
		global $conf, $user;
147
148
		$this->db = $db;
149
150
		if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) $this->fields['rowid']['visible']=0;
151
		if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) $this->fields['entity']['enabled']=0;
152
153
		// Unset fields that are disabled
154
		foreach($this->fields as $key => $val)
155
		{
156
			if (isset($val['enabled']) && empty($val['enabled']))
157
			{
158
				unset($this->fields[$key]);
159
			}
160
		}
161
	}
162
163
	/**
164
	 * Create object into database
165
	 *
166
	 * @param  User $user      User that creates
167
	 * @param  bool $notrigger false=launch triggers after, true=disable triggers
168
	 * @return int             <0 if KO, Id of created object if OK
169
	 */
170
	public function create(User $user, $notrigger = false)
171
	{
172
		return $this->createCommon($user, $notrigger);
173
	}
174
175
	/**
176
	 * Clone and object into another one
177
	 *
178
	 * @param  	User 	$user      	User that creates
179
	 * @param  	int 	$fromid     Id of object to clone
180
	 * @return 	mixed 				New object created, <0 if KO
181
	 */
182
	public function createFromClone(User $user, $fromid)
183
	{
184
		global $hookmanager, $langs;
185
	    $error = 0;
186
187
	    dol_syslog(__METHOD__, LOG_DEBUG);
188
189
	    $object = new self($this->db);
190
191
	    $this->db->begin();
192
193
	    // Load source object
194
	    $object->fetchCommon($fromid);
195
	    // Reset some properties
196
	    unset($object->id);
197
	    unset($object->fk_user_creat);
198
	    unset($object->import_key);
199
200
	    // Clear fields
201
	    $object->ref = "copy_of_".$object->ref;
202
	    $object->title = $langs->trans("CopyOf")." ".$object->title;
203
	    // ...
204
205
	    // Create clone
206
		$object->context['createfromclone'] = 'createfromclone';
207
	    $result = $object->createCommon($user);
208
	    if ($result < 0) {
209
	        $error++;
210
	        $this->error = $object->error;
211
	        $this->errors = $object->errors;
212
	    }
213
214
	    // End
215
	    if (!$error) {
216
	        $this->db->commit();
217
	        return $object;
218
	    } else {
219
	        $this->db->rollback();
220
	        return -1;
221
	    }
222
	}
223
224
	/**
225
	 * Load object in memory from the database
226
	 *
227
	 * @param int    $id   Id object
228
	 * @param string $ref  Ref
229
	 * @return int         <0 if KO, 0 if not found, >0 if OK
230
	 */
231
	public function fetch($id, $ref = null)
232
	{
233
		$result = $this->fetchCommon($id, $ref);
234
		if ($result > 0 && ! empty($this->table_element_line)) $this->fetchLines();
0 ignored issues
show
Bug introduced by
The method fetchLines() does not seem to exist on object<MyObject>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
235
		return $result;
236
	}
237
238
	/**
239
	 * Load object lines in memory from the database
240
	 *
241
	 * @return int         <0 if KO, 0 if not found, >0 if OK
242
	 */
243
	/*public function fetchLines()
244
	{
245
		$this->lines=array();
246
247
		// Load lines with object MyObjectLine
248
249
		return count($this->lines)?1:0;
250
	}*/
251
252
	/**
253
	 * Update object into database
254
	 *
255
	 * @param  User $user      User that modifies
256
	 * @param  bool $notrigger false=launch triggers after, true=disable triggers
257
	 * @return int             <0 if KO, >0 if OK
258
	 */
259
	public function update(User $user, $notrigger = false)
260
	{
261
		return $this->updateCommon($user, $notrigger);
262
	}
263
264
	/**
265
	 * Delete object in database
266
	 *
267
	 * @param User $user       User that deletes
268
	 * @param bool $notrigger  false=launch triggers after, true=disable triggers
269
	 * @return int             <0 if KO, >0 if OK
270
	 */
271
	public function delete(User $user, $notrigger = false)
272
	{
273
		return $this->deleteCommon($user, $notrigger);
274
	}
275
276
	/**
277
	 *  Return a link to the object card (with optionaly the picto)
278
	 *
279
	 *	@param	int		$withpicto					Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
280
	 *	@param	string	$option						On what the link point to ('nolink', ...)
281
     *  @param	int  	$notooltip					1=Disable tooltip
282
     *  @param  string  $morecss            		Add more css on link
283
     *  @param  int     $save_lastsearch_value    	-1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
284
	 *	@return	string								String with URL
285
	 */
286
	function getNomUrl($withpicto=0, $option='', $notooltip=0, $morecss='', $save_lastsearch_value=-1)
287
	{
288
		global $db, $conf, $langs;
289
        global $dolibarr_main_authentication, $dolibarr_main_demo;
290
        global $menumanager;
291
292
        if (! empty($conf->dol_no_mouse_hover)) $notooltip=1;   // Force disable tooltips
293
294
        $result = '';
295
        $companylink = '';
296
297
        $label = '<u>' . $langs->trans("MyObject") . '</u>';
298
        $label.= '<br>';
299
        $label.= '<b>' . $langs->trans('Ref') . ':</b> ' . $this->ref;
300
301
        $url = dol_buildpath('/mymodule/myobject_card.php',1).'?id='.$this->id;
302
303
        if ($option != 'nolink')
304
        {
305
	        // Add param to save lastsearch_values or not
306
	        $add_save_lastsearch_values=($save_lastsearch_value == 1 ? 1 : 0);
307
	        if ($save_lastsearch_value == -1 && preg_match('/list\.php/',$_SERVER["PHP_SELF"])) $add_save_lastsearch_values=1;
308
	        if ($add_save_lastsearch_values) $url.='&save_lastsearch_values=1';
309
        }
310
311
        $linkclose='';
312
        if (empty($notooltip))
313
        {
314
            if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
315
            {
316
                $label=$langs->trans("ShowMyObject");
317
                $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"';
318
            }
319
            $linkclose.=' title="'.dol_escape_htmltag($label, 1).'"';
320
            $linkclose.=' class="classfortooltip'.($morecss?' '.$morecss:'').'"';
321
        }
322
        else $linkclose = ($morecss?' class="'.$morecss.'"':'');
323
324
		$linkstart = '<a href="'.$url.'"';
325
		$linkstart.=$linkclose.'>';
326
		$linkend='</a>';
327
328
		$result .= $linkstart;
329
		if ($withpicto) $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);
330
		if ($withpicto != 2) $result.= $this->ref;
331
		$result .= $linkend;
332
		//if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
333
334
		return $result;
335
	}
336
337
	/**
338
	 *  Return label of the status
339
	 *
340
	 *  @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
341
	 *  @return	string 			       Label of status
342
	 */
343
	function getLibStatut($mode=0)
344
	{
345
		return $this->LibStatut($this->status, $mode);
346
	}
347
348
	/**
349
	 *  Return the status
350
	 *
351
	 *  @param	int		$status        Id status
352
	 *  @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
353
	 *  @return string 			       Label of status
354
	 */
355
	static function LibStatut($status, $mode=0)
356
	{
357
		if (empty($this->labelstatus))
358
		{
359
			global $langs;
360
			//$langs->load("mymodule");
361
			$this->labelstatus[1] = $langs->trans('Enabled');
0 ignored issues
show
Bug introduced by
The variable $this does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
362
			$this->labelstatus[0] = $langs->trans('Disabled');
363
		}
364
365
		if ($mode == 0)
366
		{
367
			return $this->labelstatus[$status];
368
		}
369
		if ($mode == 1)
370
		{
371
			return $this->labelstatus[$status];
372
		}
373
		if ($mode == 2)
374
		{
375
			if ($status == 1) return img_picto($this->labelstatus[$status],'statut4').' '.$this->labelstatus[$status];
376
			if ($status == 0) return img_picto($this->labelstatus[$status],'statut5').' '.$this->labelstatus[$status];
377
		}
378
		if ($mode == 3)
379
		{
380
			if ($status == 1) return img_picto($this->labelstatus[$status],'statut4');
381
			if ($status == 0) return img_picto($this->labelstatus[$status],'statut5');
382
		}
383
		if ($mode == 4)
384
		{
385
			if ($status == 1) return img_picto($this->labelstatus[$status],'statut4').' '.$this->labelstatus[$status];
386
			if ($status == 0) return img_picto($this->labelstatus[$status],'statut5').' '.$this->labelstatus[$status];
387
		}
388
		if ($mode == 5)
389
		{
390
			if ($status == 1) return $this->labelstatus[$status].' '.img_picto($this->labelstatus[$status],'statut4');
391
			if ($status == 0) return $this->labelstatus[$status].' '.img_picto($this->labelstatus[$status],'statut5');
392
		}
393
		if ($mode == 6)
394
		{
395
			if ($status == 1) return $this->labelstatus[$status].' '.img_picto($this->labelstatus[$status],'statut4');
396
			if ($status == 0) return $this->labelstatus[$status].' '.img_picto($this->labelstatus[$status],'statut5');
397
		}
398
	}
399
400
	/**
401
	 *	Charge les informations d'ordre info dans l'objet commande
402
	 *
403
	 *	@param  int		$id       Id of order
404
	 *	@return	void
405
	 */
406
	function info($id)
407
	{
408
		$sql = 'SELECT rowid, date_creation as datec, tms as datem,';
409
		$sql.= ' fk_user_creat, fk_user_modif';
410
		$sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
411
		$sql.= ' WHERE t.rowid = '.$id;
412
		$result=$this->db->query($sql);
413
		if ($result)
414
		{
415
			if ($this->db->num_rows($result))
416
			{
417
				$obj = $this->db->fetch_object($result);
418
				$this->id = $obj->rowid;
419
				if ($obj->fk_user_author)
420
				{
421
					$cuser = new User($this->db);
422
					$cuser->fetch($obj->fk_user_author);
423
					$this->user_creation   = $cuser;
424
				}
425
426
				if ($obj->fk_user_valid)
427
				{
428
					$vuser = new User($this->db);
429
					$vuser->fetch($obj->fk_user_valid);
430
					$this->user_validation = $vuser;
431
				}
432
433
				if ($obj->fk_user_cloture)
434
				{
435
					$cluser = new User($this->db);
436
					$cluser->fetch($obj->fk_user_cloture);
437
					$this->user_cloture   = $cluser;
438
				}
439
440
				$this->date_creation     = $this->db->jdate($obj->datec);
441
				$this->date_modification = $this->db->jdate($obj->datem);
442
				$this->date_validation   = $this->db->jdate($obj->datev);
443
			}
444
445
			$this->db->free($result);
446
447
		}
448
		else
449
		{
450
			dol_print_error($this->db);
451
		}
452
	}
453
454
	/**
455
	 * Initialise object with example values
456
	 * Id must be 0 if object instance is a specimen
457
	 *
458
	 * @return void
459
	 */
460
	public function initAsSpecimen()
461
	{
462
		$this->initAsSpecimenCommon();
463
	}
464
465
466
	/**
467
	 * Action executed by scheduler
468
	 * CAN BE A CRON TASK. In such a case, paramerts come from the schedule job setup field 'Parameters'
469
	 *
470
	 * @return	int			0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK)
471
	 */
472
	//public function doScheduledJob($param1, $param2, ...)
473
	public function doScheduledJob()
474
	{
475
		global $conf, $langs;
476
477
		//$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlofile.log';
478
479
		$error = 0;
480
		$this->output = '';
481
		$this->error='';
482
483
		dol_syslog(__METHOD__, LOG_DEBUG);
484
485
		$now = dol_now();
486
487
		$this->db->begin();
488
489
		// ...
490
491
		$this->db->commit();
492
493
		return $error;
494
	}
495
}
496
497
/**
498
 * Class MyObjectLine. You can also remove this and generate a CRUD class for lines objects.
499
 */
500
/*
501
class MyObjectLine
502
{
503
	// @var int ID
504
	public $id;
505
	// @var mixed Sample line property 1
506
	public $prop1;
507
	// @var mixed Sample line property 2
508
	public $prop2;
509
}
510
*/