Passed
Push — master ( 034e39...aabddd )
by Andrea Marco
04:28 queued 11s
created

ModelPropertiesMapper::shouldGenerateNestedDto()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 3
c 1
b 0
f 0
nc 3
nop 2
dl 0
loc 7
ccs 4
cts 4
cp 1
crap 4
rs 10
1
<?php
2
3
namespace Cerbero\LaravelDto\Console;
4
5
use Illuminate\Support\Facades\Artisan;
6
use Illuminate\Support\Facades\Schema;
7
use Illuminate\Support\Str;
8
use ReflectionClass;
9
use ReflectionMethod;
10
11
/**
12
 * The model properties mapper.
13
 *
14
 */
15
class ModelPropertiesMapper
16
{
17
    /**
18
     * The cached model file.
19
     *
20
     * @var array
21
     */
22
    protected $cachedFile;
23
24
    /**
25
     * The map between schema and PHP types.
26
     *
27
     * @var array
28
     */
29
    protected $schemaTypesMap = [
30
        'guid'     => 'string',
31
        'boolean'  => 'bool',
32
        'datetime' => 'Carbon\Carbon',
33
        'string'   => 'string',
34
        'json'     => 'string',
35
        'integer'  => 'int',
36
        'date'     => 'Carbon\Carbon',
37
        'smallint' => 'int',
38
        'text'     => 'string',
39
        'decimal'  => 'float',
40
        'bigint'   => 'int',
41
    ];
42
43
    /**
44
     * The map determining whether a relation involves many models.
45
     *
46
     * @var array
47
     */
48
    protected $relationsMap = [
49
        'hasOne'         => false,
50
        'morphOne'       => false,
51
        'belongsTo'      => false,
52
        'morphTo'        => false,
53
        'hasMany'        => true,
54
        'hasManyThrough' => true,
55
        'morphMany'      => true,
56
        'belongsToMany'  => true,
57
        'morphToMany'    => true,
58
        'morphedByMany'  => true,
59
    ];
60
61
    /**
62
     * The manifest.
63
     *
64
     * @var Manifest
65
     */
66
    protected $manifest;
67
68
    /**
69
     * The DTO qualifier.
70
     *
71
     * @var DtoQualifierContract
72
     */
73
    protected $qualifier;
74
75
    /**
76
     * Instantiate the class.
77
     *
78
     * @param Manifest $manifest
79
     * @param DtoQualifierContract $qualifier
80
     */
81 9
    public function __construct(Manifest $manifest, DtoQualifierContract $qualifier)
82
    {
83 9
        $this->manifest = $manifest;
84 9
        $this->qualifier = $qualifier;
85 9
    }
86
87
    /**
88
     * Retrieve the properties map of the given data to generate
89
     *
90
     * @param DtoGenerationData $data
91
     * @return array
92
     */
93 6
    public function map(DtoGenerationData $data): array
94
    {
95 6
        $propertiesFromDatabase = $this->mapPropertiesFromDatabase($data);
96 6
        $propertiesFromRelations = $this->mapPropertiesFromRelations($data);
97
98 6
        return $propertiesFromDatabase + $propertiesFromRelations;
99
    }
100
101
    /**
102
     * Retrieve the given model properties from the database
103
     *
104
     * @param DtoGenerationData $data
105
     * @return array
106
     */
107 6
    public function mapPropertiesFromDatabase(DtoGenerationData $data): array
108
    {
109 6
        $properties = [];
110 6
        $table = $data->model->getTable();
111 6
        $connection = $data->model->getConnection();
112
113 6
        foreach (Schema::getColumnListing($table) as $column) {
114 6
            $camelColumn = Str::camel($column);
115 6
            $rawType = Schema::getColumnType($table, $column);
116 6
            $types = [$this->schemaTypesMap[$rawType]];
117
118 6
            if (!$connection->getDoctrineColumn($table, $column)->getNotnull()) {
119 6
                $types[] = 'null';
120
            }
121
122 6
            $properties[$camelColumn] = $types;
123
        }
124
125 6
        return $properties;
126
    }
127
128
    /**
129
     * Retrieve the given model properties from its relations
130
     *
131
     * @param DtoGenerationData $data
132
     * @return array
133
     */
134 9
    public function mapPropertiesFromRelations(DtoGenerationData $data): array
135
    {
136 9
        $properties = [];
137 9
        $relations = implode('|', array_keys($this->relationsMap));
138 9
        $reflection = new ReflectionClass($data->model);
139 9
        $methods = $reflection->getMethods(ReflectionMethod::IS_PUBLIC);
140
141 9
        foreach ($methods as $method) {
142 9
            if ($method->getFileName() != $reflection->getFileName()) {
143 9
                continue;
144
            }
145
146 9
            if (!preg_match("/\\\$this->($relations)\W+([\w\\\]+)/", $this->getMethodBody($method), $matches)) {
147 6
                continue;
148
            }
149
150 9
            [, $relation, $relatedModel] = $matches;
151
152 9
            if (!$qualifiedModel = $this->qualifyModel($relatedModel, $reflection)) {
153 3
                continue;
154
            }
155
156 6
            $dto = $this->getDtoForModelOrGenerate($qualifiedModel, $data);
157 6
            $type = $this->relationsMap[$relation] ? $dto . '[]' : $dto;
158 6
            $properties += [$method->getName() => [$type]];
159
        }
160
161 9
        return $properties;
162
    }
163
164
    /**
165
     * Retrieve the body of the given method
166
     *
167
     * @param ReflectionMethod $method
168
     * @return string
169
     */
170 9
    protected function getMethodBody(ReflectionMethod $method): string
171
    {
172 9
        $file = $this->getFile($method->getFileName());
173 9
        $offset = $method->getStartLine();
174 9
        $length = $method->getEndLine() - $offset;
175
176 9
        return implode('', array_slice($file, $offset, $length));
177
    }
178
179
    /**
180
     * Retrieve the given file as an array
181
     *
182
     * @param string $filename
183
     * @return array
184
     */
185 9
    protected function getFile(string $filename): array
186
    {
187 9
        if ($this->cachedFile) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->cachedFile of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
188 9
            return $this->cachedFile;
189
        }
190
191 9
        return $this->cachedFile = file($filename);
0 ignored issues
show
Documentation Bug introduced by
It seems like file($filename) can also be of type false. However, the property $cachedFile is declared as type array. 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...
192
    }
193
194
    /**
195
     * Retrieve the fully qualified class name of the given model
196
     *
197
     * @param string $model
198
     * @param ReflectionClass $reflection
199
     * @return string|null
200
     */
201 9
    protected function qualifyModel(string $model, ReflectionClass $reflection): ?string
202
    {
203 9
        if (class_exists($model)) {
204 3
            return $model;
205
        }
206
207 9
        $useStatements = $this->getUseStatements($reflection);
208
209 9
        if (isset($useStatements[$model])) {
210 3
            return $useStatements[$model];
211
        }
212
213 9
        return class_exists($class = $reflection->getNamespaceName() . "\\{$model}") ? $class : null;
214
    }
215
216
    /**
217
     * Retrieve the use statements of the given class
218
     *
219
     * @param ReflectionClass $reflection
220
     * @return array
221
     */
222 9
    protected function getUseStatements(ReflectionClass $reflection): array
223
    {
224 9
        $class = $reflection->getName();
225
226 9
        if ($useStatements = $this->manifest->getUseStatements($class)) {
227 6
            return $useStatements;
228
        }
229
230 9
        $file = $this->getFile($reflection->getFileName());
231
232 9
        foreach ($file as $line) {
233 9
            if (strpos($line, 'class') === 0) {
234 9
                break;
235 9
            } elseif (strpos($line, 'use') === 0) {
236 9
                preg_match_all('/([\w\\\_]+)(?:\s+as\s+([\w_]+))?;/i', $line, $matches, PREG_SET_ORDER);
237
238 9
                foreach ($matches as $match) {
239 9
                    $segments = explode('\\', $match[1]);
240 9
                    $name = $match[2] ?? end($segments);
241 9
                    $this->manifest->addUseStatement($class, $name, $match[1]);
242
                }
243
            }
244
        }
245
246 9
        return $this->manifest->save()->getUseStatements($class);
247
    }
248
249
    /**
250
     * Retrieve the DTO class name for the given model
251
     *
252
     * @param string $model
253
     * @param DtoGenerationData $data
254
     * @return string
255
     */
256 6
    protected function getDtoForModelOrGenerate(string $model, DtoGenerationData $data): string
257
    {
258 6
        if ($dto = $this->manifest->getDto($model)) {
259 6
            return $dto;
260
        }
261
262 6
        $dto = $this->qualifier->qualify($model);
263
264 6
        if ($this->shouldGenerateNestedDto($dto, $data->forced)) {
265 6
            Artisan::call('make:dto', [
266 6
                'name' => str_replace('\\', '/', $model),
267 6
                '--force' => $data->forced,
268 6
            ], $data->output);
269
270 6
            $this->manifest->finishGeneratingDto()->save();
271
        }
272
273 6
        return $this->manifest->addDto($model, $dto)->save()->getDto($model);
274
    }
275
276
    /**
277
     * Determine whether the given nested DTO should be generated
278
     *
279
     * @param string $dto
280
     * @param bool $forced
281
     * @return bool
282
     */
283 6
    protected function shouldGenerateNestedDto(string $dto, bool $forced): bool
284
    {
285 6
        if ($this->manifest->isStartingDto($dto) || $this->manifest->generating($dto)) {
286 6
            return false;
287
        }
288
289 6
        return $forced || !class_exists($dto);
290
    }
291
}
292