Completed
Branch develop (aca1c1)
by
unknown
24:57
created

Skeleton_Class::update()   C

Complexity

Conditions 9
Paths 128

Size

Total Lines 55
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
eloc 24
nc 128
nop 2
dl 0
loc 55
rs 6.6291
c 0
b 0
f 0

How to fix   Long Method   

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) 2007-2012  Laurent Destailleur <[email protected]>
3
 * Copyright (C) 2014-2016  Juanjo Menent       <[email protected]>
4
 * Copyright (C) 2015       Florian Henry       <[email protected]>
5
 * Copyright (C) 2015       Raphaël Doursenaud  <[email protected]>
6
 * Copyright (C) ---Put here your own copyright and developer email---
7
 *
8
 * This program is free software; you can redistribute it and/or modify
9
 * it under the terms of the GNU General Public License as published by
10
 * the Free Software Foundation; either version 3 of the License, or
11
 * (at your option) any later version.
12
 *
13
 * This program is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
 * GNU General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU General Public License
19
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20
 */
21
22
/**
23
 * \file    dev/skeletons/skeleton_class.class.php
24
 * \ingroup mymodule othermodule1 othermodule2
25
 * \brief   This file is an example for a CRUD class file (Create/Read/Update/Delete)
26
 *          Put some comments here
27
 */
28
29
// Put here all includes required by your class file
30
require_once DOL_DOCUMENT_ROOT . '/core/class/commonobject.class.php';
31
//require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
32
//require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
33
34
/**
35
 * Class Skeleton_Class
36
 *
37
 * Put here description of your class
38
 *
39
 * @see CommonObject
40
 */
41
class Skeleton_Class extends CommonObject
42
{
43
	/**
44
	 * @var string Id to identify managed objects
45
	 */
46
	public $element = 'skeleton';
47
	/**
48
	 * @var string Name of table without prefix where object is stored
49
	 */
50
	public $table_element = 'skeleton';
51
52
	/**
53
	 * @var Skeleton_ClassLine[] Lines
54
	 */
55
	public $lines = array();
56
57
	/**
58
	 * @var mixed Sample property 1
59
	 */
60
	public $prop1;
61
	/**
62
	 * @var mixed Sample property 2
63
	 */
64
	public $prop2;
65
	//...
66
67
	/**
68
	 * Constructor
69
	 *
70
	 * @param DoliDb $db Database handler
71
	 */
72
	public function __construct(DoliDB $db)
73
	{
74
		$this->db = $db;
75
	}
76
77
	/**
78
	 * Create object into database
79
	 *
80
	 * @param  User $user      User that creates
81
	 * @param  bool $notrigger false=launch triggers after, true=disable triggers
82
	 *
83
	 * @return int <0 if KO, Id of created object if OK
84
	 */
85
	public function create(User $user, $notrigger = false)
86
	{
87
		dol_syslog(__METHOD__, LOG_DEBUG);
88
89
		$error = 0;
90
91
		// Clean parameters
92
		if (isset($this->prop1)) {
93
			$this->prop1 = trim($this->prop1);
94
		}
95
		if (isset($this->prop2)) {
96
			$this->prop2 = trim($this->prop2);
97
		}
98
		//...
99
100
		// Check parameters
101
		// Put here code to add control on parameters values
102
103
		// Insert request
104
		$sql = 'INSERT INTO ' . MAIN_DB_PREFIX . $this->table_element . '(';
105
		$sql .= ' field1,';
106
		$sql .= ' field2';
107
		//...
108
		$sql .= ') VALUES (';
109
		$sql .= ' \'' . $this->prop1 . '\',';
110
		$sql .= ' \'' . $this->prop2 . '\'';
111
		//...
112
		$sql .= ')';
113
114
		$this->db->begin();
115
116
		$resql = $this->db->query($sql);
117
		if (!$resql) {
118
			$error ++;
119
			$this->errors[] = 'Error ' . $this->db->lasterror();
120
			dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
121
		}
122
123
		if (!$error) {
124
			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . $this->table_element);
125
126
			if (!$notrigger) {
127
				// Uncomment this and change MYOBJECT to your own tag if you
128
				// want this action to call a trigger.
129
130
				//// Call triggers
131
				//$result=$this->call_trigger('MYOBJECT_CREATE',$user);
132
				//if ($result < 0) $error++;
133
				//// End call triggers
134
			}
135
		}
136
137
		// Commit or rollback
138
		if ($error) {
139
			$this->db->rollback();
140
141
			return - 1 * $error;
142
		} else {
143
			$this->db->commit();
144
145
			return $this->id;
146
		}
147
	}
148
149
	/**
150
	 * Load object in memory from the database
151
	 *
152
	 * @param int    $id  Id object
153
	 * @param string $ref Ref
154
	 *
155
	 * @return int <0 if KO, 0 if not found, >0 if OK
156
	 */
157
	public function fetch($id, $ref = null)
158
	{
159
		dol_syslog(__METHOD__, LOG_DEBUG);
160
161
		$sql = 'SELECT';
162
		$sql .= ' t.rowid,';
163
		$sql .= ' t.field1,';
164
		$sql .= ' t.field2';
165
		//...
166
		$sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t';
167
		$sql.= ' WHERE 1 = 1';
168
		if (! empty($conf->multicompany->enabled)) {
0 ignored issues
show
Bug introduced by
The variable $conf 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...
169
		    $sql .= " AND entity IN (" . getEntity("skeleton", 1) . ")";
170
		}
171
		if (null !== $ref) {
172
			$sql .= ' AND t.ref = ' . '\'' . $ref . '\'';
173
		} else {
174
			$sql .= ' AND t.rowid = ' . $id;
175
		}
176
177
		$resql = $this->db->query($sql);
178
		if ($resql) {
179
			$numrows = $this->db->num_rows($resql);
180
			if ($numrows) {
181
				$obj = $this->db->fetch_object($resql);
182
183
				$this->id = $obj->rowid;
184
				$this->prop1 = $obj->field1;
185
				$this->prop2 = $obj->field2;
186
				//...
187
			}
188
			
189
			// Retrieve all extrafields for invoice
190
			// fetch optionals attributes and labels
191
			/*
192
			require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
193
			$extrafields=new ExtraFields($this->db);
194
			$extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true);
195
			$this->fetch_optionals($this->id,$extralabels);
196
            */
197
			
198
			// $this->fetch_lines();
199
			
200
			$this->db->free($resql);
201
202
			if ($numrows) {
203
				return 1;
204
			} else {
205
				return 0;
206
			}
207
		} else {
208
			$this->errors[] = 'Error ' . $this->db->lasterror();
209
			dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
210
211
			return - 1;
212
		}
213
	}
214
215
	/**
216
	 * Load object in memory from the database
217
	 *
218
	 * @param string $sortorder Sort Order
219
	 * @param string $sortfield Sort field
220
	 * @param int    $limit     offset limit
221
	 * @param int    $offset    offset limit
222
	 * @param array  $filter    filter array
223
	 * @param string $filtermode filter mode (AND or OR)
224
	 *
225
	 * @return int <0 if KO, >0 if OK
226
	 */
227
	public function fetchAll($sortorder='', $sortfield='', $limit=0, $offset=0, array $filter = array(), $filtermode='AND')
228
	{
229
		dol_syslog(__METHOD__, LOG_DEBUG);
230
231
		$sql = 'SELECT';
232
		$sql .= ' t.rowid,';
233
		$sql .= ' t.field1,';
234
		$sql .= ' t.field2';
235
		//...
236
		$sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element. ' as t';
237
238
		// Manage filter
239
		$sqlwhere = array();
240
		if (count($filter) > 0) {
241
			foreach ($filter as $key => $value) {
242
				$sqlwhere [] = $key . ' LIKE \'%' . $this->db->escape($value) . '%\'';
243
			}
244
		}
245
		$sql.= ' WHERE 1 = 1';
246
		if (! empty($conf->multicompany->enabled)) {
0 ignored issues
show
Bug introduced by
The variable $conf 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...
247
		    $sql .= " AND entity IN (" . getEntity("skeleton", 1) . ")";
248
		}
249
		if (count($sqlwhere) > 0) {
250
			$sql .= ' AND ' . implode(' '.$filtermode.' ', $sqlwhere);
251
		}
252
		if (!empty($sortfield)) {
253
			$sql .= $this->db->order($sortfield,$sortorder);
254
		}
255
		if (!empty($limit)) {
256
		 $sql .=  ' ' . $this->db->plimit($limit, $offset);
257
		}
258
259
		$resql = $this->db->query($sql);
260
		if ($resql) {
261
			$num = $this->db->num_rows($resql);
262
263
			while ($obj = $this->db->fetch_object($resql)) {
264
				$line = new self($this->db);
265
266
				$line->id = $obj->rowid;
267
				$line->prop1 = $obj->field1;
268
				$line->prop2 = $obj->field2;
269
				//...
270
			}
271
			$this->db->free($resql);
272
273
			return $num;
274
		} else {
275
			$this->errors[] = 'Error ' . $this->db->lasterror();
276
			dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
277
278
			return - 1;
279
		}
280
	}
281
282
	/**
283
	 * Update object into database
284
	 *
285
	 * @param  User $user      User that modifies
286
	 * @param  bool $notrigger false=launch triggers after, true=disable triggers
287
	 *
288
	 * @return int <0 if KO, >0 if OK
289
	 */
290
	public function update(User $user, $notrigger = false)
291
	{
292
		$error = 0;
293
294
		dol_syslog(__METHOD__, LOG_DEBUG);
295
296
		// Clean parameters
297
		if (isset($this->prop1)) {
298
			$this->prop1 = trim($this->prop1);
299
		}
300
		if (isset($this->prop2)) {
301
			$this->prop2 = trim($this->prop2);
302
		}
303
		//...
304
305
		// Check parameters
306
		// Put here code to add a control on parameters values
307
308
		// Update request
309
		$sql = 'UPDATE ' . MAIN_DB_PREFIX . $this->table_element . ' SET';
310
		$sql .= " field1=".(isset($this->field1)?"'".$this->db->escape($this->field1)."'":"null").",";
311
        $sql .= " field2=".(isset($this->field2)?"'".$this->db->escape($this->field2)."'":"null")."";
312
		//...
313
		$sql .= ' WHERE rowid=' . $this->id;
314
315
		$this->db->begin();
316
317
		$resql = $this->db->query($sql);
318
		if (!$resql) {
319
			$error ++;
320
			$this->errors[] = 'Error ' . $this->db->lasterror();
321
			dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
322
		}
323
324
		if (!$error && !$notrigger) {
325
			// Uncomment this and change MYOBJECT to your own tag if you
326
			// want this action calls a trigger.
327
328
			//// Call triggers
329
			//$result=$this->call_trigger('MYOBJECT_MODIFY',$user);
330
			//if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail}
331
			//// End call triggers
332
		}
333
334
		// Commit or rollback
335
		if ($error) {
336
			$this->db->rollback();
337
338
			return - 1 * $error;
339
		} else {
340
			$this->db->commit();
341
342
			return 1;
343
		}
344
	}
345
346
	/**
347
	 * Delete object in database
348
	 *
349
	 * @param User $user      User that deletes
350
	 * @param bool $notrigger false=launch triggers after, true=disable triggers
351
	 *
352
	 * @return int <0 if KO, >0 if OK
353
	 */
354
	public function delete(User $user, $notrigger = false)
355
	{
356
		dol_syslog(__METHOD__, LOG_DEBUG);
357
358
		$error = 0;
359
360
		$this->db->begin();
361
362
		if (!$error) {
363
			if (!$notrigger) {
364
				// Uncomment this and change MYOBJECT to your own tag if you
365
				// want this action calls a trigger.
366
367
				//// Call triggers
368
				//$result=$this->call_trigger('MYOBJECT_DELETE',$user);
369
				//if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail}
370
				//// End call triggers
371
			}
372
		}
373
374
		// If you need to delete child tables to, you can insert them here
375
		
376
		if (!$error) {
377
			$sql = 'DELETE FROM ' . MAIN_DB_PREFIX . $this->table_element;
378
			$sql .= ' WHERE rowid=' . $this->id;
379
380
			$resql = $this->db->query($sql);
381
			if (!$resql) {
382
				$error ++;
383
				$this->errors[] = 'Error ' . $this->db->lasterror();
384
				dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
385
			}
386
		}
387
388
		// Commit or rollback
389
		if ($error) {
390
			$this->db->rollback();
391
392
			return - 1 * $error;
393
		} else {
394
			$this->db->commit();
395
396
			return 1;
397
		}
398
	}
399
400
	/**
401
	 * Load an object from its id and create a new one in database
402
	 *
403
	 * @param int $fromid Id of object to clone
404
	 *
405
	 * @return int New id of clone
406
	 */
407
	public function createFromClone($fromid)
408
	{
409
		dol_syslog(__METHOD__, LOG_DEBUG);
410
411
		global $user;
412
		$error = 0;
413
		$object = new Skeleton_Class($this->db);
414
415
		$this->db->begin();
416
417
		// Load source object
418
		$object->fetch($fromid);
419
		// Reset object
420
		$object->id = 0;
421
422
		// Clear fields
423
		// ...
424
425
		// Create clone
426
		$result = $object->create($user);
427
428
		// Other options
429
		if ($result < 0) {
430
			$error ++;
431
			$this->errors = $object->errors;
432
			dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
433
		}
434
435
		// End
436
		if (!$error) {
437
			$this->db->commit();
438
439
			return $object->id;
440
		} else {
441
			$this->db->rollback();
442
443
			return - 1;
444
		}
445
	}
446
447
	/**
448
	 *  Return a link to the object card (with optionaly the picto)
449
	 *
450
	 *	@param	int		$withpicto			Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
451
	 *	@param	string	$option				On what the link point to
452
     *  @param	int  	$notooltip			1=Disable tooltip
453
     *  @param	int		$maxlen				Max length of visible user name
454
     *  @param  string  $morecss            Add more css on link
455
	 *	@return	string						String with URL
456
	 */
457
	function getNomUrl($withpicto=0, $option='', $notooltip=0, $maxlen=24, $morecss='')
458
	{
459
		global $db, $conf, $langs;
460
        global $dolibarr_main_authentication, $dolibarr_main_demo;
461
        global $menumanager;
462
463
        if (! empty($conf->dol_no_mouse_hover)) $notooltip=1;   // Force disable tooltips
464
        
465
        $result = '';
466
        $companylink = '';
467
468
        $label = '<u>' . $langs->trans("MyModule") . '</u>';
469
        $label.= '<br>';
470
        $label.= '<b>' . $langs->trans('Ref') . ':</b> ' . $this->ref;
471
472
        $url = DOL_URL_ROOT.'/mymodule/'.$this->table_name.'_card.php?id='.$this->id;
473
        
474
        $linkclose='';
475
        if (empty($notooltip))
476
        {
477
            if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
478
            {
479
                $label=$langs->trans("ShowProject");
480
                $linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"';
481
            }
482
            $linkclose.=' title="'.dol_escape_htmltag($label, 1).'"';
483
            $linkclose.=' class="classfortooltip'.($morecss?' '.$morecss:'').'"';
484
        }
485
        else $linkclose = ($morecss?' class="'.$morecss.'"':'');
486
        
487
		$linkstart = '<a href="'.$url.'"';
488
		$linkstart.=$linkclose.'>';
489
		$linkend='</a>';
490
491
        if ($withpicto)
492
        {
493
            $result.=($linkstart.img_object(($notooltip?'':$label), 'label', ($notooltip?'':'class="classfortooltip"')).$linkend);
494
            if ($withpicto != 2) $result.=' ';
495
		}
496
		$result.= $linkstart . $this->ref . $linkend;
497
		return $result;
498
	}
499
500
	/**
501
	 *  Retourne le libelle du status d'un user (actif, inactif)
502
	 *
503
	 *  @param	int		$mode          0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
504
	 *  @return	string 			       Label of status
505
	 */
506
	function getLibStatut($mode=0)
507
	{
508
		return $this->LibStatut($this->status,$mode);
509
	}
510
511
	/**
512
	 *  Return the status
513
	 *
514
	 *  @param	int		$status        	Id status
515
	 *  @param  int		$mode          	0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 5=Long label + Picto
516
	 *  @return string 			       	Label of status
517
	 */
518
	static function LibStatut($status,$mode=0)
519
	{
520
		global $langs;
521
522
		if ($mode == 0)
523
		{
524
			$prefix='';
525
			if ($status == 1) return $langs->trans('Enabled');
526
			if ($status == 0) return $langs->trans('Disabled');
527
		}
528
		if ($mode == 1)
529
		{
530
			if ($status == 1) return $langs->trans('Enabled');
531
			if ($status == 0) return $langs->trans('Disabled');
532
		}
533
		if ($mode == 2)
534
		{
535
			if ($status == 1) return img_picto($langs->trans('Enabled'),'statut4').' '.$langs->trans('Enabled');
536
			if ($status == 0) return img_picto($langs->trans('Disabled'),'statut5').' '.$langs->trans('Disabled');
537
		}
538
		if ($mode == 3)
539
		{
540
			if ($status == 1) return img_picto($langs->trans('Enabled'),'statut4');
541
			if ($status == 0) return img_picto($langs->trans('Disabled'),'statut5');
542
		}
543
		if ($mode == 4)
544
		{
545
			if ($status == 1) return img_picto($langs->trans('Enabled'),'statut4').' '.$langs->trans('Enabled');
546
			if ($status == 0) return img_picto($langs->trans('Disabled'),'statut5').' '.$langs->trans('Disabled');
547
		}
548
		if ($mode == 5)
549
		{
550
			if ($status == 1) return $langs->trans('Enabled').' '.img_picto($langs->trans('Enabled'),'statut4');
551
			if ($status == 0) return $langs->trans('Disabled').' '.img_picto($langs->trans('Disabled'),'statut5');
552
		}
553
		if ($mode == 6)
554
		{
555
			if ($status == 1) return $langs->trans('Enabled').' '.img_picto($langs->trans('Enabled'),'statut4');
556
			if ($status == 0) return $langs->trans('Disabled').' '.img_picto($langs->trans('Disabled'),'statut5');
557
		}
558
	}
559
560
561
	/**
562
	 * Initialise object with example values
563
	 * Id must be 0 if object instance is a specimen
564
	 *
565
	 * @return void
566
	 */
567
	public function initAsSpecimen()
568
	{
569
		$this->id = 0;
570
		$this->prop1 = 'prop1';
571
		$this->prop2 = 'prop2';
572
	}
573
574
}
575
576
/**
577
 * Class Skeleton_ClassLine
578
 */
579
class Skeleton_ClassLine
580
{
581
	/**
582
	 * @var int ID
583
	 */
584
	public $id;
585
	/**
586
	 * @var mixed Sample line property 1
587
	 */
588
	public $prop1;
589
	/**
590
	 * @var mixed Sample line property 2
591
	 */
592
	public $prop2;
593
}
594