Passed
Pull Request — master (#19)
by
unknown
08:00
created

Material::addTableRow()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 34
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 34
ccs 0
cts 10
cp 0
rs 8.8571
cc 2
eloc 19
nc 2
nop 1
crap 6
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
    /**
72
     * Set additional material field value by field identifier
73
     * @param string $fieldID Field identifier
74
     * @param string $value Value to be stored
75
     * @param string $locale Locale identifier
76
     */
77
    public function setFieldByID($fieldID, $value, $locale = null)
78
    {
79
        /** @var Field $fieldRecord Try to find this additional field */
80
        $fieldRecord = null;
81
        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...
82
            /** @var MaterialField $materialFieldRecord Try to find additional field value */
83
            $materialFieldRecord = null;
84
            if (!MaterialField::byFieldIDAndMaterialID($this->query, $this->id, $fieldRecord->id, $materialFieldRecord, $locale)) {
85
                // Create new additional field value record if it does not exists
86
                $materialFieldRecord = new MaterialField();
87
                $materialFieldRecord->FieldID = $fieldRecord->id;
88
                $materialFieldRecord->MaterialID = $this->id;
89
                $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...
90
91
                // Add locale if field needs it
92
                if ($fieldRecord->localized()) {
93
                    $materialFieldRecord->locale = $locale;
94
                }
95
            } else { // Get first record(actually it should be only one)
96
                $materialFieldRecord = array_shift($materialFieldRecord);
97
            }
98
99
            // At this point we already have database record instance
100
            $valueFieldName = $fieldRecord->valueFieldName();
101
            $materialFieldRecord->$valueFieldName = $value;
102
            $materialFieldRecord->save();
103
        }
104
    }
105
106
    /**
107
     * Add new row to table of entity
108
     * @param $row
109
     */
110
    public function addTableRow(Row $row)
111
    {
112
        // Get user
113
        /** @var \samson\social\Core $socialModule Social module object */
114
        $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...
115
        /** @var \samson\activerecord\user $user User object */
116
        $user = $socialModule->user();
117
118
        $tableMaterial = new Material();
119
        $tableMaterial->parent_id = $this->id;
120
        $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...
121
        $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...
122
        $tableMaterial->Url = $this->Url . '-' . md5(date('Y-m-d-h-i-s'));
123
        $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...
124
        $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...
125
        $tableMaterial->priority = 0;
126
        $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...
127
        $tableMaterial->Created = date('Y-m-d H:m:s');
0 ignored issues
show
Bug introduced by
The property Created 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->Modyfied = date('Y-m-d H:m:s');
0 ignored issues
show
Bug introduced by
The property Modyfied 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...
129
        $tableMaterial->save();
130
131
        // Iterate and set all fields of row
132
        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...
133
134
            // Get field id
135
            $fieldId = $row::$fieldIDs[$id];
136
137
            // Add additional field to created material
138
            $tableMaterial->setFieldByID($fieldId, $value);
139
        }
140
141
        // Save material
142
        $tableMaterial->save();
143
    }
144
145
    /**
146
     * Get select additional field text value.
147
     *
148
     * @param string $fieldID Field identifier
149
     * @return string Select field text
150
     */
151
    public function selectText($fieldID)
152
    {
153
        // TODO: this is absurd as we do not have any additional values here
154
        /** @var Field $field */
155
        $field = null;
156
157
        // If this entity has this field set
158
        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...
159
            return $field->options($this[$field->Name]);
160
        }
161
162
        // Value not set
163
        return '';
164
    }
165
166
    /**
167
     * Get collection of images for material by gallery additional field selector. If none is passed
168
     * all images from gallery table would be returned for this material entity.
169
     *
170
     * @param string|null $fieldSelector Additional field selector value
171
     * @param string $selector Additional field field name to search for
172
     * @return \samsonframework\orm\RecordInterface[] Collection of images in this gallery additional field for material
173
     */
174
    public function &gallery($fieldSelector = null, $selector = 'FieldID')
175
    {
176
        /** @var \samsonframework\orm\RecordInterface[] $images Get material images for this gallery */
177
        $images = array();
178
179
        $this->query->entity(CMS::MATERIAL_FIELD_RELATION_ENTITY);
180
181
        /* @var Field Get field object if we need to search it by other fields */
182
        $field = null;
183
        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...
184
            $fieldSelector = $field->id;
185
        }
186
187
        // Add field filter if present
188
        if (isset($fieldSelector)) {
189
            $this->query->where("FieldID", $fieldSelector);
190
        }
191
192
        /** @var \samson\activerecord\materialfield $dbMaterialField Find material field gallery record */
193
        $dbMaterialField = null;
194
        if ($this->query->where('MaterialID', $this->id)->first($dbMaterialField)) {
195
            // Get material images for this materialfield
196
            $images = $this->query->entity(CMS::MATERIAL_IMAGES_RELATION_ENTITY)
197
                ->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...
198
                ->exec();
199
        }
200
201
        return $images;
202
    }
203
204
    /**
205
     * Copy this material related entities.
206
     *
207
     * @param string $entity Entity identifier
208
     * @param string $newIdentifier Copied material idetifier
209
     * @param array $excludedIDs Collection of related entity identifier to exclude from copying
210
     */
211
    protected function copyRelatedEntity($entity, $newIdentifier, $excludedIDs = array())
212
    {
213
        /** @var self $copiedEntity Copy additional fields */
214
        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...
215
            // Check if field is NOT excluded from copying
216
            if (!in_array($copiedEntity->id, $excludedIDs)) {
217
                /** @var MaterialField $copy Copy instance */
218
                $copy = &$copiedEntity->copy();
219
                $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...
220
                $copy->save();
221
            }
222
        }
223
    }
224
225
    /**
226
     * Create copy of current object.
227
     *
228
     * @param mixed $clone Material for cloning
229
     * @param array $excludedFields Additional fields identifiers not copied
230
     * @returns self New copied instance
231
     */
232
    public function &copy(&$clone = null, $excludedFields = array())
233
    {
234
        /** @var Material $clone Create new instance by copying */
235
        $clone = parent::copy($clone);
236
237
        $this->copyRelatedEntity(CMS::MATERIAL_NAVIGATION_RELATION_ENTITY, $clone->id);
238
        $this->copyRelatedEntity(CMS::MATERIAL_FIELD_RELATION_ENTITY, $clone->id, $excludedFields);
239
        $this->copyRelatedEntity(CMS::MATERIAL_IMAGES_RELATION_ENTITY, $clone->id);
240
241
        return $clone;
242
    }
243
}
244