Completed
Push — master ( d99e5c...f08d75 )
by Vitaly
07:24 queued 02:56
created

Material   C

Complexity

Total Complexity 55

Size/Duplication

Total Lines 448
Duplicated Lines 9.6 %

Coupling/Cohesion

Components 3
Dependencies 8

Importance

Changes 9
Bugs 2 Features 6
Metric Value
wmc 55
lcom 3
cbo 8
dl 43
loc 448
c 9
b 2
f 6
rs 6.8

11 Methods

Rating   Name   Duplication   Size   Complexity  
B idsByFieldValue() 0 36 5
A idsByNavigationID() 0 22 3
A byFieldValue() 6 14 3
A byNavigationID() 15 15 3
A byNavigationIdAndFieldValue() 6 21 4
A byUrl() 0 8 2
B setFieldByID() 0 37 5
A selectText() 0 19 4
B gallery() 0 31 5
C copy() 16 42 8
D getTable() 0 89 13

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like Material 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 Material, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * Created by Vitaly Iegorov <[email protected]>
4
 * on 07.08.14 at 17:11
5
 */
6
namespace samsoncms\api;
7
8
use \samsonframework\orm\Condition;
9
use \samsonframework\orm\QueryInterface;
10
11
/**
12
 * SamsonCMS Material database record object.
13
 * This class extends default ActiveRecord material table record functionality.
14
 * @package samson\cms
15
 * @author Vitaly Egorov <[email protected]>
16
 */
17
class Material extends \samson\activerecord\material
18
{
19
    /** Override table attributes for late static binding */
20
    public static $_attributes = array();
21
    public static $_sql_select = array();
22
    public static $_sql_from = array();
23
    public static $_own_group = array();
24
    public static $_map = array();
25
26
    /**
27
     * Get identifiers collection by field identifier and its value.
28
     * Method is optimized for performance.
29
     *
30
     * @param QueryInterface $query Database query instance
31
     * @param string $fieldID Additional field identifier
32
     * @param string $fieldValue Additional field value for searching
33
     * @param array|null $return Variable where request result would be returned
34
     * @param array $materialIDs Collection of material identifiers for filtering query
35
     * @return bool|array True if material entities has been found and $return is passed
36
     *                      or identifiers collection if only two parameters is passed.
37
     */
38
    public static function idsByFieldValue(
39
        QueryInterface $query,
40
        $fieldID,
41
        $fieldValue,
42
        &$return = array(),
43
        $materialIDs = null
44
    ) {
45
        /** @var array $fields Collection for storing fields data */
46
        static $fields;
47
48
        /** @var Field $fieldRecord Cache field object */
49
        $fieldRecord = isset($fields[$fieldID]) ? $fields[$fieldID] : Field::byID($query, $fieldID);
50
51
        // We need to have field record
52
        if (isset($fieldRecord)) {
53
            $materials = array();
54
55
            // Get material identifiers by field
56
            $query->entity('samson\activerecord\materialfield')
57
                ->where('MaterialID', $materials)
0 ignored issues
show
Documentation introduced by
$materials is of type array, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
58
                ->where('Active', 1)
59
                ->where('FieldID', $fieldID)
60
                ->where($fieldRecord->valueFieldName(), $fieldValue);
61
62
            // Add material identifier filter if passed
63
            if (isset($materialIDs)) {
64
                $query->where('MaterialID', $materialIDs);
0 ignored issues
show
Documentation introduced by
$materialIDs is of type array, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
65
            }
66
67
            // Perform database query and get only material identifiers collection
68
            $return = $query->fields($materials);
0 ignored issues
show
Documentation introduced by
$materials is of type array, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
69
        }
70
71
        // If only one argument is passed - return null, otherwise bool
72
        return func_num_args() > 3 ? $return == null : $return;
73
    }
74
75
    /**
76
     * Get current entity identifiers collection by navigation identifier.
77
     *
78
     * @param QueryInterface $query Database query
79
     * @param string $navigationID Navigation identifier
80
     * @param array $return Variable where request result would be returned
81
     * @param array $materialIDs Collection of material identifiers for filtering query
82
     * @return bool|array True if material entities has been found and $return is passed
83
     *                      or collection of identifiers if only two parameters is passed.
84
     */
85
    public static function idsByNavigationID(
86
        QueryInterface $query,
87
        $navigationID,
88
        &$return = array(),
89
        $materialIDs = null
90
    ) {
91
        // Prepare query
92
         $query->entity('\samson\activerecord\structurematerial')
93
            ->where('StructureID', $navigationID)
94
            ->where('Active', 1);
95
96
        // Add material identifier filter if passed
97
        if (isset($materialIDs)) {
98
            $query->where('MaterialID', $materialIDs);
0 ignored issues
show
Documentation introduced by
$materialIDs is of type array, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
99
        }
100
101
        // Perform database query and get only material identifiers collection
102
        $return = $query->fields('MaterialID');
103
104
        // If only one argument is passed - return null, otherwise bool
105
        return func_num_args() > 2 ? $return == null : $return;
106
    }
107
108
    /**
109
     * Get self[] by field identifier and its value.
110
     * Method is optimized for performance.
111
     *
112
     * @param QueryInterface $query Database query instance
113
     * @param string $fieldID Additional field identifier
114
     * @param string $fieldValue Additional field value for searching
115
     * @param self[]|array|null $return Variable where request result would be returned
116
     * @return bool|self[] True if material entities has been found and $return is passed
117
     *                      or self[] if only two parameters is passed.
118
     */
119
    public static function byFieldValue(QueryInterface $query, $fieldID, $fieldValue, &$return = array())
120
    {
121
        /** @var array $materialIds Collection of entity identifiers filtered by additional field */
122
        $materialIds = null;
123 View Code Duplication
        if (static::idsByFieldValue($query, $fieldID, $fieldValue, $materialIds)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
124
            // Get material instances
125
            $return = $query->entity(get_called_class())
126
                ->where('MaterialID', $materialIds)
0 ignored issues
show
Bug introduced by
It seems like $materialIds can also be of type array; however, samsonframework\orm\QueryInterface::where() does only seem to accept string|null, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
127
                ->exec();
128
        }
129
130
        // If only one argument is passed - return null, otherwise bool
131
        return func_num_args() > 3 ? $return == null : $return;
132
    }
133
134
    /**
135
     * Get current entity instances collection by navigation identifier.
136
     *
137
     * @param QueryInterface $query Database query
138
     * @param string $navigationID Navigation identifier
139
     * @param self[]|array|null $return Variable where request result would be returned
140
     * @return bool|self[] True if material entities has been found and $return is passed
141
     *                      or self[] if only two parameters is passed.
142
     */
143 View Code Duplication
    public static function byNavigationID(QueryInterface $query, $navigationID, &$return = array())
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
144
    {
145
        /** @var array $materialIds Collection of entity identifiers filtered by additional field */
146
        $materialIds = null;
147
        if (static::idsByNavigationID($query, $navigationID, $materialIds)) {
148
            $return = $query->entity(get_called_class())
149
                ->where('MaterialID', $materialIds)
0 ignored issues
show
Documentation introduced by
$materialIds is of type array, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
150
                ->where('Active', 1)
151
                ->where('Published', 1)
152
                ->exec();
153
        }
154
155
        // If only one argument is passed - return null, otherwise bool
156
        return func_num_args() > 2 ? $return == null : $return;
157
    }
158
159
    /**
160
     * Get current entity instances collection by navigation identifier.
161
     *
162
     * @param QueryInterface $query Database query
163
     * @param string $navigationID Navigation identifier
164
     * @param string $fieldID Additional field identifier
165
     * @param string $fieldValue Additional field value for searching
166
     * @param self[]|array|null $return Variable where request result would be returned
167
     * @return bool|Material[] True if material entities has been found and $return is passed
168
     *                      or self[] if only two parameters is passed.
169
     */
170
    public static function byNavigationIdAndFieldValue(
171
        QueryInterface $query,
172
        $navigationID,
173
        $fieldID,
174
        $fieldValue,
175
        &$return = array()
176
    ) {
177
        /** @var array $materialIds Collection of entity identifiers filtered by additional field */
178
        $materialIds = null;
179
        if (static::idsByNavigationID($query, $navigationID, $materialIds)) {
180 View Code Duplication
            if (static::idsByFieldValue($query, $fieldID, $fieldValue, $materialIds, $materialIds)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
181
                // Get entities by filtered identifiers
182
                $return = $query->entity(get_called_class())
183
                    ->where('MaterialID', $materialIds)
0 ignored issues
show
Bug introduced by
It seems like $materialIds can also be of type array; however, samsonframework\orm\QueryInterface::where() does only seem to accept string|null, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
184
                    ->exec();
185
            }
186
        }
187
188
        // If only one argument is passed - return null, otherwise bool
189
        return func_num_args() > 4 ? $return == null : $return;
190
    }
191
192
    /**
193
     * Get material entities collection by URL(s).
194
     * @param QueryInterface $query Object for performing database queries
195
     * @param array|string $url Material URL or collection of material URLs
196
     * @param self[]|array|null $return Variable where request result would be returned
197
     * @return bool|self[] True if material entities has been found
198
     */
199
    public static function byUrl(QueryInterface $query, $url, & $return = array())
200
    {
201
        // Get field record by identifier column
202
        $return = static::collectionByColumn($query, 'Url', $url);
0 ignored issues
show
Bug introduced by
It seems like $url defined by parameter $url on line 199 can also be of type array; however, samsonframework\orm\Record::collectionByColumn() does only seem to accept string, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
203
204
        // If only one argument is passed - return null, otherwise bool
205
        return func_num_args() > 1 ? $return == null : $return;
206
    }
207
208
    /**
209
     * Set additional material field value by field identifier
210
     * @param string $fieldID Field identifier
211
     * @param string $value Value to be stored
212
     * @param string $locale Locale identifier
213
     */
214
    public function setFieldByID($fieldID, $value, $locale = DEFAULT_LOCALE)
215
    {
216
        // TODO: This should be removed
217
        /** @var QueryInterface $query This should be removed to use $this->database*/
218
        $query = dbQuery();
0 ignored issues
show
Bug introduced by
The call to dbQuery() misses a required argument $class_name.

This check looks for function calls that miss required arguments.

Loading history...
219
220
        /** @var Field $fieldRecord Try to find this additional field */
221
        $fieldRecord = null;
222
        if (Field::byID($query, $fieldID, $fieldRecord)) {
0 ignored issues
show
Documentation introduced by
$fieldRecord is of type object<samsoncms\api\Field>, but the function expects a null|object<self>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
223
            /** @var MaterialField $materialFieldRecord Try to find additional field value */
224
            $materialFieldRecord = null;
225
            if (!MaterialField::byFieldIDAndMaterialID($query, $this->id, $fieldRecord->id, $materialFieldRecord)) {
0 ignored issues
show
Documentation introduced by
$materialFieldRecord is of type object<samsoncms\api\MaterialField>, but the function expects a null|object<self>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
226
                // Create new additional field value record if it does not exists
227
                $materialFieldRecord = new MaterialField();
228
                $materialFieldRecord->FieldID = $fieldRecord->id;
0 ignored issues
show
Bug introduced by
The property FieldID does not seem to exist in samsoncms\api\MaterialField.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
229
                $materialFieldRecord->MaterialID = $this->id;
0 ignored issues
show
Bug introduced by
The property MaterialID does not seem to exist in samsoncms\api\MaterialField.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
230
                $materialFieldRecord->Active = 1;
0 ignored issues
show
Bug introduced by
The property Active does not seem to exist in samsoncms\api\MaterialField.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
231
                $materialFieldRecord->locale = $locale;
0 ignored issues
show
Bug introduced by
The property locale does not seem to exist in samsoncms\api\MaterialField.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
232
            }
233
234
            // Define which field should be filled
235
            switch ($fieldRecord->Type) {
236
                case 1:
237
                    $valueFieldName = 'numeric_value';
238
                    break;
239
                case 2:
240
                    $valueFieldName = 'key_value';
241
                    break;
242
                default:
243
                    $valueFieldName = 'Value';
244
            }
245
246
            // At this point we already have database record instance
247
            $fieldRecord->$valueFieldName = $value;
248
            $fieldRecord->save();
249
        }
250
    }
251
252
    /**
253
     * Get select additional field text value
254
     * TODO: Find where do we use it
255
     * @return string Select field text
256
     */
257
    public function selectText($fieldID)
258
    {
259
        /** @var \samson\activerecord\field $field */
260
        $field = null;
261
        if (dbQuery('field')->id($fieldID)->first($field)) {
0 ignored issues
show
Deprecated Code introduced by
The method samson\activerecord\dbQuery::id() has been deprecated with message: Use direct query with where('PRIMARY_FIELD',...)

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
262
            // If this entity has this field set
263
            if (isset($this[$field->Name]{0})) {
264
                $types = array();
265
                foreach (explode(',', $field->Value) as $typeValue) {
266
                    $typeValue = explode(':', $typeValue);
267
                    $types[$typeValue[0]] = $typeValue[1];
268
                }
269
                return $types[$this[$field->Name]];
270
            }
271
        }
272
273
        // Value not set
274
        return '';
275
    }
276
277
    /**
278
     * Get collection of images for material by gallery additional field selector. If none is passed
279
     * all images from gallery table would be returned for this material entity.
280
     *
281
     * @param string|null $fieldSelector Additional field selector value
282
     * @param string $selector Additional field field name to search for
283
     * @return \samson\activerecord\gallery[] Collection of images in this gallery additional field for material
284
     */
285
    public function &gallery($fieldSelector = null, $selector = 'FieldID')
286
    {
287
        /** @var \samson\activerecord\gallery[] $images Get material images for this gallery */
288
        $images = array();
289
290
        /* @var \samson\activerecord\field Get field object if we need to search it by other fields */
291
        $field = null;
0 ignored issues
show
Unused Code introduced by
$field is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
292
        if ($selector != 'FieldID') {
293
            $field = dbQuery('field')->cond($selector, $fieldSelector)->first();
0 ignored issues
show
Deprecated Code introduced by
The method samson\activerecord\dbQuery::cond() has been deprecated with message: @see self::where()

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
294
            $fieldSelector = $field->id;
295
        }
296
297
        // Create query
298
        $query = dbQuery('materialfield');
299
300
        // Add field filter if present
301
        if (isset($fieldSelector)) {
302
            $query->cond("FieldID", $fieldSelector);
0 ignored issues
show
Deprecated Code introduced by
The method samson\activerecord\dbQuery::cond() has been deprecated with message: @see self::where()

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
303
        }
304
305
        /** @var \samson\activerecord\materialfield $dbMaterialField Find material field gallery record */
306
        $dbMaterialField = null;
307
        if ($query->cond('MaterialID', $this->id)->first($dbMaterialField)) {
0 ignored issues
show
Deprecated Code introduced by
The method samson\activerecord\dbQuery::cond() has been deprecated with message: @see self::where()

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
308
            // Get material images for this materialfield
309
            if (dbQuery('gallery')->cond('materialFieldId', $dbMaterialField->id)->exec($images)) {
0 ignored issues
show
Deprecated Code introduced by
The method samson\activerecord\dbQuery::cond() has been deprecated with message: @see self::where()

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
310
311
            }
312
        }
313
314
        return $images;
315
    }
316
317
    /**
318
     * Create copy of current object
319
     * @param mixed $clone Material for cloning
320
     * @param array $excludedFields excluded from materialfield fields identifiers
321
     * @returns void
322
     */
323
    public function &copy(& $clone = null, $excludedFields = array())
324
    {
325
        // Create new instance by copying
326
        $clone = parent::copy($clone);
327
328
        /** @var \samson\activerecord\structurematerial[] $objects Create structure material relations */
329
        $objects = array();
330 View Code Duplication
        if (dbQuery('structurematerial')->cond('MaterialID', $this->MaterialID)->exec($objects)) {
0 ignored issues
show
Bug introduced by
The property MaterialID 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...
Deprecated Code introduced by
The method samson\activerecord\dbQuery::cond() has been deprecated with message: @see self::where()

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
331
            foreach ($objects as $cmsNavigation) {
332
                /** @var \samson\activerecord\Record $copy */
333
                $copy = $cmsNavigation->copy();
334
                $copy->MaterialID = $clone->id;
335
                $copy->save();
336
            }
337
        }
338
        /** @var \samson\activerecord\materialfield[] $objects Create material field relations */
339
        $objects = array();
340
        if (dbQuery('materialfield')->cond('MaterialID', $this->MaterialID)->exec($objects)) {
0 ignored issues
show
Deprecated Code introduced by
The method samson\activerecord\dbQuery::cond() has been deprecated with message: @see self::where()

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
341
            foreach ($objects as $pMaterialField) {
342
                // Check if field is NOT excluded from copying
343
                if (!in_array($pMaterialField->FieldID, $excludedFields)) {
344
                    /** @var \samson\activerecord\dbRecord $copy Copy instance */
345
                    $copy = $pMaterialField->copy();
346
                    $copy->MaterialID = $clone->id;
0 ignored issues
show
Bug introduced by
The property MaterialID does not seem to exist in samson\activerecord\dbRecord.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
347
                    $copy->save();
348
                }
349
            }
350
        }
351
352
        /** @var \samson\activerecord\gallery[] $objects Create gallery field relations */
353
        $objects = array();
354 View Code Duplication
        if (dbQuery('gallery')->cond('MaterialID', $this->MaterialID)->exec($objects)) {
0 ignored issues
show
Deprecated Code introduced by
The method samson\activerecord\dbQuery::cond() has been deprecated with message: @see self::where()

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
355
            foreach ($objects as $cmsGallery) {
356
                /** @var \samson\activerecord\Record $copy */
357
                $copy = $cmsGallery->copy();
358
                $copy->MaterialID = $clone->id;
359
                $copy->save();
360
            }
361
        }
362
363
        return $clone;
364
    }
365
366
    /**
367
     * Function to retrieve this material table by specified field
368
     * @param string $tableSelector Selector to identify table structure
369
     * @param string $selector Database field by which search is performed
370
     * @param array $tableColumns Columns names list
371
     * @param string $externalHandler External handler to perform some extra code
372
     * @param array $params External handler params
373
     * @return array Collection of collections of table cells, represented as materialfield objects
374
     */
375
    public function getTable($tableSelector, $selector = 'StructureID', &$tableColumns = null, $externalHandler = null, $params = array())
376
    {
377
        /** @var array $resultTable Collection of collections of field cells */
378
        $resultTable = array();
379
        /** @var array $dbTableFieldsIds Array of table structure column identifiers */
380
        $dbTableFieldsIds = array();
381
382
        // Get structure object if we need to search it by other fields
383
        if ($selector != 'StructureID') {
384
            $structure = dbQuery('structure')->cond($selector, $tableSelector)->first();
0 ignored issues
show
Deprecated Code introduced by
The method samson\activerecord\dbQuery::cond() has been deprecated with message: @see self::where()

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
385
            $tableSelector = $structure->id;
386
        }
387
388
        /** If this table has columns */
389
        if (dbQuery('structurefield')
0 ignored issues
show
Deprecated Code introduced by
The method samson\activerecord\dbQuery::cond() has been deprecated with message: @see self::where()

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
390
            ->cond("StructureID", $tableSelector)
391
            ->fields('FieldID', $dbTableFieldsIds)
0 ignored issues
show
Documentation introduced by
$dbTableFieldsIds is of type array, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
392
        ) {
393
            // Get localized and not localized fields
394
            $localizedFields = array();
395
            $unlocalizedFields = array();
396
            /** @var \samson\cms\CMSField $dbTableField Table column */
397
            foreach (dbQuery('field')->order_by('priority')->cond('FieldID', $dbTableFieldsIds)->exec() as $field) {
0 ignored issues
show
Deprecated Code introduced by
The method samson\activerecord\dbQuery::cond() has been deprecated with message: @see self::where()

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
398
                /** Add table columns names */
399
                $tableColumns[] = $field->Name;
400
                if ($field->local == 1) {
401
                    $localizedFields[] = $field->id;
402
                } else {
403
                    $unlocalizedFields[] = $field->id;
404
                }
405
            }
406
407
            // Query to get table rows(table materials)
408
            $tableQuery = dbQuery('material')
0 ignored issues
show
Deprecated Code introduced by
The method samson\activerecord\dbQuery::cond() has been deprecated with message: @see self::where()

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
409
                ->cond('parent_id', $this->MaterialID)
410
                ->cond('Active', '1')
411
                ->join('structurematerial')
412
                ->cond('structurematerial_StructureID', $tableSelector)
413
                ->order_by('priority');
414
415
            // Call user function if exists
416
            if (is_callable($externalHandler)) {
417
                // Give it query as parameter
418
                call_user_func_array($externalHandler, array_merge(array(&$tableQuery), $params));
419
            }
420
421
            // Get table row materials
422
            $tableMaterialIds = array();
423
            if ($tableQuery->fields('MaterialID', $tableMaterialIds)) {
424
                // Create field condition
425
                $localizationFieldCond = new Condition('or');
426
427
                // Create localized condition
428
                if (sizeof($localizedFields)) {
429
                    $localizedFieldCond = new Condition('and');
430
                    $localizedFieldCond->add('materialfield_FieldID', $localizedFields)
431
                        ->add('materialfield_locale', locale());
432
                    // Add this condition to condition group
433
                    $localizationFieldCond->add($localizedFieldCond);
0 ignored issues
show
Bug introduced by
The call to add() misses a required argument $value.

This check looks for function calls that miss required arguments.

Loading history...
Documentation introduced by
$localizedFieldCond is of type object<samsonframework\orm\Condition>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
434
                }
435
436
                // Create not localized condition
437
                if (sizeof($unlocalizedFields)) {
438
                    $localizationFieldCond->add('materialfield_FieldID', $unlocalizedFields);
439
                }
440
441
                // Create db query
442
                $materialFieldQuery = dbQuery('materialfield')
0 ignored issues
show
Deprecated Code introduced by
The method samson\activerecord\dbQuery::cond() has been deprecated with message: @see self::where()

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
443
                    ->cond('MaterialID', $tableMaterialIds)
0 ignored issues
show
Documentation introduced by
$tableMaterialIds is of type array, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
444
                    ->cond($localizationFieldCond);
0 ignored issues
show
Documentation introduced by
$localizationFieldCond is of type object<samsonframework\orm\Condition>, but the function expects a string|object<samson\act...cord\ArgumentInterface>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
445
446
                // Flip field identifiers as keys
447
                $tableColumnIds = array_flip($dbTableFieldsIds);
448
                $resultTable = array_flip($tableMaterialIds);
449
450
                /** @var \samson\activerecord\material $dbTableRow Material object (table row) */
451
                foreach ($materialFieldQuery->exec() as $mf) {
452
                    if (!is_array($resultTable[$mf['MaterialID']])) {
453
                        $resultTable[$mf['MaterialID']] = array();
454
                    }
455
456
                    $resultTable[$mf['MaterialID']][$tableColumnIds[$mf->FieldID]] =
457
                        !empty($mf->Value) ? $mf->Value : (!empty($mf->numeric_value) ? $mf->numeric_value : $mf->key_value);
458
                }
459
            }
460
        }
461
462
        return array_values($resultTable);
463
    }
464
}
465