Completed
Pull Request — master (#57)
by Olexandr
02:41
created

Table   A

Complexity

Total Complexity 17

Size/Duplication

Total Lines 177
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Importance

Changes 4
Bugs 1 Features 2
Metric Value
wmc 17
c 4
b 1
f 2
lcom 1
cbo 6
dl 0
loc 177
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A columns() 0 4 1
A values() 0 4 2
A toArray() 0 4 1
A rowIDs() 0 11 1
B fieldsCondition() 0 33 5
B find() 0 47 6
A __construct() 0 9 1
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: VITALYIEGOROV
5
 * Date: 09.12.15
6
 * Time: 09:57
7
 */
8
namespace samsoncms\api\field;
9
10
use samsoncms\api\CMS;
11
use samsoncms\api\Material;
12
use samsoncms\api\MaterialField;
13
use samsoncms\api\query\FieldNavigation;
14
use samsoncms\api\query\MaterialNavigation;
15
use samsonframework\orm\Condition;
16
use samsonframework\orm\ConditionInterface;
17
use samsonframework\orm\QueryInterface;
18
use samsoncms\api\Field;
19
20
/**
21
 * Material additional fields table.
22
 * @package samsoncms\api
23
 */
24
class Table
25
{
26
    /** @var array Collection of real row field names  */
27
    protected static $fieldsRealNames = array();
28
29
    /** @var integer Navigation identifier for table structure */
30
    protected $navigationID;
31
32
    /** @var integer Table parent material identifier */
33
    protected $materialID;
34
35
    /** @var Field[] Collection field instances that correspond table columns */
36
    protected $fields;
37
38
    /** @var QueryInterface Database query interface */
39
    protected $query;
40
41
    /** @var string Locale identifier */
42
    protected $locale;
43
44
    /** @var Row[] Fields table rows collection */
45
    protected $collection = array();
46
47
    /** @var string Row class name */
48
    protected $rowInstance = '\samsoncms\api\field\Row';
49
50
    /** @return array Get field table column names collection */
51
    public function columns()
52
    {
53
        return array_column($this->fields, Field::F_IDENTIFIER);
54
    }
55
56
    /**
57
     * Get collection of table column values as array.
58
     *
59
     * @param string $fieldID Additional field identifier
60
     *
61
     * @return array Collection of table column values as array
62
     */
63
    public function values($fieldID)
64
    {
65
        return (null !== $this->fields[$fieldID]) ? array_column($this->collection, $fieldID) : array();
66
    }
67
68
    /**
69
     * Get field table as multidimensional array.
70
     *
71
     * @return Row[] Field table represented as array
72
     */
73
    public function toArray()
74
    {
75
        return $this->collection;
76
    }
77
78
    /** @return array Collection of table rows(materials) identifiers */
79
    protected function rowIDs()
80
    {
81
        // Get collection of nested materials
82
        return $this->query
83
            ->entity(Material::class)
84
            ->where(Material::F_DELETION, 1)
85
            ->where(Material::F_PRIMARY, (new MaterialNavigation())->idsByRelationID($this->navigationID))
86
            ->where(Material::F_PARENT, $this->materialID)
87
            ->orderBy(Material::F_PRIORITY)
88
            ->fields(Material::F_PRIMARY);
89
    }
90
91
    /**
92
     * Build correct localized field request for retrieving additional fields records.
93
     *
94
     * @param Field[] $fields Collection of additional fields
95
     *
96
     * @return Condition Built condition for query
97
     */
98
    protected function fieldsCondition($fields)
99
    {
100
        // Group fields by localization
101
        $localizedColumns = array();
102
        $notLocalizedColumns = array();
103
        /** @var Field $field Iterate table columns(fields) */
104
        foreach ($fields as $field) {
105
            if ($field->localized()) {
106
                $localizedColumns[] = $field->id;
107
            } else {
108
                $notLocalizedColumns[] = $field->id;
109
            }
110
        }
111
112
        // Create field condition
113
        $fieldsCondition = new Condition(ConditionInterface::DISJUNCTION);
114
        // Create localized condition
115
        if (count($localizedColumns)) {
116
            $localizedCondition = new Condition(ConditionInterface::CONJUNCTION);
117
            $localizedCondition->add(Field::F_PRIMARY, $localizedColumns)
118
                ->add(MaterialField::F_LOCALE, $this->locale);
119
120
            // Add this condition to condition group
121
            $fieldsCondition->addCondition($localizedCondition);
122
        }
123
124
        // Create not localized condition
125
        if (count($notLocalizedColumns)) {
126
            $fieldsCondition->add(Field::F_PRIMARY, $notLocalizedColumns);
127
        }
128
129
        return $fieldsCondition;
130
    }
131
132
    /**
133
     * Fill table with data from database.
134
     */
135
    protected function find()
136
    {
137
        // Get table Fields instances
138
        $this->fields = (new FieldNavigation())->byRelationID($this->navigationID);
0 ignored issues
show
Documentation Bug introduced by
It seems like (new \samsoncms\api\quer...ID($this->navigationID) of type array<integer,*> is incompatible with the declared type array<integer,object<samsoncms\api\Field>> of property $fields.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
139
140
        $collection = array();
141
        if (count($rowIDs = $this->rowIDs())) {
142
            /** @var MaterialField $fieldValue Get additional field value instances */
143
            foreach ($this->query->entity(CMS::MATERIAL_FIELD_RELATION_ENTITY)
0 ignored issues
show
Bug introduced by
The expression $this->query->entity(\sa...$this->fields))->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...
144
                         // Get only needed rows(materials)
145
                         ->where(Material::F_PRIMARY, $rowIDs)
146
                         ->where(Material::F_DELETION, 1)
147
                         // Get correct localizes field condition for columns
148
                         ->whereCondition($this->fieldsCondition($this->fields))
149
                         ->exec() as $fieldValue) {
150
                /** @var Field $field Try to find Field instance by identifier */
151
                $field = &$this->fields[$fieldValue[Field::F_PRIMARY]];
152
                if (null !== $field) {
153
                    /**
154
                     * As we generate camelCase names for fields we need to store
155
                     * original names to get their values and correctly set row
156
                     * fields.
157
                     */
158
                    $fieldName = null !== static::$fieldsRealNames[$field->Name]
159
                        ? static::$fieldsRealNames[$field->Name] : $field->Name;
160
                    /**
161
                     * Store table row(material) as it primary, store columns(Fields)
162
                     * by field primary. Use correct column for value.
163
                     */
164
                    $collection[$fieldValue[Material::F_PRIMARY]][$fieldName]
165
                        = $fieldValue[$field->valueFieldName()];
166
                }
167
            }
168
169
            /** @var Material[] $materials */
170
            $materials = $this->query->entity(Material::class)->where(Material::F_PRIMARY, array_keys($collection))->exec();
171
172
173
174
            // Go through collection again and created specific rows
175
            foreach ($collection as $materialID => $fields) {
176
                $this->collection[$materialID] = new $this->rowInstance($materialID, array_merge($fields, array('created' => $materials[$materialID]->Created, 'modified' => $materials[$materialID]->Modyfied)));
177
            }
178
        }
179
180
        return $this->collection;
181
    }
182
183
    /**
184
     * FieldsTable constructor.
185
     *
186
     * @param QueryInterface $query        Database query interface
187
     * @param int[]        $navigationID Navigation identifier for table structure
188
     * @param integer        $materialID   Table parent material identifier
189
     * @param string|null    $locale       Locale identifier
190
     */
191
    public function __construct(QueryInterface $query, $navigationID, $materialID, $locale = null)
192
    {
193
        $this->query = $query;
194
        $this->navigationID = $navigationID;
0 ignored issues
show
Documentation Bug introduced by
It seems like $navigationID of type array<integer,integer> is incompatible with the declared type integer of property $navigationID.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
195
        $this->materialID = $materialID;
196
        $this->locale = $locale;
197
198
        $this->find();
199
    }
200
}
201