Completed
Push — master ( 0a5acd...43aa97 )
by Guilherme Luiz Argentino
05:40
created

ObjectModel   D

Complexity

Total Complexity 214

Size/Duplication

Total Lines 711
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
dl 0
loc 711
rs 4.4444
c 0
b 0
f 0
wmc 214
lcom 1
cbo 3

23 Methods

Rating   Name   Duplication   Size   Complexity  
A getValidationRules() 0 11 1
A getFields() 0 1 1
C __construct() 0 60 23
A save() 0 4 2
C add() 0 37 14
C update() 0 43 12
B delete() 0 17 5
B deleteSelection() 0 12 6
A toggleStatus() 0 18 4
A getTranslationsFields() 0 16 4
B makeTranslationFields() 0 20 12
D validateFields() 0 26 18
D validateFieldsLang() 0 40 23
B displayFieldName() 0 9 5
A validateControler() 0 4 1
D validateController() 0 39 17
F getWebserviceParameters() 0 129 37
A getWebserviceObjectList() 0 11 3
A getFieldsRequiredDatabase() 0 7 2
B addFieldsRequiredDatabase() 0 13 5
B clearCache() 0 7 5
C deleteImage() 0 26 12
A existsInDatabase() 0 15 2

How to fix   Complexity   

Complex Class

Complex classes like ObjectModel often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use ObjectModel, and based on these observations, apply Extract Interface, too.

1
<?php
2
/*
3
* 2007-2012 PrestaShop
4
*
5
* NOTICE OF LICENSE
6
*
7
* This source file is subject to the Open Software License (OSL 3.0)
8
* that is bundled with this package in the file LICENSE.txt.
9
* It is also available through the world-wide-web at this URL:
10
* http://opensource.org/licenses/osl-3.0.php
11
* If you did not receive a copy of the license and are unable to
12
* obtain it through the world-wide-web, please send an email
13
* to [email protected] so we can send you a copy immediately.
14
*
15
* DISCLAIMER
16
*
17
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
18
* versions in the future. If you wish to customize PrestaShop for your
19
* needs please refer to http://www.prestashop.com for more information.
20
*
21
*  @author PrestaShop SA <[email protected]>
22
*  @copyright  2007-2012 PrestaShop SA
23
*  @version  Release: $Revision: 14248 $
24
*  @license    http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
25
*  International Registered Trademark & Property of PrestaShop SA
26
*/
27
28
abstract class ObjectModel
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
29
{
30
	/** @var integer Object id */
31
	public $id;
32
33
	/** @var integer lang id */
34
	protected $id_lang = NULL;
35
	
36
	/** @var string SQL Table name */
37
	protected $table = NULL;
38
39
	/** @var string SQL Table identifier */
40
	protected $identifier = NULL;
41
42
	/** @var array Required fields for admin panel forms */
43
 	protected $fieldsRequired = array();
44
45
	/** @var fieldsRequiredDatabase */
46
	protected static $fieldsRequiredDatabase = NULL;
47
48
 	/** @var array Maximum fields size for admin panel forms */
49
 	protected $fieldsSize = array();
50
51
 	/** @var array Fields validity functions for admin panel forms */
52
 	protected $fieldsValidate = array();
53
54
	/** @var array Multilingual required fields for admin panel forms */
55
 	protected $fieldsRequiredLang = array();
56
57
 	/** @var array Multilingual maximum fields size for admin panel forms */
58
 	protected $fieldsSizeLang = array();
59
60
 	/** @var array Multilingual fields validity functions for admin panel forms */
61
 	protected $fieldsValidateLang = array();
62
63
	/** @var array tables */
64
 	protected $tables = array();
65
66
 	/** @var array tables */
67
 	protected $webserviceParameters = array();
68
69
	protected static $_cache = array();
70
	
71
	/** @var  string path to image directory. Used for image deletion. */
72
	protected $image_dir = NULL;
73
	
74
	/** @var string file type of image files. Used for image deletion. */
75
	protected $image_format = 'jpg';
76
77
	/**
78
	 * Returns object validation rules (fields validity)
79
	 *
80
	 * @param string $className Child class name for static use (optional)
81
	 * @return array Validation rules (fields validity)
82
	 */
83
	public static function getValidationRules($className = __CLASS__)
84
	{
85
		$object = new $className();
86
		return array(
87
		'required' => $object->fieldsRequired,
88
		'size' => $object->fieldsSize,
89
		'validate' => $object->fieldsValidate,
90
		'requiredLang' => $object->fieldsRequiredLang,
91
		'sizeLang' => $object->fieldsSizeLang,
92
		'validateLang' => $object->fieldsValidateLang);
93
	}
94
95
	/**
96
	 * Prepare fields for ObjectModel class (add, update)
97
	 * All fields are verified (pSQL, intval...)
98
	 *
99
	 * @return array All object fields
100
	 */
101
	public function getFields()	{ return array(); }
102
103
	/**
104
	 * Build object
105
	 *
106
	 * @param integer $id Existing object id in order to load object (optional)
107
	 * @param integer $id_lang Required if object is multilingual (optional)
108
	 */
109
	public function __construct($id = NULL, $id_lang = NULL)
110
	{
111
		if ($id_lang != NULL && Validate::isLoadedObject(new Language($id_lang)))
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing $id_lang of type integer|null against null; this is ambiguous if the integer can be zero. Consider using a strict comparison !== instead.
Loading history...
112
			$this->id_lang = $id_lang;
113
		elseif ($id_lang != NULL)
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing $id_lang of type integer|null against null; this is ambiguous if the integer can be zero. Consider using a strict comparison !== instead.
Loading history...
114
			$this->id_lang = Configuration::get('PS_LANG_DEFAULT');
0 ignored issues
show
Documentation Bug introduced by
It seems like \Configuration::get('PS_LANG_DEFAULT') can also be of type string. However, the property $id_lang is declared as type integer. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
115
			
116
	 	/* Connect to database and check SQL table/identifier */
117
	 	if (!Validate::isTableOrIdentifier($this->identifier) OR !Validate::isTableOrIdentifier($this->table))
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
118
			die(Tools::displayError());
0 ignored issues
show
Coding Style Compatibility introduced by
The method __construct() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
119
		$this->identifier = pSQL($this->identifier);
120
121
		/* Load object from database if object id is present */
122
		if ($id)
0 ignored issues
show
Bug Best Practice introduced by
The expression $id of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
123
		{
124
			if (!isset(self::$_cache[$this->table][(int)($id)][(int)($id_lang)]))
125
				self::$_cache[$this->table][(int)($id)][(int)($id_lang)] = Db::getInstance()->getRow('
126
				SELECT *
127
				FROM `'._DB_PREFIX_.$this->table.'` a '.
128
				($id_lang ? ('LEFT JOIN `'.pSQL(_DB_PREFIX_.$this->table).'_lang` b ON (a.`'.$this->identifier.'` = b.`'.$this->identifier).'` AND `id_lang` = '.(int)($id_lang).')' : '')
129
				.' WHERE a.`'.$this->identifier.'` = '.(int)($id));
130
131
			$result = self::$_cache[$this->table][(int)($id)][(int)($id_lang)];
132
			if ($result)
133
			{
134
				$this->id = (int)($id);
135
				foreach ($result AS $key => $value)
136
					if (key_exists($key, $this))
137
						$this->{$key} = $value;
138
	
139
				/* Join multilingual tables */
140
				if (!$id_lang AND method_exists($this, 'getTranslationsFieldsChild'))
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
141
				{
142
					$result = Db::getInstance()->ExecuteS('
143
					SELECT * 
144
					FROM `'.pSQL(_DB_PREFIX_.$this->table).'_lang` 
145
					WHERE `'.$this->identifier.'` = '.(int)$id);
146
					if ($result)
147
						foreach ($result AS $row)
148
							foreach ($row AS $key => $value)
149
								if (key_exists($key, $this) AND $key != $this->identifier)
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
150
								{
151
									if (!is_array($this->{$key}))
152
										$this->{$key} = array();
153
									$this->{$key}[(int)$row['id_lang']] = $value;
154
								}
155
				}
156
			}
157
		}
158
159
		if (!is_array(self::$fieldsRequiredDatabase))
160
		{
161
			$fields = $this->getfieldsRequiredDatabase(true);
162
			if ($fields)
163
				foreach ($fields AS $row)
164
					self::$fieldsRequiredDatabase[$row['object_name']][(int)$row['id_required_field']] = pSQL($row['field_name']);
165
			else
166
				self::$fieldsRequiredDatabase = array();
0 ignored issues
show
Documentation Bug introduced by
It seems like array() of type array is incompatible with the declared type object<fieldsRequiredDatabase> of property $fieldsRequiredDatabase.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
167
		}
168
	}
169
170
	/**
171
	 * Save current object to database (add or update)
172
	 *
173
	 * return boolean Insertion result
174
	 */
175
	public function save($nullValues = false, $autodate = true)
176
	{
177
		return (int)($this->id) > 0 ? $this->update($nullValues) : $this->add($autodate, $nullValues);
178
	}
179
180
	/**
181
	 * Add current object to database
182
	 *
183
	 * return boolean Insertion result
184
	 */
185
	public function add($autodate = true, $nullValues = false)
186
	{
187
	 	if (!Validate::isTableOrIdentifier($this->table))
188
			die(Tools::displayError('not table or identifier : ').$this->table);
0 ignored issues
show
Coding Style Compatibility introduced by
The method add() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
189
190
		/* Automatically fill dates */
191
		if ($autodate AND key_exists('date_add', $this))
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
192
			$this->date_add = date('Y-m-d H:i:s');
0 ignored issues
show
Bug introduced by
The property date_add does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
193
		if ($autodate AND key_exists('date_upd', $this))
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
194
			$this->date_upd = date('Y-m-d H:i:s');
0 ignored issues
show
Bug introduced by
The property date_upd does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
195
196
		/* Database insertion */
197
		if ($nullValues)
198
			$result = Db::getInstance()->autoExecuteWithNullValues(_DB_PREFIX_.$this->table, $this->getFields(), 'INSERT');
199
		else
200
			$result = Db::getInstance()->autoExecute(_DB_PREFIX_.$this->table, $this->getFields(), 'INSERT');
201
202
		if (!$result)
203
			return false;
204
		/* Get object id in database */
205
		$this->id = Db::getInstance()->Insert_ID();
206
		/* Database insertion for multilingual fields related to the object */
207
		if (method_exists($this, 'getTranslationsFieldsChild'))
208
		{
209
			$fields = $this->getTranslationsFieldsChild();
0 ignored issues
show
Bug introduced by
The method getTranslationsFieldsChild() does not exist on ObjectModel. Did you maybe mean getTranslationsFields()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
210
			if ($fields AND is_array($fields))
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
211
				foreach ($fields AS $field)
212
				{
213
					foreach (array_keys($field) AS $key)
214
					 	if (!Validate::isTableOrIdentifier($key))
215
			 				die(Tools::displayError('key is not table or identifier, ').Tools::safeOutput($key));
0 ignored issues
show
Coding Style Compatibility introduced by
The method add() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
216
					$field[$this->identifier] = (int)$this->id;
217
					$result &= Db::getInstance()->AutoExecute(_DB_PREFIX_.$this->table.'_lang', $field, 'INSERT');
218
				}
219
		}
220
		return $result;
221
	}
222
223
	/**
224
	 * Update current object to database
225
	 *
226
	 * return boolean Update result
227
	 */
228
	public function update($nullValues = false)
229
	{
230
	 	if (!Validate::isTableOrIdentifier($this->identifier) OR !Validate::isTableOrIdentifier($this->table))
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
231
			die(Tools::displayError());
0 ignored issues
show
Coding Style Compatibility introduced by
The method update() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
232
233
		$this->clearCache();
234
235
		/* Automatically fill dates */
236
		if (key_exists('date_upd', $this))
237
			$this->date_upd = date('Y-m-d H:i:s');
238
239
		/* Database update */
240
		if ($nullValues)
241
			$result = Db::getInstance()->autoExecuteWithNullValues(_DB_PREFIX_.$this->table, $this->getFields(), 'UPDATE', '`'.pSQL($this->identifier).'` = '.(int)($this->id));
242
		else
243
			$result = Db::getInstance()->autoExecute(_DB_PREFIX_.$this->table, $this->getFields(), 'UPDATE', '`'.pSQL($this->identifier).'` = '.(int)($this->id));
244
		if (!$result)
245
			return false;
246
247
		// Database update for multilingual fields related to the object 
248
		if (method_exists($this, 'getTranslationsFieldsChild'))
249
		{
250
			$fields = $this->getTranslationsFieldsChild();
0 ignored issues
show
Bug introduced by
The method getTranslationsFieldsChild() does not exist on ObjectModel. Did you maybe mean getTranslationsFields()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
251
			if (is_array($fields))
252
				foreach ($fields as $field)
253
				{
254
					foreach (array_keys($field) as $key)
255
						if (!Validate::isTableOrIdentifier($key))
256
							die(Tools::displayError());
0 ignored issues
show
Coding Style Compatibility introduced by
The method update() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
257
258
					// used to insert missing lang entries
259
					$where_lang = '`'.pSQL($this->identifier).'` = '.(int)($this->id).' AND `id_lang` = '.(int)($field['id_lang']);
260
261
					$lang_found = Db::getInstance()->getValue('SELECT COUNT(*) FROM `'.pSQL(_DB_PREFIX_.$this->table).'_lang` WHERE '. $where_lang);
262
263
					if (!$lang_found)
264
						$result &= Db::getInstance()->AutoExecute(_DB_PREFIX_.$this->table.'_lang', $field, 'INSERT');
265
					else
266
						$result &= Db::getInstance()->AutoExecute(_DB_PREFIX_.$this->table.'_lang', $field, 'UPDATE', $where_lang);
267
				}
268
		}
269
		return $result;
270
	}
271
272
	/**
273
	 * Delete current object from database
274
	 *
275
	 * return boolean Deletion result
276
	 */
277
	public function delete()
278
	{
279
	 	if (!Validate::isTableOrIdentifier($this->identifier) OR !Validate::isTableOrIdentifier($this->table))
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
280
	 		die(Tools::displayError());
0 ignored issues
show
Coding Style Compatibility introduced by
The method delete() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
281
282
		$this->clearCache();
283
284
		/* Database deletion */
285
		$result = Db::getInstance()->Execute('DELETE FROM `'.pSQL(_DB_PREFIX_.$this->table).'` WHERE `'.pSQL($this->identifier).'` = '.(int)($this->id));
286
		if (!$result)
287
			return false;
288
289
		/* Database deletion for multilingual fields related to the object */
290
		if (method_exists($this, 'getTranslationsFieldsChild'))
291
			Db::getInstance()->Execute('DELETE FROM `'.pSQL(_DB_PREFIX_.$this->table).'_lang` WHERE `'.pSQL($this->identifier).'` = '.(int)($this->id));
292
		return $result;
293
	}
294
295
	/**
296
	 * Delete several objects from database
297
	 *
298
	 * return boolean Deletion result
299
	 */
300
	public function deleteSelection($selection)
301
	{
302
		if (!is_array($selection) OR !Validate::isTableOrIdentifier($this->identifier) OR !Validate::isTableOrIdentifier($this->table))
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
303
			die(Tools::displayError());
0 ignored issues
show
Coding Style Compatibility introduced by
The method deleteSelection() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
304
		$result = true;
305
		foreach ($selection AS $id)
306
		{
307
			$this->id = (int)($id);
308
			$result = $result AND $this->delete();
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
309
		}
310
		return $result;
311
	}
312
313
	/**
314
	 * Toggle object status in database
315
	 *
316
	 * return boolean Update result
317
	 */
318
	public function toggleStatus()
319
	{
320
	 	if (!Validate::isTableOrIdentifier($this->identifier) OR !Validate::isTableOrIdentifier($this->table))
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
321
	 		die(Tools::displayError());
0 ignored issues
show
Coding Style Compatibility introduced by
The method toggleStatus() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
322
323
	 	/* Object must have a variable called 'active' */
324
	 	elseif (!key_exists('active', $this))
325
	 		die(Tools::displayError());
0 ignored issues
show
Coding Style Compatibility introduced by
The method toggleStatus() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
326
327
	 	/* Update active status on object */
328
	 	$this->active = (int)(!$this->active);
0 ignored issues
show
Bug introduced by
The property active does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
329
330
		/* Change status to active/inactive */
331
		return Db::getInstance()->Execute('
332
		UPDATE `'.pSQL(_DB_PREFIX_.$this->table).'`
333
		SET `active` = !`active`
334
		WHERE `'.pSQL($this->identifier).'` = '.(int)($this->id));
335
	}
336
337
	/**
338
	 * Prepare multilingual fields for database insertion
339
	 *
340
	 * @param array $fieldsArray Multilingual fields to prepare
341
	 * return array Prepared fields for database insertion
342
	 */
343
	protected function getTranslationsFields($fieldsArray)
344
	{
345
		/* WARNING : Product do not use this function, so do not forget to report any modification if necessary */
346
	 	if (!Validate::isTableOrIdentifier($this->identifier))
347
	 		die(Tools::displayError('identifier is not table or identifier : ').Tools::safeOutput($this->identifier));
0 ignored issues
show
Coding Style Compatibility introduced by
The method getTranslationsFields() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
348
349
		$fields = array();
350
351
		if ($this->id_lang == NULL)
352
			foreach (Language::getLanguages(false) as $language)
353
				$this->makeTranslationFields($fields, $fieldsArray, $language['id_lang']);
354
		else
355
			$this->makeTranslationFields($fields, $fieldsArray, $this->id_lang);
356
357
		return $fields;
358
	}
359
360
	protected function makeTranslationFields(&$fields, &$fieldsArray, $id_language)
361
	{
362
		$fields[$id_language]['id_lang'] = $id_language;
363
		$fields[$id_language][$this->identifier] = (int)($this->id);
364
		foreach ($fieldsArray as $field)
365
		{
366
			/* Check fields validity */
367
			if (!Validate::isTableOrIdentifier($field))
368
				die(Tools::displayError());
0 ignored issues
show
Coding Style Compatibility introduced by
The method makeTranslationFields() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
369
370
			/* Copy the field, or the default language field if it's both required and empty */
371
			if ((!$this->id_lang AND isset($this->{$field}[$id_language]) AND !empty($this->{$field}[$id_language])) 
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
372
			OR ($this->id_lang AND isset($this->$field) AND !empty($this->$field)))
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
373
				$fields[$id_language][$field] = $this->id_lang ? pSQL($this->$field) : pSQL($this->{$field}[$id_language]);
374
			elseif (in_array($field, $this->fieldsRequiredLang))
375
				$fields[$id_language][$field] = $this->id_lang ? pSQL($this->$field) : pSQL($this->{$field}[Configuration::get('PS_LANG_DEFAULT')]);
376
			else
377
				$fields[$id_language][$field] = '';
378
		}
379
	}
380
381
	/**
382
	 * Check for fields validity before database interaction
383
	 */
384
	public function validateFields($die = true, $errorReturn = false)
385
	{
386
		$fieldsRequired = array_merge($this->fieldsRequired, (isset(self::$fieldsRequiredDatabase[get_class($this)]) ? self::$fieldsRequiredDatabase[get_class($this)] : array()));
387
		foreach ($fieldsRequired as $field)
388
			if (Tools::isEmpty($this->{$field}) AND (!is_numeric($this->{$field})))
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
389
			{
390
				if ($die) die (Tools::displayError().' ('.Tools::safeOutput(get_class($this)).' -> '.Tools::safeOutput($field).' is empty)');
0 ignored issues
show
Coding Style Compatibility introduced by
The method validateFields() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
391
				return $errorReturn ? get_class($this).' -> '.$field.' is empty' : false;
392
			}
393
		foreach ($this->fieldsSize as $field => $size)
394
			if (isset($this->{$field}) AND Tools::strlen($this->{$field}) > $size)
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
395
			{
396
				if ($die) die (Tools::displayError().' ('.Tools::safeOutput(get_class($this)).' -> '.Tools::safeOutput($field).' Length '.Tools::safeOutput($size).')');
0 ignored issues
show
Coding Style Compatibility introduced by
The method validateFields() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
397
				return $errorReturn ? get_class($this).' -> '.$field.' Length '.$size : false;
398
			}
399
		$validate = new Validate();
400
		foreach ($this->fieldsValidate as $field => $method)
401
			if (!method_exists($validate, $method))
402
				die (Tools::displayError('Validation function not found.').' '.$method);
0 ignored issues
show
Coding Style Compatibility introduced by
The method validateFields() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
403
			elseif (!empty($this->{$field}) AND !call_user_func(array('Validate', $method), $this->{$field}))
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
404
			{
405
				if ($die) die (Tools::displayError().' ('.Tools::safeOutput(get_class($this)).' -> '.Tools::safeOutput($field).' = '.Tools::safeOutput($this->{$field}).')');
0 ignored issues
show
Coding Style Compatibility introduced by
The method validateFields() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
406
				return $errorReturn ? get_class($this).' -> '.$field.' = '.$this->{$field} : false;
407
			}
408
		return true;
409
	}
410
411
	/**
412
	 * Check for multilingual fields validity before database interaction
413
	 */
414
	public function validateFieldsLang($die = true, $errorReturn = false)
415
	{
416
		$defaultLanguage = (int)(Configuration::get('PS_LANG_DEFAULT'));
417
		foreach ($this->fieldsRequiredLang as $fieldArray)
418
		{
419
			if (!is_array($this->{$fieldArray}))
420
				continue ;
421
			if (!$this->{$fieldArray} OR !sizeof($this->{$fieldArray}) OR ($this->{$fieldArray}[$defaultLanguage] !== '0' AND empty($this->{$fieldArray}[$defaultLanguage])))
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
422
			{
423
				if ($die) die (Tools::displayError().' ('.Tools::safeOutput(get_class($this)).'->'.Tools::safeOutput($fieldArray).' '.Tools::displayError('is empty for default language.').')');
0 ignored issues
show
Coding Style Compatibility introduced by
The method validateFieldsLang() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
424
				return $errorReturn ? get_class($this).'->'.$fieldArray.' '.Tools::displayError('is empty for default language.') : false;
425
			}
426
		}
427
		foreach ($this->fieldsSizeLang as $fieldArray => $size)
428
		{
429
			if (!is_array($this->{$fieldArray}))
430
				continue ;
431
			foreach ($this->{$fieldArray} as $k => $value)
432
				if (Tools::strlen($value) > $size)
433
				{
434
					if ($die) die (Tools::displayError().' ('.Tools::safeOutput(get_class($this)).'->'.Tools::safeOutput($fieldArray).' '.Tools::displayError('Length').' '.Tools::safeOutput($size).' '.Tools::displayError('for language').')');
0 ignored issues
show
Coding Style Compatibility introduced by
The method validateFieldsLang() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
435
					return $errorReturn ? get_class($this).'->'.$fieldArray.' '.Tools::displayError('Length').' '.$size.' '.Tools::displayError('for language') : false;
436
				}
437
		}
438
		$validate = new Validate();
439
		foreach ($this->fieldsValidateLang as $fieldArray => $method)
440
		{
441
			if (!is_array($this->{$fieldArray}))
442
				continue ;
443
			foreach ($this->{$fieldArray} as $k => $value)
444
				if (!method_exists($validate, $method))
445
					die (Tools::displayError('Validation function not found.').' '.Tools::safeOutput($method));
0 ignored issues
show
Coding Style Compatibility introduced by
The method validateFieldsLang() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
446
				elseif (!empty($value) AND !call_user_func(array('Validate', $method), $value))
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
447
				{
448
					if ($die) die (Tools::displayError('The following field is invalid according to the validate method ').'<b>'.Tools::safeOutput($method).'</b>:<br/> ('.Tools::safeOutput(get_class($this)).'->'.Tools::safeOutput($fieldArray).' = '.Tools::safeOutput($value).' '.Tools::displayError('for language').' '.Tools::safeOutput($k).')');
0 ignored issues
show
Coding Style Compatibility introduced by
The method validateFieldsLang() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
449
					return $errorReturn ? Tools::displayError('The following field is invalid according to the validate method ').'<b>'.$method.'</b>:<br/> ('. get_class($this).'->'.$fieldArray.' = '.$value.' '.Tools::displayError('for language').' '.$k : false;
450
				}
451
		}
452
		return true;
453
	}
454
455
	public static function displayFieldName($field, $className = __CLASS__, $htmlentities = true)
456
	{
457
		global $_FIELDS, $cookie;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
458
		$iso = strtolower(Language::getIsoById($cookie->id_lang ? (int)$cookie->id_lang : Configuration::get('PS_LANG_DEFAULT')));
459
		@include(_PS_TRANSLATIONS_DIR_.$iso.'/fields.php');
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
460
461
		$key = $className.'_'.md5($field);
462
		return ((is_array($_FIELDS) AND array_key_exists($key, $_FIELDS)) ? ($htmlentities ? htmlentities($_FIELDS[$key], ENT_QUOTES, 'utf-8') : $_FIELDS[$key]) : $field);
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
463
	}
464
465
	/**
466
	* TODO: refactor rename all calls to this to validateController
467
	*/
468
	public function validateControler($htmlentities = true)
469
	{
470
		return $this->validateController($htmlentities);
471
	}
472
473
	public function validateController($htmlentities = true)
474
	{
475
		$errors = array();
476
477
		/* Checking for required fields */
478
		$fieldsRequired = array_merge($this->fieldsRequired, (isset(self::$fieldsRequiredDatabase[get_class($this)]) ? self::$fieldsRequiredDatabase[get_class($this)] : array()));
479
		foreach ($fieldsRequired AS $field)
480
		if (($value = Tools::getValue($field, $this->{$field})) == false AND (string)$value != '0')
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
481
			if (!$this->id OR $field != 'passwd')
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
482
				$errors[] = '<b>'.self::displayFieldName($field, get_class($this), $htmlentities).'</b> '.Tools::displayError('is required.');
483
484
485
		/* Checking for maximum fields sizes */
486
		foreach ($this->fieldsSize AS $field => $maxLength)
487
			if (($value = Tools::getValue($field, $this->{$field})) AND Tools::strlen($value) > $maxLength)
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
488
				$errors[] = '<b>'.self::displayFieldName($field, get_class($this), $htmlentities).'</b> '.Tools::displayError('is too long.').' ('.Tools::displayError('Maximum length:').' '.$maxLength.')';
489
490
		/* Checking for fields validity */
491
		foreach ($this->fieldsValidate AS $field => $function)
492
		{
493
			// Hack for postcode required for country which does not have postcodes
494
			if ($value = Tools::getValue($field, $this->{$field}) OR ($field == 'postcode' AND $value == '0'))
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
495
			{
496
				if (!Validate::$function($value))
497
					$errors[] = '<b>'.self::displayFieldName($field, get_class($this), $htmlentities).'</b> '.Tools::displayError('is invalid.');
498
				else
499
				{
500
					if ($field == 'passwd')
501
					{
502
						if ($value = Tools::getValue($field))
503
							$this->{$field} = Tools::encrypt($value);
504
					}
505
					else
506
						$this->{$field} = $value;
507
				}
508
			}
509
		}
510
		return $errors;
511
	}
512
513
	public function getWebserviceParameters($wsParamsAttributeName = NULL)
514
	{
515
		$defaultResourceParameters = array(
516
			'objectSqlId' => $this->identifier,
517
			'retrieveData' => array(
518
				'className' => get_class($this),
519
				'retrieveMethod' => 'getWebserviceObjectList',
520
				'params' => array(),
521
				'table' => $this->table,
522
			),
523
			'fields' => array(
524
				'id' => array('sqlId' => $this->identifier, 'i18n' => false),
525
			),
526
		);
527
528
		if (is_null($wsParamsAttributeName))
529
			$wsParamsAttributeName = 'webserviceParameters';
530
531
532
		if (!isset($this->{$wsParamsAttributeName}['objectNodeName']))
533
			$defaultResourceParameters['objectNodeName'] = $this->table;
534
		if (!isset($this->{$wsParamsAttributeName}['objectsNodeName']))
535
			$defaultResourceParameters['objectsNodeName'] = $this->table.'s';
536
537
		if (isset($this->{$wsParamsAttributeName}['associations']))
538
			foreach ($this->{$wsParamsAttributeName}['associations'] as $assocName => &$association)
539
			{
540
				if (!array_key_exists('setter', $association) || (isset($association['setter']) && !$association['setter']))
541
					$association['setter'] = Tools::toCamelCase('set_ws_'.$assocName);
542
				if (!array_key_exists('getter', $association))
543
					$association['getter'] = Tools::toCamelCase('get_ws_'.$assocName);
544
			}
545
546
547
		if (isset($this->{$wsParamsAttributeName}['retrieveData']) && isset($this->{$wsParamsAttributeName}['retrieveData']['retrieveMethod']))
548
			unset($defaultResourceParameters['retrieveData']['retrieveMethod']);
549
550
		$resourceParameters = array_merge_recursive($defaultResourceParameters, $this->{$wsParamsAttributeName});
551
		if (isset($this->fieldsSize))
552
			foreach ($this->fieldsSize as $fieldName => $maxSize)
553
			{
554
				if (!isset($resourceParameters['fields'][$fieldName]))
555
					$resourceParameters['fields'][$fieldName] = array('required' => false);
556
				$resourceParameters['fields'][$fieldName] = array_merge(
557
					$resourceParameters['fields'][$fieldName],
558
					$resourceParameters['fields'][$fieldName] = array('sqlId' => $fieldName, 'maxSize' => $maxSize, 'i18n' => false)
559
				);
560
			}
561
		if (isset($this->fieldsValidate))
562
			foreach ($this->fieldsValidate as $fieldName => $validateMethod)
563
			{
564
				if (!isset($resourceParameters['fields'][$fieldName]))
565
					$resourceParameters['fields'][$fieldName] = array('required' => false);
566
				$resourceParameters['fields'][$fieldName] = array_merge(
567
					$resourceParameters['fields'][$fieldName],
568
					$resourceParameters['fields'][$fieldName] = array(
569
						'sqlId' => $fieldName,
570
						'validateMethod' => (
571
								array_key_exists('validateMethod', $resourceParameters['fields'][$fieldName]) ?
572
								array_merge($resourceParameters['fields'][$fieldName]['validateMethod'], array($validateMethod)) :
573
								array($validateMethod)
574
							),
575
						'i18n' => false
576
					)
577
				);
578
			}
579
		if (isset($this->fieldsRequired))
580
		{
581
			$fieldsRequired = array_merge($this->fieldsRequired, (isset(self::$fieldsRequiredDatabase[get_class($this)]) ? self::$fieldsRequiredDatabase[get_class($this)] : array()));
582
			foreach ($fieldsRequired as $fieldRequired)
583
			{
584
				if (!isset($resourceParameters['fields'][$fieldRequired]))
585
					$resourceParameters['fields'][$fieldRequired] = array();
586
				$resourceParameters['fields'][$fieldRequired] = array_merge(
587
					$resourceParameters['fields'][$fieldRequired],
588
					$resourceParameters['fields'][$fieldRequired] = array('sqlId' => $fieldRequired, 'required' => true, 'i18n' => false)
589
				);
590
			}
591
		}
592
		if (isset($this->fieldsSizeLang))
593
			foreach ($this->fieldsSizeLang as $fieldName => $maxSize)
594
			{
595
				if (!isset($resourceParameters['fields'][$fieldName]))
596
					$resourceParameters['fields'][$fieldName] = array('required' => false);
597
				$resourceParameters['fields'][$fieldName] = array_merge(
598
					$resourceParameters['fields'][$fieldName],
599
					$resourceParameters['fields'][$fieldName] = array('sqlId' => $fieldName, 'maxSize' => $maxSize, 'i18n' => true)
600
				);
601
			}
602
		if (isset($this->fieldsValidateLang))
603
			foreach ($this->fieldsValidateLang as $fieldName => $validateMethod)
604
			{
605
				if (!isset($resourceParameters['fields'][$fieldName]))
606
					$resourceParameters['fields'][$fieldName] = array('required' => false);
607
				$resourceParameters['fields'][$fieldName] = array_merge(
608
					$resourceParameters['fields'][$fieldName],
609
					$resourceParameters['fields'][$fieldName] = array(
610
						'sqlId' => $fieldName,
611
						'validateMethod' => (
612
								array_key_exists('validateMethod', $resourceParameters['fields'][$fieldName]) ?
613
								array_merge($resourceParameters['fields'][$fieldName]['validateMethod'], array($validateMethod)) :
614
								array($validateMethod)
615
							),
616
						'i18n' => true
617
					)
618
				);
619
			}
620
621
		if (isset($this->fieldsRequiredLang))
622
			foreach ($this->fieldsRequiredLang as $field)
623
			{
624
				if (!isset($resourceParameters['fields'][$field]))
625
					$resourceParameters['fields'][$field] = array();
626
				$resourceParameters['fields'][$field] = array_merge(
627
					$resourceParameters['fields'][$field],
628
					$resourceParameters['fields'][$field] = array('sqlId' => $field, 'required' => true, 'i18n' => true)
629
				);
630
			}
631
632
		if (isset($this->date_add))
633
			$resourceParameters['fields']['date_add']['setter'] = false;
634
		if (isset($this->date_upd))
635
			$resourceParameters['fields']['date_upd']['setter'] = false;
636
637
		foreach ($resourceParameters['fields'] as $key => &$resourceParametersField)
0 ignored issues
show
Bug introduced by
The expression $resourceParameters['fields'] of type string|array<string,stri...\"i18n\":\"false\"}>"}> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
638
			if (!isset($resourceParametersField['sqlId']))
639
				$resourceParametersField['sqlId'] = $key;
640
		return $resourceParameters;
641
	}
642
643
	public function getWebserviceObjectList($sql_join, $sql_filter, $sql_sort, $sql_limit)
644
	{
645
		$query = '
646
		SELECT DISTINCT main.`'.$this->identifier.'` FROM `'._DB_PREFIX_.$this->table.'` AS main
647
		'.$sql_join.'
648
		WHERE 1 '.$sql_filter.'
649
		'.($sql_sort != '' ? $sql_sort : '').'
650
		'.($sql_limit != '' ? $sql_limit : '').'
651
		';
652
		return Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($query);
653
	}
654
655
	public function getFieldsRequiredDatabase($all = false)
656
	{
657
		return Db::getInstance()->ExecuteS('
658
		SELECT id_required_field, object_name, field_name
659
		FROM '._DB_PREFIX_.'required_field
660
		'.(!$all ? 'WHERE object_name = \''.pSQL(get_class($this)).'\'' : ''));
661
	}
662
663
	public function addFieldsRequiredDatabase($fields)
664
	{
665
		if (!is_array($fields))
666
			return false;
667
668
		if (!Db::getInstance()->Execute('DELETE FROM '._DB_PREFIX_.'required_field WHERE object_name = \''.pSQL(get_class($this)).'\''))
669
			return false;
670
671
		foreach ($fields AS $field)
672
			if (!Db::getInstance()->AutoExecute(_DB_PREFIX_.'required_field', array('object_name' => pSQL(get_class($this)), 'field_name' => pSQL($field)), 'INSERT'))
673
				return false;
674
		return true;
675
	}
676
677
	public function clearCache($all = false)
678
	{
679
		if ($all AND isset(self::$_cache[$this->table]))
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
680
			unset(self::$_cache[$this->table]);
681
		elseif ($this->id AND isset(self::$_cache[$this->table][(int)$this->id]))
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
682
			unset(self::$_cache[$this->table][(int)$this->id]);
683
	}
684
	
685
	/**
686
	 * Delete images associated with the object
687
	 *
688
	 * @return bool success
689
	 */
690
	public function deleteImage()
691
	{
692
		if (!$this->id)
693
			return false;
694
695
		/* Deleting object images and thumbnails (cache) */
696
		if ($this->image_dir)
697
		{
698
			if (file_exists($this->image_dir.$this->id.'.'.$this->image_format) 
699
				&& !unlink($this->image_dir.$this->id.'.'.$this->image_format))
700
				return false;
701
		}
702
		if (file_exists(_PS_TMP_IMG_DIR_.$this->table.'_'.$this->id.'.'.$this->image_format) 
703
			&& !unlink(_PS_TMP_IMG_DIR_.$this->table.'_'.$this->id.'.'.$this->image_format))
704
			return false;
705
		if (file_exists(_PS_TMP_IMG_DIR_.$this->table.'_mini_'.$this->id.'.'.$this->image_format) 
706
			&& !unlink(_PS_TMP_IMG_DIR_.$this->table.'_mini_'.$this->id.'.'.$this->image_format))
707
			return false;
708
			
709
		$types = ImageType::getImagesTypes();
710
		foreach ($types AS $image_type)
711
			if (file_exists($this->image_dir.$this->id.'-'.stripslashes($image_type['name']).'.'.$this->image_format) 
712
			&& !unlink($this->image_dir.$this->id.'-'.stripslashes($image_type['name']).'.'.$this->image_format))
713
				return false;
714
		return true;
715
	}
716
717
	/**
718
	* Specify if an ObjectModel is already in database
719
	*
720
	* @param $id_entity entity id
721
	* @return boolean
722
	*/
723
	public static function existsInDatabase($id_entity, $table)
724
	{
725
		
726
		if ($table == 'orders')
727
			$field = 'order';
728
		else
729
			$field = $table;
730
			
731
		$row = Db::getInstance()->getRow('
732
		SELECT `id_'.$field.'` as id
733
		FROM `'._DB_PREFIX_.$table.'` e
734
		WHERE e.`id_'.$field.'` = '.(int)($id_entity));
735
736
		return isset($row['id']);
737
	}
738
}
739
740