Passed
Pull Request — master (#21)
by
unknown
03:31
created

Material   A

Complexity

Total Complexity 20

Size/Duplication

Total Lines 232
Duplicated Lines 4.74 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 0%

Importance

Changes 23
Bugs 7 Features 11
Metric Value
wmc 20
c 23
b 7
f 11
lcom 1
cbo 5
dl 11
loc 232
ccs 0
cts 83
cp 0
rs 10

7 Methods

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

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 samsoncms\api\field\Row;
10
use \samsonframework\orm\QueryInterface;
11
12
/**
13
 * SamsonCMS Material database record object.
14
 * This class extends default ActiveRecord material table record functionality.
15
 * @package samson\cms
16
 * @author Vitaly Egorov <[email protected]>
17
 */
18
class Material extends \samson\activerecord\Material
19
{
20
    /** Store entity name */
21
    const ENTITY = __CLASS__;
22
23
    /** Entity field names constants for using in code */
24
    const F_PRIMARY = 'MaterialID';
25
    const F_IDENTIFIER = 'Url';
26
    const F_DELETION = 'Active';
27
    const F_PUBLISHED = 'Published';
28
    const F_PARENT = 'parent_id';
29
    const F_PRIORITY = 'priority';
30
    const F_CREATED = 'Created';
31
    const F_MODIFIED = 'Modyfied';
32
33
    /**
34
     * Get material entity by URL(s).
35
     *
36
     * @param QueryInterface $query Object for performing database queries
37
     * @param array|string $url Material URL or collection of material URLs
38
     * @param self|array|null $return Variable where request result would be returned
39
     * @return bool|self True if material entities has been found
40
     */
41 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...
42
    {
43
        // Get entities by filtered identifiers
44
        $return = $query->entity(get_called_class())
45
            ->where('Url', $url)
46
            ->where('Active', 1)
47
            ->first();
48
49
        // If only one argument is passed - return null, otherwise bool
50
        return func_num_args() > 2 ? $return !== null : $return;
51
    }
52
53
    /** @var integer Primary field */
54
    public $MaterialID;
55
56
    /** @var string Unique identifier */
57
    public $Url;
58
59
    /** @var bool Internal existence flag */
60
    public $Active;
61
62
    /** @var bool Published flag */
63
    public $Published;
64
65
    /** @var integer Parent material identifier */
66
    public $parent_id;
67
68
    /** @var integer Priority inside material relation */
69
    public $priority;
70
71
    /** @var mixed Last material creation timestamp */
72
    public $Created;
73
74
    /** @var mixed Last material modification timestamp */
75
    public $Modyfied;
76
77
    /**
78
     * Set additional material field value by field identifier
79
     * @param string $fieldID Field identifier
80
     * @param string $value Value to be stored
81
     * @param string $locale Locale identifier
82
     */
83
    public function setFieldByID($fieldID, $value, $locale = null)
84
    {
85
        /** @var Field $fieldRecord Try to find this additional field */
86
        $fieldRecord = null;
87
        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...
88
            /** @var MaterialField $materialFieldRecord Try to find additional field value */
89
            $materialFieldRecord = null;
90
            if (!MaterialField::byFieldIDAndMaterialID($this->query, $this->id, $fieldRecord->id, $materialFieldRecord, $locale)) {
91
                // Create new additional field value record if it does not exists
92
                $materialFieldRecord = new MaterialField();
93
                $materialFieldRecord->FieldID = $fieldRecord->id;
94
                $materialFieldRecord->MaterialID = $this->id;
95
                $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...
96
97
                // Add locale if field needs it
98
                if ($fieldRecord->localized()) {
99
                    $materialFieldRecord->locale = $locale;
100
                }
101
            } else { // Get first record(actually it should be only one)
102
                $materialFieldRecord = array_shift($materialFieldRecord);
103
            }
104
105
            // At this point we already have database record instance
106
            $valueFieldName = $fieldRecord->valueFieldName();
107
            $materialFieldRecord->$valueFieldName = $value;
108
            $materialFieldRecord->save();
109
        }
110
    }
111
112
    /**
113
     * Add new row to table of entity
114
     * @param $row
115
     */
116
    public function addTableRow(Row $row)
117
    {
118
        // Get user
119
        /** @var \samson\social\Core $socialModule Social module object */
120
        $socialModule = m('social');
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...
121
        /** @var \samson\activerecord\user $user User object */
122
        $user = $socialModule->user();
123
124
        $tableMaterial = new Material();
125
        $tableMaterial->parent_id = $this->id;
126
        $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...
127
        $tableMaterial->Name = $this->Url . '-' . md5(date('Y-m-d-h-i-s'));
0 ignored issues
show
Bug introduced by
The property Name 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...
128
        $tableMaterial->Url = $this->Url . '-' . md5(date('Y-m-d-h-i-s'));
129
        $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...
130
        $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...
131
        $tableMaterial->priority = 0;
132
        $tableMaterial->UserID = $user->id;
0 ignored issues
show
Bug introduced by
The property UserID 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...
133
        $tableMaterial->Created = date('Y-m-d H:m:s');
134
        $tableMaterial->Modyfied = date('Y-m-d H:m:s');
135
        $tableMaterial->save();
136
137
        // Iterate and set all fields of row
138
        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...
139
140
            // Get field id
141
            $fieldId = $row::$fieldIDs[$id];
142
143
            // Add additional field to created material
144
            $tableMaterial->setFieldByID($fieldId, $value);
145
        }
146
147
        // Save material
148
        $tableMaterial->save();
149
    }
150
151
    /**
152
     * Get select additional field text value.
153
     *
154
     * @param string $fieldID Field identifier
155
     * @return string Select field text
156
     */
157
    public function selectText($fieldID)
158
    {
159
        // TODO: this is absurd as we do not have any additional values here
160
        /** @var Field $field */
161
        $field = null;
162
163
        // If this entity has this field set
164
        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...
165
            return $field->options($this[$field->Name]);
166
        }
167
168
        // Value not set
169
        return '';
170
    }
171
172
    /**
173
     * Get collection of images for material by gallery additional field selector. If none is passed
174
     * all images from gallery table would be returned for this material entity.
175
     *
176
     * @param string|null $fieldSelector Additional field selector value
177
     * @param string $selector Additional field field name to search for
178
     * @return \samsonframework\orm\RecordInterface[] Collection of images in this gallery additional field for material
179
     */
180
    public function &gallery($fieldSelector = null, $selector = 'FieldID')
181
    {
182
        /** @var \samsonframework\orm\RecordInterface[] $images Get material images for this gallery */
183
        $images = array();
184
185
        $this->query->entity(CMS::MATERIAL_FIELD_RELATION_ENTITY);
186
187
        /* @var Field Get field object if we need to search it by other fields */
188
        $field = null;
189
        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...
190
            $fieldSelector = $field->id;
191
        }
192
193
        // Add field filter if present
194
        if (isset($fieldSelector)) {
195
            $this->query->where("FieldID", $fieldSelector);
196
        }
197
198
        /** @var \samson\activerecord\materialfield $dbMaterialField Find material field gallery record */
199
        $dbMaterialField = null;
200
        if ($this->query->where('MaterialID', $this->id)->first($dbMaterialField)) {
201
            // Get material images for this materialfield
202
            $images = $this->query->entity(CMS::MATERIAL_IMAGES_RELATION_ENTITY)
203
                ->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...
204
                ->exec();
205
        }
206
207
        return $images;
208
    }
209
210
    /**
211
     * Copy this material related entities.
212
     *
213
     * @param string $entity Entity identifier
214
     * @param string $newIdentifier Copied material idetifier
215
     * @param array $excludedIDs Collection of related entity identifier to exclude from copying
216
     */
217
    protected function copyRelatedEntity($entity, $newIdentifier, $excludedIDs = array())
218
    {
219
        /** @var self $copiedEntity Copy additional fields */
220
        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...
221
            // Check if field is NOT excluded from copying
222
            if (!in_array($copiedEntity->id, $excludedIDs)) {
223
                /** @var MaterialField $copy Copy instance */
224
                $copy = &$copiedEntity->copy();
225
                $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...
226
                $copy->save();
227
            }
228
        }
229
    }
230
231
    /**
232
     * Create copy of current object.
233
     *
234
     * @param mixed $clone Material for cloning
235
     * @param array $excludedFields Additional fields identifiers not copied
236
     * @returns self New copied instance
237
     */
238
    public function &copy(&$clone = null, $excludedFields = array())
239
    {
240
        /** @var Material $clone Create new instance by copying */
241
        $clone = parent::copy($clone);
242
243
        $this->copyRelatedEntity(CMS::MATERIAL_NAVIGATION_RELATION_ENTITY, $clone->id);
244
        $this->copyRelatedEntity(CMS::MATERIAL_FIELD_RELATION_ENTITY, $clone->id, $excludedFields);
245
        $this->copyRelatedEntity(CMS::MATERIAL_IMAGES_RELATION_ENTITY, $clone->id);
246
247
        return $clone;
248
    }
249
}
250