Material   A
last analyzed

Complexity

Total Complexity 25

Size/Duplication

Total Lines 259
Duplicated Lines 4.25 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 25
lcom 1
cbo 5
dl 11
loc 259
ccs 0
cts 109
cp 0
rs 10
c 1
b 0
f 1

9 Methods

Rating   Name   Duplication   Size   Complexity  
A remove() 0 13 2
A removeRelatedEntity() 0 9 2
A selectText() 0 14 3
B gallery() 0 29 5
A copyRelatedEntity() 0 13 3
A copy() 0 11 1
B setFieldByID() 0 28 4
A byUrl() 11 11 2
A addTableRow() 0 53 3

How to fix   Duplicated Code   

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:

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 samson\activerecord\dbQuery;
9
use samson\activerecord\structurematerial;
10
use samsoncms\api\field\Row;
11
use \samsonframework\orm\QueryInterface;
12
13
/**
14
 * SamsonCMS Material database record object.
15
 * This class extends default ActiveRecord material table record functionality.
16
 * @package samson\cms
17
 * @author Vitaly Egorov <[email protected]>
18
 */
19
class Material extends \samson\activerecord\Material
20
{
21
    /** Store entity name */
22
    const ENTITY = __CLASS__;
23
24
    /** Entity field names constants for using in code */
25
    const F_PRIMARY = 'MaterialID';
26
    const F_IDENTIFIER = 'Url';
27
    const F_DELETION = 'Active';
28
    const F_PUBLISHED = 'Published';
29
    const F_PARENT = 'parent_id';
30
    const F_PRIORITY = 'priority';
31
    const F_CREATED = 'Created';
32
    const F_MODIFIED = 'Modyfied';
33
34
    /**
35
     * Get material entity by URL(s).
36
     *
37
     * @param QueryInterface $query Object for performing database queries
38
     * @param array|string $url Material URL or collection of material URLs
39
     * @param self|array|null $return Variable where request result would be returned
40
     * @return bool|self True if material entities has been found
41
     */
42 View Code Duplication
    public static function byUrl(QueryInterface $query, $url, & $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...
43
    {
44
        // Get entities by filtered identifiers
45
        $return = $query->entity(get_called_class())
46
            ->where('Url', $url)
47
            ->where('Active', 1)
48
            ->first();
49
50
        // If only one argument is passed - return null, otherwise bool
51
        return func_num_args() > 2 ? $return !== null : $return;
52
    }
53
54
    /**
55
     * Set additional material field value by field identifier
56
     * @param string $fieldID Field identifier
57
     * @param string $value Value to be stored
58
     * @param string $locale Locale identifier
59
     */
60
    public function setFieldByID($fieldID, $value, $locale = null)
61
    {
62
        /** @var Field $fieldRecord Try to find this additional field */
63
        $fieldRecord = null;
64
        if (Field::byID($this->query, $fieldID, $fieldRecord)) {
0 ignored issues
show
Deprecated Code introduced by
The method samsonframework\orm\Record::byID() has been deprecated with message: Record should not be queryable, query class ancestor must be used

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...
65
            /** @var MaterialField $materialFieldRecord Try to find additional field value */
66
            $materialFieldRecord = null;
67
            if (!MaterialField::byFieldIDAndMaterialID($this->query, $this->id, $fieldRecord->id, $materialFieldRecord, $locale)) {
68
                // Create new additional field value record if it does not exists
69
                $materialFieldRecord = new MaterialField();
70
                $materialFieldRecord->FieldID = $fieldRecord->id;
71
                $materialFieldRecord->MaterialID = $this->id;
72
                $materialFieldRecord->Active = 1;
0 ignored issues
show
Documentation Bug introduced by
The property $Active was declared of type boolean, but 1 is of type integer. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
73
74
                // Add locale if field needs it
75
                if ($fieldRecord->localized()) {
76
                    $materialFieldRecord->locale = $locale;
77
                }
78
            } else { // Get first record(actually it should be only one)
79
                $materialFieldRecord = array_shift($materialFieldRecord);
80
            }
81
82
            // At this point we already have database record instance
83
            $valueFieldName = $fieldRecord->valueFieldName();
84
            $materialFieldRecord->$valueFieldName = $value;
85
            $materialFieldRecord->save();
86
        }
87
    }
88
89
    /**
90
     * Add new row to table of entity
91
     * @param $row
92
     */
93
    public function addTableRow(Row $row)
94
    {
95
        // Get user
96
        $user = m('socialemail')->user();
0 ignored issues
show
Deprecated Code introduced by
The function m() has been deprecated with message: Use $this->system->module() in module context

This function has been deprecated. The supplier of the file has supplied an explanatory message.

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

Loading history...
97
98
        $tableMaterial = new Material();
99
        $tableMaterial->parent_id = $this->id;
100
        $tableMaterial->type = 3;
0 ignored issues
show
Bug introduced by
The property type 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...
101
        $tableMaterial->Name = $this->Url . '-' . md5(date('Y-m-d-h-i-s'));
102
        $tableMaterial->Url = $this->Url . '-' . md5(date('Y-m-d-h-i-s'));
103
        $tableMaterial->Published = 1;
0 ignored issues
show
Documentation Bug introduced by
The property $Published was declared of type boolean, but 1 is of type integer. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
104
        $tableMaterial->Active = 1;
0 ignored issues
show
Documentation Bug introduced by
The property $Active was declared of type boolean, but 1 is of type integer. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
105
        $tableMaterial->priority = 0;
106
        $tableMaterial->UserID = $user->id;
107
        $tableMaterial->Created = date('Y-m-d H:m:s');
108
        $tableMaterial->Modyfied = date('Y-m-d H:m:s');
109
        $tableMaterial->save();
110
111
        // TODO: Ugly way to retrieve static var
112
        $class = new \ReflectionClass(preg_replace('/Row$/', '', get_class($row)));
113
        $structureId = $class->getConstant('IDENTIFIER');
114
115
        $structureMaterial = new structurematerial();
116
        $structureMaterial->Active = 1;
117
        $structureMaterial->MaterialID = $tableMaterial->id;
118
        $structureMaterial->StructureID = $structureId;
119
        $structureMaterial->save();
120
121
        // TODO: Ugly way to retrieve static var
122
        $class = new \ReflectionClass(get_class($row));
123
        $fieldIDs = $class->getStaticPropertyValue('fieldIDs');
124
125
        // Iterate and set all fields of row
126
        foreach ($row as $id => $value) {
0 ignored issues
show
Bug introduced by
The expression $row of type object<samsoncms\api\field\Row> is not traversable.
Loading history...
127
128
            /**
129
             * Go next if it primary key because its public
130
             * TODO Fix it
131
             */
132
            if ($id === 'primary') {
133
                continue;
134
            }
135
136
            // Get field id
137
            $fieldId = $fieldIDs[$id];
138
139
            // Add additional field to created material
140
            $tableMaterial->setFieldByID($fieldId, $value);
141
        }
142
143
        // Save material
144
        $tableMaterial->save();
145
    }
146
147
    /**
148
     * Get select additional field text value.
149
     *
150
     * @param string $fieldID Field identifier
151
     * @return string Select field text
152
     */
153
    public function selectText($fieldID)
154
    {
155
        // TODO: this is absurd as we do not have any additional values here
156
        /** @var Field $field */
157
        $field = null;
158
159
        // If this entity has this field set
160
        if (Field::byID($this->query, $fieldID, $field) && isset($this[$field->Name]{0})) {
0 ignored issues
show
Deprecated Code introduced by
The method samsonframework\orm\Record::byID() has been deprecated with message: Record should not be queryable, query class ancestor must be used

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...
161
            return $field->options($this[$field->Name]);
162
        }
163
164
        // Value not set
165
        return '';
166
    }
167
168
    /**
169
     * Get collection of images for material by gallery additional field selector. If none is passed
170
     * all images from gallery table would be returned for this material entity.
171
     *
172
     * @param string|null $fieldSelector Additional field selector value
173
     * @param string $selector Additional field field name to search for
174
     * @return \samsonframework\orm\RecordInterface[] Collection of images in this gallery additional field for material
175
     */
176
    public function &gallery($fieldSelector = null, $selector = 'FieldID')
177
    {
178
        /** @var \samsonframework\orm\RecordInterface[] $images Get material images for this gallery */
179
        $images = array();
180
181
        $this->query->entity(CMS::MATERIAL_FIELD_RELATION_ENTITY);
182
183
        /* @var Field Get field object if we need to search it by other fields */
184
        $field = null;
185
        if ($selector != 'FieldID' && Field::oneByColumn($this->query, $selector, $fieldSelector)) {
0 ignored issues
show
Deprecated Code introduced by
The method samsonframework\orm\Record::oneByColumn() has been deprecated with message: Record should not be queryable, query class ancestor must be used

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...
186
            $fieldSelector = $field->id;
187
        }
188
189
        // Add field filter if present
190
        if (isset($fieldSelector)) {
191
            $this->query->where("FieldID", $fieldSelector);
192
        }
193
194
        /** @var \samson\activerecord\materialfield $dbMaterialField Find material field gallery record */
195
        $dbMaterialField = null;
196
        if ($this->query->where('MaterialID', $this->id)->first($dbMaterialField)) {
197
            // Get material images for this materialfield
198
            $images = $this->query->entity(CMS::MATERIAL_IMAGES_RELATION_ENTITY)
199
                ->where('materialFieldId', $dbMaterialField->id)
0 ignored issues
show
Bug introduced by
Accessing id on the interface samsonframework\orm\RecordInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
200
                ->exec();
201
        }
202
203
        return $images;
204
    }
205
206
    /**
207
     * Copy this material related entities.
208
     *
209
     * @param string $entity Entity identifier
210
     * @param string $newIdentifier Copied material idetifier
211
     * @param array $excludedIDs Collection of related entity identifier to exclude from copying
212
     */
213
    protected function copyRelatedEntity($entity, $newIdentifier, $excludedIDs = array())
214
    {
215
        /** @var self $copiedEntity Copy additional fields */
216
        foreach ($this->query->entity($entity)->where(self::F_PRIMARY, $this->MaterialID)->exec() as $copiedEntity) {
0 ignored issues
show
Bug introduced by
The expression $this->query->entity($en...is->MaterialID)->exec() of type boolean|array<integer,ob...k\orm\RecordInterface>> 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...
217
            // Check if field is NOT excluded from copying
218
            if (!in_array($copiedEntity->id, $excludedIDs)) {
219
                /** @var MaterialField $copy Copy instance */
220
                $copy = &$copiedEntity->copy();
221
                $copy->MaterialID = $newIdentifier;
0 ignored issues
show
Documentation Bug introduced by
The property $MaterialID was declared of type integer, but $newIdentifier is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
222
                $copy->save();
223
            }
224
        }
225
    }
226
227
    /**
228
     * Create copy of current object.
229
     *
230
     * @param mixed $clone Material for cloning
231
     * @param array $excludedFields Additional fields identifiers not copied
232
     * @returns self New copied instance
233
     */
234
    public function &copy(&$clone = null, $excludedFields = array())
235
    {
236
        /** @var Material $clone Create new instance by copying */
237
        $clone = parent::copy($clone);
238
239
        $this->copyRelatedEntity(CMS::MATERIAL_NAVIGATION_RELATION_ENTITY, $clone->id);
240
        $this->copyRelatedEntity(CMS::MATERIAL_FIELD_RELATION_ENTITY, $clone->id, $excludedFields);
241
        $this->copyRelatedEntity(CMS::MATERIAL_IMAGES_RELATION_ENTITY, $clone->id);
242
243
        return $clone;
244
    }
245
246
    /**
247
     * Remove current object.
248
     */
249
    public function remove()
250
    {
251
        $this->Active = 0;
0 ignored issues
show
Documentation Bug introduced by
The property $Active was declared of type boolean, but 0 is of type integer. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
252
253
        $this->removeRelatedEntity(CMS::MATERIAL_NAVIGATION_RELATION_ENTITY);
254
        $this->removeRelatedEntity(CMS::MATERIAL_FIELD_RELATION_ENTITY);
255
        $this->removeRelatedEntity(CMS::MATERIAL_IMAGES_RELATION_ENTITY);
256
        foreach ($this->query->entity(self::ENTITY)->where(self::F_PARENT, $this->MaterialID)->exec() as $removedChild) {
0 ignored issues
show
Bug introduced by
The expression $this->query->entity(sel...is->MaterialID)->exec() of type boolean|array<integer,ob...k\orm\RecordInterface>> 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...
257
            /** @var MaterialField $copy Copy instance */
258
            $removedChild->remove();
259
        }
260
        $this->save();
261
    }
262
263
    /**
264
     * Remove this material related entities.
265
     *
266
     * @param string $entity Entity identifier
267
     */
268
    protected function removeRelatedEntity($entity)
269
    {
270
        /** @var self $copiedEntity Remove additional fields */
271
        foreach ($this->query->entity($entity)->where(self::F_PRIMARY, $this->MaterialID)->exec() as $removedEntity) {
0 ignored issues
show
Bug introduced by
The expression $this->query->entity($en...is->MaterialID)->exec() of type boolean|array<integer,ob...k\orm\RecordInterface>> 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...
272
            /** @var MaterialField $copy Copy instance */
273
            $removedEntity->Active = 0;
274
            $removedEntity->save();
275
        }
276
    }
277
}
278