Completed
Push — master ( 4f4aae...6745e3 )
by Vitaly
02:58
created

Virtual::getParentEntity()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

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