Completed
Push — develop ( 0d96fa...aab434 )
by Neomerx
02:11
created

DataSettings::getModelsSchemaInfo()   C

Complexity

Conditions 12
Paths 1

Size

Total Lines 82
Code Lines 50

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 51
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 82
rs 5.034
c 0
b 0
f 0
ccs 51
cts 51
cp 1
cc 12
eloc 50
nc 1
nop 1
crap 12

How to fix   Long Method    Complexity   

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 namespace Limoncello\Application\Packages\Data;
2
3
/**
4
 * Copyright 2015-2017 [email protected]
5
 *
6
 * Licensed under the Apache License, Version 2.0 (the "License");
7
 * you may not use this file except in compliance with the License.
8
 * You may obtain a copy of the License at
9
 *
10
 * http://www.apache.org/licenses/LICENSE-2.0
11
 *
12
 * Unless required by applicable law or agreed to in writing, software
13
 * distributed under the License is distributed on an "AS IS" BASIS,
14
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
 * See the License for the specific language governing permissions and
16
 * limitations under the License.
17
 */
18
19
use Limoncello\Application\Data\ModelSchemaInfo;
20
use Limoncello\Contracts\Application\ModelInterface;
21
use Limoncello\Contracts\Data\RelationshipTypes;
22
use Limoncello\Contracts\Settings\SettingsInterface;
23
use Limoncello\Core\Reflection\CheckCallableTrait;
24
use Limoncello\Core\Reflection\ClassIsTrait;
25
use Psr\Container\ContainerInterface;
26
27
/**
28
 * @package Limoncello\Application
29
 */
30
abstract class DataSettings implements SettingsInterface
31
{
32
    use ClassIsTrait, CheckCallableTrait;
33
34
    /** Settings key */
35
    const KEY_MODELS_FOLDER = 0;
36
37
    /** Settings key */
38
    const KEY_MODELS_FILE_MASK = self::KEY_MODELS_FOLDER + 1;
39
40
    /** Settings key */
41
    const KEY_MIGRATIONS_FOLDER = self::KEY_MODELS_FILE_MASK + 1;
42
43
    /** Settings key */
44
    const KEY_MIGRATIONS_LIST_FILE = self::KEY_MIGRATIONS_FOLDER + 1;
45
46
    /** Settings key */
47
    const KEY_SEEDS_FOLDER = self::KEY_MIGRATIONS_LIST_FILE + 1;
48
49
    /** Settings key */
50
    const KEY_SEEDS_LIST_FILE = self::KEY_SEEDS_FOLDER + 1;
51
52
    /** Settings key */
53
    const KEY_SEED_INIT = self::KEY_SEEDS_LIST_FILE + 1;
54
55
    /** Settings key */
56
    const KEY_MODELS_SCHEMA_INFO = self::KEY_SEED_INIT + 1;
57
58
    /** Settings key */
59
    protected const KEY_LAST = self::KEY_MODELS_SCHEMA_INFO;
60
61
    /**
62
     * @inheritdoc
63
     */
64 2
    final public function get(array $appConfig): array
65
    {
66 2
        $defaults = $this->getSettings();
67
68 2
        $modelsFolder       = $defaults[static::KEY_MODELS_FOLDER] ?? null;
69 2
        $modelsFileMask     = $defaults[static::KEY_MODELS_FILE_MASK] ?? null;
70 2
        $migrationsFolder   = $defaults[static::KEY_MIGRATIONS_FOLDER] ?? null;
71 2
        $migrationsListFile = $defaults[static::KEY_MIGRATIONS_LIST_FILE] ?? null;
72 2
        $seedsFolder        = $defaults[static::KEY_SEEDS_FOLDER] ?? null;
73 2
        $seedsListFile      = $defaults[static::KEY_SEEDS_LIST_FILE] ?? null;
74
75 2
        assert(
76 2
            $modelsFolder !== null && empty(glob($modelsFolder)) === false,
77 2
            "Invalid Models folder `$modelsFolder`."
78
        );
79 2
        assert(empty($modelsFileMask) === false, "Invalid Models file mask `$modelsFileMask`.");
80 2
        assert(
81 2
            $migrationsFolder !== null && empty(glob($migrationsFolder)) === false,
82 2
            "Invalid Migrations folder `$migrationsFolder`."
83
        );
84 2
        assert(file_exists($migrationsListFile) === true, "Invalid Migrations file `$migrationsListFile`.");
85 2
        assert(
86 2
            $seedsFolder !== null && empty(glob($seedsFolder)) === false,
87 2
            "Invalid Seeds folder `$seedsFolder`."
88
        );
89 2
        assert(file_exists($seedsListFile) === true, "Invalid Seeds file `$seedsListFile`.");
90
91 2
        $modelsPath = $modelsFolder . DIRECTORY_SEPARATOR . $modelsFileMask;
92
93 2
        $seedInit = $defaults[static::KEY_SEED_INIT] ?? null;
94 2
        assert(
95
            (
96 2
                $seedInit === null ||
97 2
                $this->checkPublicStaticCallable($seedInit, [ContainerInterface::class, 'string']) === true
98
            ),
99 2
            'Seed init should be either `null` or static callable.'
100
        );
101
102 2
        $defaults[static::KEY_MODELS_SCHEMA_INFO] = $this->getModelsSchemaInfo($modelsPath);
103
104 2
        return $defaults;
105
    }
106
107
    /**
108
     * @return array
109
     */
110 2
    protected function getSettings(): array
111
    {
112
        return [
113 2
            static::KEY_MODELS_FILE_MASK => '*.php',
114 2
            static::KEY_SEED_INIT        => null,
115
        ];
116
    }
117
118
    /**
119
     * @param string $modelsPath
120
     *
121
     * @return array
122
     *
123
     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
124
     */
125 2
    private function getModelsSchemaInfo(string $modelsPath): array
126
    {
127
        // check reverse relationships
128 2
        $requireReverseRel = true;
129
130 2
        $registered    = [];
131 2
        $modelSchemas  = new ModelSchemaInfo();
132 2
        $registerModel = function ($modelClass) use ($modelSchemas, &$registered, $requireReverseRel) {
133
            /** @var ModelInterface $modelClass */
134 2
            $modelSchemas->registerClass(
135 2
                $modelClass,
136 2
                $modelClass::getTableName(),
137 2
                $modelClass::getPrimaryKeyName(),
138 2
                $modelClass::getAttributeTypes(),
139 2
                $modelClass::getAttributeLengths()
140
            );
141
142 2
            $relationships = $modelClass::getRelationships();
143
144 2
            if (array_key_exists(RelationshipTypes::BELONGS_TO, $relationships) === true) {
145 2
                foreach ($relationships[RelationshipTypes::BELONGS_TO] as $relName => list($rClass, $fKey, $rRel)) {
146
                    /** @var string $rClass */
147 2
                    $modelSchemas->registerBelongsToOneRelationship($modelClass, $relName, $fKey, $rClass, $rRel);
148 2
                    $registered[(string)$modelClass][$relName] = true;
149 2
                    $registered[$rClass][$rRel]                = true;
150
151
                    // Sanity check. Every `belongs_to` should be paired with `has_many` on the other side.
152
                    /** @var ModelInterface $rClass */
153 2
                    $rRelationships   = $rClass::getRelationships();
154 2
                    $isRelationshipOk = $requireReverseRel === false ||
155 2
                        (isset($rRelationships[RelationshipTypes::HAS_MANY][$rRel]) === true &&
156 2
                            $rRelationships[RelationshipTypes::HAS_MANY][$rRel] === [$modelClass, $fKey, $relName]);
157
                    /** @var string $modelClass */
158
159 2
                    assert($isRelationshipOk, "`belongsTo` relationship `$relName` of class $modelClass " .
160 2
                        "should be paired with `hasMany` relationship.");
161
                }
162
            }
163
164 2
            if (array_key_exists(RelationshipTypes::HAS_MANY, $relationships) === true) {
165 2
                foreach ($relationships[RelationshipTypes::HAS_MANY] as $relName => list($rClass, $fKey, $rRel)) {
166
                    // Sanity check. Every `has_many` should be paired with `belongs_to` on the other side.
167
                    /** @var ModelInterface $rClass */
168 2
                    $rRelationships   = $rClass::getRelationships();
169 2
                    $isRelationshipOk = $requireReverseRel === false ||
170 2
                        (isset($rRelationships[RelationshipTypes::BELONGS_TO][$rRel]) === true &&
171 2
                            $rRelationships[RelationshipTypes::BELONGS_TO][$rRel] === [$modelClass, $fKey, $relName]);
172
                    /** @var string $modelClass */
173 2
                    assert($isRelationshipOk, "`hasMany` relationship `$relName` of class $modelClass " .
174 2
                        "should be paired with `belongsTo` relationship.");
175
                }
176
            }
177
178 2
            if (array_key_exists(RelationshipTypes::BELONGS_TO_MANY, $relationships) === true) {
179 2
                foreach ($relationships[RelationshipTypes::BELONGS_TO_MANY] as $relName => $data) {
180 2
                    if (isset($registered[(string)$modelClass][$relName]) === true) {
181 2
                        continue;
182
                    }
183
                    /** @var string $rClass */
184 2
                    list($rClass, $iTable, $fKeyPrimary, $fKeySecondary, $rRel) = $data;
185 2
                    $modelSchemas->registerBelongsToManyRelationship(
186 2
                        $modelClass,
187 2
                        $relName,
188 2
                        $iTable,
189 2
                        $fKeyPrimary,
190 2
                        $fKeySecondary,
191 2
                        $rClass,
192 2
                        $rRel
193
                    );
194 2
                    $registered[(string)$modelClass][$relName] = true;
195 2
                    $registered[$rClass][$rRel]                = true;
196
                }
197
            }
198 2
        };
199
200 2
        $modelClasses = iterator_to_array($this->selectClasses($modelsPath, ModelInterface::class));
201 2
        array_map($registerModel, $modelClasses);
202
203 2
        $data = $modelSchemas->getData();
204
205 2
        return $data;
206
    }
207
}
208