Completed
Push — master ( a5ec56...0143f1 )
by Vitaly
04:57 queued 02:19
created

VirtualAnalyzer::getChildEntities()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 8
rs 9.4285
cc 1
eloc 3
nc 1
nop 1
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\generator\exception\ParentEntityNotFound;
12
use samsoncms\api\generator\metadata\GenericMetadata;
13
use samsoncms\api\Navigation;
14
15
/**
16
 * Generic entities metadata analyzer.
17
 *
18
 * @package samsoncms\api\analyzer
19
 */
20
class VirtualAnalyzer extends GenericAnalyzer
21
{
22
    /** @var string Metadata class */
23
    protected $metadataClass = \samsoncms\api\generator\metadata\VirtualMetadata::class;
24
25
    /**
26
     * Analyze virtual entities and gather their metadata.
27
     *
28
     * @return \samsoncms\api\generator\metadata\VirtualMetadata[]
29
     * @throws ParentEntityNotFound
30
     */
31
    public function analyze()
32
    {
33
        $metadataCollection = [];
34
35
        // Iterate all structures, parents first
36
        foreach ($this->getVirtualEntities() as $structureRow) {
37
            // Fill in entity metadata
38
            $metadata = new $this->metadataClass;
39
40
            $this->analyzeEntityRecord($metadata, $structureRow);
41
42
            // TODO: Add multiple parent and fetching their data in a loop
43
44
            // Set pointer to parent entity
45
            if (null !== $metadata->parentID && (int)$structureRow[Navigation::F_TYPE] === \samsoncms\api\generator\metadata\VirtualMetadata::TYPE_STRUCTURE) {
46
                if (array_key_exists($metadata->parentID, GenericMetadata::$instances)) {
47
                    $metadata->parent = $metadataCollection[$metadata->parentID];
48
                    // Add all parent metadata to current object
49
                    $metadata->defaultValues = $metadata->parent->defaultValues;
50
                    $metadata->realNames = $metadata->parent->realNames;
51
                    $metadata->fields = $metadata->parent->fields;
52
                    $metadata->fieldNames = $metadata->parent->fieldNames;
53
                    $metadata->types = $metadata->parent->types;
54
                    $metadata->allFieldValueColumns = $metadata->parent->allFieldValueColumns;
55
                    $metadata->fieldDescriptions = $metadata->parent->fieldDescriptions;
56
                    $metadata->localizedFieldIDs = $metadata->parent->localizedFieldIDs;
57
                    $metadata->notLocalizedFieldIDs = $metadata->parent->notLocalizedFieldIDs;
58
                } else {
59
                    throw new ParentEntityNotFound($metadata->parentID);
60
                }
61
            }
62
63
            // Get old AR collections of metadata
64
            $metadata->arSelect = \samson\activerecord\material::$_sql_select;
65
            $metadata->arAttributes = \samson\activerecord\material::$_attributes;
66
            $metadata->arMap = \samson\activerecord\material::$_map;
67
            $metadata->arFrom = \samson\activerecord\material::$_sql_from;
68
            $metadata->arGroup = \samson\activerecord\material::$_own_group;
69
            $metadata->arRelationAlias = \samson\activerecord\material::$_relation_alias;
70
            $metadata->arRelationType = \samson\activerecord\material::$_relation_type;
71
            $metadata->arRelations = \samson\activerecord\material::$_relations;
72
73
            // Add SamsonCMS material needed data
74
            $metadata->arSelect['this'] = ' STRAIGHT_JOIN ' . $metadata->arSelect['this'];
75
            $metadata->arFrom['this'] .= "\n" .
76
                'LEFT JOIN ' . dbMySQLConnector::$prefix . 'materialfield as _mf
77
            ON ' . dbMySQLConnector::$prefix . 'material.MaterialID = _mf.MaterialID';
78
            $metadata->arGroup[] = dbMySQLConnector::$prefix . 'material.MaterialID';
79
80
            // Iterate entity fields
81
            foreach ($this->getEntityFields($structureRow[Navigation::F_PRIMARY]) as $fieldID => $fieldRow) {
82
                $this->analyzeFieldRecord($metadata, $fieldID, $fieldRow);
83
84
                // Get camelCase and transliterated field name
85
                $fieldName = $this->fieldName($fieldRow[Field::F_IDENTIFIER]);
86
87
                // Fill localization fields collections
88
                if ($fieldRow[Field::F_LOCALIZED] == 1) {
89
                    $metadata->localizedFieldIDs[$fieldID] = $fieldName;
90
                } else {
91
                    $metadata->notLocalizedFieldIDs[$fieldID] = $fieldName;
92
                }
93
94
                // Set old AR collections of metadata
95
                $metadata->arAttributes[$fieldName] = $fieldName;
96
                $metadata->arMap[$fieldName] = dbMySQLConnector::$prefix . 'material.' . $fieldName;
97
98
                // Add additional field column to entity query
99
                $equal = '((_mf.FieldID = ' . $fieldID . ')&&(_mf.locale ' . ($fieldRow['local'] ? ' = "@locale"' : 'IS NULL') . '))';
100
                $metadata->arSelect['this'] .= "\n\t\t" . ',MAX(IF(' . $equal . ', _mf.`' . Field::valueColumn($fieldRow['Type']) . '`, NULL)) as `' . $fieldName . '`';
101
            }
102
103
            // Store metadata by entity identifier
104
            $metadataCollection[(int)$structureRow[Navigation::F_PRIMARY]] = $metadata;
105
            // Store global collection
106
            GenericMetadata::$instances[(int)$structureRow[Navigation::F_PRIMARY]] = $metadata;
107
        }
108
109
110
        return $metadataCollection;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $metadataCollection; (array) 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...
111
    }
112
113
    /**
114
     * Get virtual entities from database by their type.
115
     *
116
     * @param int $type Virtual entity type
117
     *
118
     * @return array Get collection of navigation objects
119
     */
120
    protected function getVirtualEntities($type = 0)
121
    {
122
        return $this->database->fetch('
123
        SELECT * FROM `structure`
124
        WHERE `Active` = "1" AND `Type` = "' . $type . '"
125
        ORDER BY `ParentID` ASC
126
        ');
127
    }
128
129
    /**
130
     * Analyze entity.
131
     *
132
     * @param \samsoncms\api\generator\metadata\VirtualMetadata $metadata
133
     * @param array                                             $structureRow Entity database row
134
     */
135
    public function analyzeEntityRecord(&$metadata, array $structureRow)
136
    {
137
        $metadata->structureRow = $structureRow;
138
139
        // Get CapsCase and transliterated entity name
140
        $metadata->entity = $this->entityName($structureRow[Navigation::F_NAME]);
141
        $metadata->entityClassName = $this->fullEntityName($metadata->entity);
142
        $metadata->entityRealName = $structureRow[Navigation::F_NAME];
143
        $metadata->entityID = $structureRow[Navigation::F_PRIMARY];
144
        $metadata->type = (int)$structureRow[Navigation::F_TYPE];
145
146
        // Try to find entity parent identifier for building future relations
147
        $metadata->parentID = $this->getParentEntity($structureRow[Navigation::F_PRIMARY]);
148
    }
149
150
    /**
151
     * Find entity parent identifier.
152
     *
153
     * @param int $entityID Entity identifier
154
     *
155
     * @return null|int Parent entity identifier
156
     */
157
    public function getParentEntity($entityID)
158
    {
159
        $parentData = $this->database->fetch('
160
SELECT *
161
FROM structure_relation as sm
162
JOIN structure as s ON s.StructureID = sm.parent_id
163
WHERE sm.child_id = "' . $entityID . '"
164
AND s.StructureID != "' . $entityID . '"
165
');
166
        // Get parent entity identifier
167
        return count($parentData) ? $parentData[0]['StructureID'] : null;
168
    }
169
170
    /**
171
     * Get entity fields.
172
     *
173
     * @param int $entityID Entity identifier
174
     *
175
     * @return array Collection of entity fields
176
     */
177
    protected function getEntityFields($entityID)
178
    {
179
        $return = array();
180
        // TODO: Optimize queries make one single query with only needed data
181
        foreach ($this->database->fetch('SELECT * FROM `structurefield` WHERE `StructureID` = "' . $entityID . '" AND `Active` = "1"') as $fieldStructureRow) {
182
            foreach ($this->database->fetch('SELECT * FROM `field` WHERE `FieldID` = "' . $fieldStructureRow['FieldID'] . '"') as $fieldRow) {
183
                $return[$fieldRow['FieldID']] = $fieldRow;
184
            }
185
        }
186
187
        return $return;
188
    }
189
190
    /**
191
     * Virtual entity additional field analyzer.
192
     *
193
     * @param \samsoncms\api\generator\metadata\VirtualMetadata $metadata Metadata instance for filling
194
     * @param int                                               $fieldID  Additional field identifier
195
     * @param array                                             $fieldRow Additional field database row
196
     */
197
    public function analyzeFieldRecord(&$metadata, $fieldID, array $fieldRow)
198
    {
199
        // Get camelCase and transliterated field name
200
        $fieldName = $this->fieldName($fieldRow[Field::F_IDENTIFIER]);
201
202
        // TODO: Set default for additional field storing type accordingly.
203
204
        // Store field metadata
205
        $metadata->realNames[$fieldRow[Field::F_IDENTIFIER]] = $fieldName;
206
        $metadata->fields[$fieldID] = $fieldName;
207
        $metadata->fieldNames[$fieldName] = $fieldID;
208
        $metadata->allFieldValueColumns[$fieldID] = Field::valueColumn($fieldRow[Field::F_TYPE]);
209
        $metadata->types[$fieldID] = Field::phpType($fieldRow[Field::F_TYPE]);
210
        $metadata->allFieldCmsTypes[$fieldID] = (int)$fieldRow[Field::F_TYPE];
211
        $metadata->fieldDescriptions[$fieldID] = $fieldRow[Field::F_DESCRIPTION] . ', ' . $fieldRow[Field::F_IDENTIFIER] . '#' . $fieldID;
212
        $metadata->fieldRawDescriptions[$fieldID] = $fieldRow[Field::F_DESCRIPTION];
213
    }
214
215
    /**
216
     * Get child entities by parent identifier.
217
     *
218
     * @param int $parentId Parent entity identifier
219
     *
220
     * @return array Get collection of child navigation objects
221
     */
222
    protected function getChildEntities($parentId)
223
    {
224
        return $this->database->fetch('
225
        SELECT * FROM `structure`
226
        WHERE `Active` = "1" AND `ParentID` = ' . $parentId . '
227
        ORDER BY `ParentID` ASC
228
        ');
229
    }
230
}
231
//[PHPCOMPRESSOR(remove,end)]