Completed
Push — master ( 1fd713...646730 )
by Vitaly
05:38
created

Material   A

Complexity

Total Complexity 17

Size/Duplication

Total Lines 194
Duplicated Lines 5.67 %

Coupling/Cohesion

Components 2
Dependencies 6

Importance

Changes 28
Bugs 7 Features 14
Metric Value
wmc 17
c 28
b 7
f 14
lcom 2
cbo 6
dl 11
loc 194
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A byUrl() 11 11 2
B setFieldByID() 0 27 3
A selectText() 0 15 3
B gallery() 0 32 5
A copyRelatedEntity() 0 15 3
A copy() 0 14 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 samsonframework\orm\Query;
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
31
    /** @var integer Primary field */
32
    public $MaterialID;
33
34
    /** @var string Unique identifier */
35
    public $Url;
36
37
    /** @var bool Internal existence flag */
38
    public $Active;
39
40
    /** @var bool Published flag */
41
    public $Published;
42
43
    /** @var integer Parent material identifier */
44
    public $parent_id;
45
46
    /** @var integer Priority inside material relation */
47
    public $priority;
48
49
    /**
50
     * Get material entity by URL(s).
51
     *
52
     * @param QueryInterface $query Object for performing database queries
53
     * @param array|string $url Material URL or collection of material URLs
54
     * @param self|array|null $return Variable where request result would be returned
55
     * @return bool|self True if material entities has been found
56
     */
57 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...
58
    {
59
        // Get entities by filtered identifiers
60
        $return = $query->entity(get_called_class())
61
            ->where('Url', $url)
0 ignored issues
show
Bug introduced by
It seems like $url defined by parameter $url on line 57 can also be of type array; however, samsonframework\orm\QueryInterface::where() does only seem to accept string|null, 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...
62
            ->where('Active', 1)
63
            ->first();
64
65
        // If only one argument is passed - return null, otherwise bool
66
        return func_num_args() > 2 ? $return !== null : $return;
67
    }
68
69
    /**
70
     * Set additional material field value by field identifier
71
     * @param string $fieldID Field identifier
72
     * @param string $value Value to be stored
73
     * @param string $locale Locale identifier
74
     */
75
    public function setFieldByID($fieldID, $value, $locale = DEFAULT_LOCALE)
76
    {
77
        /** @var QueryInterface $query This should be removed to use $this->database*/
78
        $query = new dbQuery();
79
80
        /** @var Field $fieldRecord Try to find this additional field */
81
        $fieldRecord = null;
82
        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...
83
            /** @var MaterialField[] $materialFieldRecord Try to find additional field value */
84
            $materialFieldRecord = null;
85
            if (!MaterialField::byFieldIDAndMaterialID($query, $this->id, $fieldRecord->id, $materialFieldRecord)) {
86
                // Create new additional field value record if it does not exists
87
                $materialFieldRecord = new MaterialField();
88
                $materialFieldRecord->FieldID = $fieldRecord->id;
89
                $materialFieldRecord->MaterialID = $this->id;
90
                $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...
91
                $materialFieldRecord->locale = $locale;
92
            } else { // Get first record(actually it should be only one)
93
                $materialFieldRecord = array_shift($materialFieldRecord);
94
            }
95
96
            // At this point we already have database record instance
97
            $valueFieldName = $fieldRecord->valueFieldName();
98
            $materialFieldRecord->$valueFieldName = $value;
99
            $materialFieldRecord->save();
100
        }
101
    }
102
103
    /**
104
     * Get select additional field text value.
105
     *
106
     * @param string $fieldID Field identifier
107
     * @return string Select field text
108
     */
109
    public function selectText($fieldID)
110
    {
111
        // TODO: this is absurd as we do not have any additional values here
112
        /** @var Field $field */
113
        $field = null;
114
        if (Field::byID(new Query(Field::ENTITY, $this->database), $fieldID, $fieldID)) {
0 ignored issues
show
Documentation introduced by
$fieldID is of type string, 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...
115
            // If this entity has this field set
116
            if (isset($this[$field->Name]{0})) {
117
                return $field->options($this[$field->Name]);
118
            }
119
        }
120
121
        // Value not set
122
        return '';
123
    }
124
125
    /**
126
     * Get collection of images for material by gallery additional field selector. If none is passed
127
     * all images from gallery table would be returned for this material entity.
128
     *
129
     * @param string|null $fieldSelector Additional field selector value
130
     * @param string $selector Additional field field name to search for
131
     * @return \samsonframework\orm\RecordInterface[] Collection of images in this gallery additional field for material
132
     */
133
    public function &gallery($fieldSelector = null, $selector = 'FieldID')
134
    {
135
        /** @var \samsonframework\orm\RecordInterface[] $images Get material images for this gallery */
136
        $images = array();
137
138
        // Create query
139
        $query = new dbQuery();
140
141
        $query->entity(CMS::MATERIAL_FIELD_RELATION_ENTITY);
142
143
        /* @var Field Get field object if we need to search it by other fields */
144
        $field = null;
145
        if ($selector != 'FieldID' && Field::oneByColumn($query, $selector, $fieldSelector)) {
146
            $fieldSelector = $field->id;
147
        }
148
149
        // Add field filter if present
150
        if (isset($fieldSelector)) {
151
            $query->where("FieldID", $fieldSelector);
152
        }
153
154
        /** @var \samson\activerecord\materialfield $dbMaterialField Find material field gallery record */
155
        $dbMaterialField = null;
156
        if ($query->where('MaterialID', $this->id)->first($dbMaterialField)) {
157
            // Get material images for this materialfield
158
            $images = $query->entity(CMS::MATERIAL_IMAGES_RELATION_ENTITY)
159
                ->where('materialFieldId', $dbMaterialField->id)
160
                ->exec();
161
        }
162
163
        return $images;
164
    }
165
166
    /**
167
     * Copy this material related entities.
168
     *
169
     * @param QueryInterface $query Database query instance
170
     * @param string $entity Entity identifier
171
     * @param string $newIdentifier Copied material idetifier
172
     * @param array $excludedIDs Collection of related entity identifier to exclude from copying
173
     */
174
    protected function copyRelatedEntity(QueryInterface $query, $entity, $newIdentifier, $excludedIDs = array())
175
    {
176
        // Copy additional fields
177
        foreach ($query->entity($entity)
0 ignored issues
show
Bug introduced by
The expression $query->entity($entity)-...is->MaterialID)->exec() of type boolean|object<samsonfra...rk\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...
178
                     ->where('MaterialID', $this->MaterialID)
179
                     ->exec() as $copiedEntity) {
180
            // Check if field is NOT excluded from copying
181
            if (!in_array($copiedEntity->id, $excludedIDs)) {
182
                /** @var MaterialField $copy Copy instance */
183
                $copy = $copiedEntity->copy();
184
                $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...
185
                $copy->save();
186
            }
187
        }
188
    }
189
190
    /**
191
     * Create copy of current object.
192
     *
193
     * @param mixed $clone Material for cloning
194
     * @param array $excludedFields Additional fields identifiers not copied
195
     * @returns self New copied instance
196
     */
197
    public function &copy(&$clone = null, $excludedFields = array())
198
    {
199
        /** @var Material $clone Create new instance by copying */
200
        $clone = parent::copy($clone);
201
202
        // Create query
203
        $query = new dbQuery();
204
205
        $this->copyRelatedEntity($query, CMS::MATERIAL_NAVIGATION_RELATION_ENTITY, $clone->id);
206
        $this->copyRelatedEntity($query, CMS::MATERIAL_FIELD_RELATION_ENTITY, $clone->id, $excludedFields);
207
        $this->copyRelatedEntity($query, CMS::MATERIAL_IMAGES_RELATION_ENTITY, $clone->id);
208
209
        return $clone;
210
    }
211
}
212