VirtualAnalyzer::analyze()   C
last analyzed

Complexity

Conditions 7
Paths 8

Size

Total Lines 89
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 89
rs 6.5134
c 0
b 0
f 0
cc 7
eloc 33
nc 8
nop 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
//[PHPCOMPRESSOR(remove,start)]
3
/**
4
 * Created by Vitaly Iegorov <[email protected]>.
5
 * on 23.03.16 at 11:45
6
 */
7
namespace samsoncms\api\generator\analyzer;
8
9
use samson\activerecord\dbMySQLConnector;
10
use samsoncms\api\Field;
11
use samsoncms\api\generated\Material;
12
use samsoncms\api\generator\exception\ParentEntityNotFound;
13
use samsoncms\api\generator\metadata\GenericMetadata;
14
use samsoncms\api\generator\metadata\VirtualMetadata;
15
use samsoncms\api\Navigation;
16
17
/**
18
 * Generic entities metadata analyzer.
19
 *
20
 * @package samsoncms\api\analyzer
21
 */
22
class VirtualAnalyzer extends GenericAnalyzer
23
{
24
    /** @var string Metadata class */
25
    protected $metadataClass = \samsoncms\api\generator\metadata\VirtualMetadata::class;
26
27
    /**
28
     * Analyze virtual entities and gather their metadata.
29
     *
30
     * @return \samsoncms\api\generator\metadata\VirtualMetadata[]
31
     * @throws ParentEntityNotFound
32
     */
33
    public function analyze()
34
    {
35
        /** @var RealMetadata[] $metadataCollection Set pointer to global metadata collection */
36
        $metadataCollection = [];
37
38
        // Iterate all structures, parents first
39
        foreach ($this->getVirtualEntities() as $structureRow) {
40
            $entity = $this->entityName($structureRow[Navigation::F_NAME]);
41
42
            /** @var VirtualMetadata $metadata Fill in entity metadata */
43
            $metadata = new $this->metadataClass($this->fullEntityName($entity));
44
45
            $this->analyzeEntityRecord($metadata, $entity, $structureRow);
46
47
            // TODO: Add multiple parent and fetching their data in a loop
48
49
            // Set pointer to parent entity
50
            if (null !== $metadata->parentID && (int)$structureRow[Navigation::F_TYPE] === \samsoncms\api\generator\metadata\VirtualMetadata::TYPE_STRUCTURE) {
51
                if (array_key_exists($metadata->parentID, $metadataCollection)) {
52
                    $metadata->parent = $metadataCollection[$metadata->parentID];
0 ignored issues
show
Documentation Bug introduced by
It seems like $metadataCollection[$metadata->parentID] can also be of type object<samsoncms\api\gen...\analyzer\RealMetadata>. However, the property $parent is declared as type object<samsoncms\api\gen...tadata\VirtualMetadata>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
53
                    // Add all parent metadata to current object
54
                    $metadata->defaultValues = $metadata->parent->defaultValues;
55
                    $metadata->realNames = $metadata->parent->realNames;
56
                    $metadata->fields = $metadata->parent->fields;
57
                    $metadata->fieldNames = $metadata->parent->fieldNames;
58
                    $metadata->types = $metadata->parent->types;
59
                    $metadata->allFieldValueColumns = $metadata->parent->allFieldValueColumns;
60
                    $metadata->allFieldCmsTypes = $metadata->parent->allFieldCmsTypes;
61
                    $metadata->fieldDescriptions = $metadata->parent->fieldDescriptions;
62
                    $metadata->localizedFieldIDs = $metadata->parent->localizedFieldIDs;
63
                    $metadata->notLocalizedFieldIDs = $metadata->parent->notLocalizedFieldIDs;
64
                } else {
65
                    throw new ParentEntityNotFound($metadata->parentID);
66
                }
67
            } else {
68
                $metadata->parent = GenericMetadata::$instances[Material::class];
69
            }
70
71
//            // Get old AR collections of metadata
72
//            $metadata->arSelect = \samson\activerecord\material::$_sql_select;
73
//            $metadata->arAttributes = \samson\activerecord\material::$_attributes;
74
//            $metadata->arMap = \samson\activerecord\material::$_map;
75
//            $metadata->arFrom = \samson\activerecord\material::$_sql_from;
76
//            $metadata->arGroup = \samson\activerecord\material::$_own_group;
77
//            $metadata->arRelationAlias = \samson\activerecord\material::$_relation_alias;
78
//            $metadata->arRelationType = \samson\activerecord\material::$_relation_type;
79
//            $metadata->arRelations = \samson\activerecord\material::$_relations;
80
81
//            // Add SamsonCMS material needed data
82
//            $metadata->arSelect['this'] = ' STRAIGHT_JOIN ' . $metadata->arSelect['this'];
83
//            $metadata->arFrom['this'] .= "\n" .
84
//                'LEFT JOIN ' . $this->database::$prefix . 'materialfield as _mf
85
//            ON ' . $this->database::$prefix . 'material.MaterialID = _mf.MaterialID';
86
//            $metadata->arGroup[] = $this->database::$prefix . 'material.MaterialID';
87
88
            // Add material table real fields
89
90
91
            // Iterate entity fields
92
            foreach ($this->getEntityFields($structureRow[Navigation::F_PRIMARY]) as $fieldID => $fieldRow) {
93
                $this->analyzeFieldRecord($metadata, $fieldID, $fieldRow);
94
95
                // Get camelCase and transliterated field name
96
                $fieldName = $this->fieldName($fieldRow[Field::F_IDENTIFIER]);
97
98
                // Fill localization fields collections
99
                if ($fieldRow[Field::F_LOCALIZED] == 1) {
100
                    $metadata->localizedFieldIDs[$fieldID] = $fieldName;
101
                } else {
102
                    $metadata->notLocalizedFieldIDs[$fieldID] = $fieldName;
103
                }
104
//
105
//                // Set old AR collections of metadata
106
//                $metadata->arAttributes[$fieldName] = $fieldName;
107
//                $metadata->arMap[$fieldName] = $this->database::$prefix . 'material.' . $fieldName;
108
109
//                // Add additional field column to entity query
110
//                $equal = '((_mf.FieldID = ' . $fieldID . ')&&(_mf.locale ' . ($fieldRow['local'] ? ' = "@locale"' : 'IS NULL') . '))';
111
//                $metadata->arSelect['this'] .= "\n\t\t" . ',MAX(IF(' . $equal . ', _mf.`' . Field::valueColumn($fieldRow['Type']) . '`, NULL)) as `' . $fieldName . '`';
112
            }
113
114
            // Store metadata by entity identifier
115
            $metadataCollection[(int)$structureRow[Navigation::F_PRIMARY]] = $metadata;
116
            // Store virtual metadata
117
            GenericMetadata::$instances[(int)$structureRow[Navigation::F_PRIMARY]] = $metadata;
118
        }
119
120
        return $metadataCollection;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $metadataCollection; (array<samsoncms\api\gene...tadata\VirtualMetadata>) is incompatible with the return type of the parent method samsoncms\api\generator\...enericAnalyzer::analyze of type samsoncms\api\generator\...\GenericMetadata[]|null.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
121
    }
122
123
    /**
124
     * Get virtual entities from database by their type.
125
     *
126
     * @param int $type Virtual entity type
127
     *
128
     * @return array Get collection of navigation objects
129
     */
130
    protected function getVirtualEntities($type = 0)
131
    {
132
        $navigations = $this->database->fetch('
133
        SELECT * FROM `structure`
134
        WHERE `Active` = "1" AND `Type` = "' . $type . '"
135
        ORDER BY `ParentID` ASC
136
        ');
137
138
        // Store navigation elements by identifiers
139
        $navigationsIDs = [];
140
        foreach ($navigations as $navigation) {
141
            $navigationsIDs[$navigation['StructureID']] = $navigation;
142
        }
143
144
        $tree = [];
145
        foreach ($navigationsIDs as $navigationID => $navigation) {
146
            $arrayDefinition = [];
147
            $parentPointer = $navigation;
148
            do {
149
                $arrayDefinition[] = '['.$parentPointer['StructureID'].']';
150
                $parentPointer = array_key_exists($parentPointer['ParentID'], $navigationsIDs) ? $navigationsIDs[$parentPointer['ParentID']] : null;
151
            } while (null !== $parentPointer);
152
153
            // Create multi-dimensional array
154
            eval('$tree'.implode('', array_reverse($arrayDefinition)).'[$navigationID] = $navigationID;');
155
        }
156
157
158
        // Walk recursive array and using array keys fill flat array in correct order to preserve parent/child relations
159
        $output = [];
160
        array_walk_recursive($tree, function($value, $key) use (&$output, &$navigationsIDs) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after FUNCTION keyword; 0 found
Loading history...
161
            $output[$key] = $navigationsIDs[$key];
162
        });
163
164
        // TODO: This function still works wrong when child has earlier id than parent
165
        return $output;
166
    }
167
168
    /**
169
     * Analyze entity.
170
     *
171
     * @param \samsoncms\api\generator\metadata\VirtualMetadata $metadata
172
     * @param string $entity
173
     * @param array $structureRow Entity database row
174
     */
175
    public function analyzeEntityRecord(VirtualMetadata $metadata, string $entity, array $structureRow)
176
    {
177
        $metadata->structureRow = $structureRow;
178
179
        // Get CapsCase and transliterated entity name
180
        $metadata->entity = $entity;
181
        $metadata->entityRealName = $structureRow[Navigation::F_NAME];
182
        $metadata->entityID = $structureRow[Navigation::F_PRIMARY];
183
        $metadata->type = (int)$structureRow[Navigation::F_TYPE];
184
185
        // Try to find entity parent identifier for building future relations
186
        $metadata->parentID = $this->getParentEntity($structureRow[Navigation::F_PRIMARY]);
187
    }
188
189
    /**
190
     * Find entity parent identifier.
191
     *
192
     * @param int $entityID Entity identifier
193
     *
194
     * @return null|int Parent entity identifier
195
     */
196
    public function getParentEntity($entityID)
197
    {
198
        $parentData = $this->database->fetch('
199
SELECT *
200
FROM structure_relation as sm
201
JOIN structure as s ON s.StructureID = sm.parent_id
202
WHERE sm.child_id = "' . $entityID . '"
203
AND s.StructureID != "' . $entityID . '"
204
');
205
        // Get parent entity identifier
206
        return count($parentData) ? $parentData[0]['StructureID'] : null;
207
    }
208
209
    /**
210
     * Get entity fields.
211
     *
212
     * @param int $entityID Entity identifier
213
     *
214
     * @return array Collection of entity fields
215
     */
216
    protected function getEntityFields($entityID)
217
    {
218
        $return = array();
219
        // TODO: Optimize queries make one single query with only needed data
220
        foreach ($this->database->fetch('SELECT * FROM `structurefield` WHERE `StructureID` = "' . $entityID . '" AND `Active` = "1"') as $fieldStructureRow) {
221
            foreach ($this->database->fetch('SELECT * FROM `field` WHERE `FieldID` = "' . $fieldStructureRow['FieldID'] . '"') as $fieldRow) {
222
                $return[$fieldRow['FieldID']] = $fieldRow;
223
            }
224
        }
225
226
        return $return;
227
    }
228
229
    /**
230
     * Virtual entity additional field analyzer.
231
     *
232
     * @param \samsoncms\api\generator\metadata\VirtualMetadata $metadata Metadata instance for filling
233
     * @param int                                               $fieldID  Additional field identifier
234
     * @param array                                             $fieldRow Additional field database row
235
     */
236
    public function analyzeFieldRecord(&$metadata, $fieldID, array $fieldRow)
237
    {
238
        // Get camelCase and transliterated field name
239
        $fieldName = $this->fieldName($fieldRow[Field::F_IDENTIFIER]);
240
241
        // TODO: Set default for additional field storing type accordingly.
242
243
        // Store field metadata
244
        $metadata->realNames[$fieldRow[Field::F_IDENTIFIER]] = $fieldName;
245
        $metadata->fields[$fieldID] = $fieldName;
246
        $metadata->fieldNames[$fieldName] = $fieldID;
247
        $metadata->allFieldValueColumns[$fieldID] = Field::valueColumn($fieldRow[Field::F_TYPE]);
248
        $metadata->types[$fieldID] = Field::phpType($fieldRow[Field::F_TYPE]);
249
        $metadata->allFieldCmsTypes[$fieldID] = (int)$fieldRow[Field::F_TYPE];
250
        $metadata->fieldDescriptions[$fieldID] = $fieldRow[Field::F_DESCRIPTION] . ', ' . $fieldRow[Field::F_IDENTIFIER] . '#' . $fieldID;
251
        $metadata->fieldRawDescriptions[$fieldID] = $fieldRow[Field::F_DESCRIPTION];
252
    }
253
254
    /**
255
     * Get child entities by parent identifier.
256
     *
257
     * @param int $parentId Parent entity identifier
258
     *
259
     * @return array Get collection of child navigation objects
260
     */
261
    protected function getChildEntities($parentId)
262
    {
263
        return $this->database->fetch('
264
        SELECT * FROM `structure`
265
        WHERE `Active` = "1" AND `ParentID` = ' . $parentId . '
266
        ORDER BY `ParentID` ASC
267
        ');
268
    }
269
}
270
//[PHPCOMPRESSOR(remove,end)]
271