Completed
Branch develop (59ab9a)
by
unknown
27:43
created

MyModuleObject::fetchAll()   B

Complexity

Conditions 9
Paths 96

Size

Total Lines 54
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Importance

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