Passed
Pull Request — master (#221)
by Alex
05:59
created

MetadataTrait::getEndpointName()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
eloc 6
c 0
b 0
f 0
dl 0
loc 10
rs 10
ccs 0
cts 5
cp 0
cc 3
nc 4
nop 0
crap 12
1
<?php
2
namespace AlgoWeb\PODataLaravel\Models;
3
4
use AlgoWeb\PODataLaravel\Models\ObjectMap\Entities\Associations\AssociationStubFactory;
5
use AlgoWeb\PODataLaravel\Models\ObjectMap\Entities\Associations\AssociationStubMonomorphic;
6
use AlgoWeb\PODataLaravel\Models\ObjectMap\Entities\Associations\AssociationStubPolymorphic;
7
use AlgoWeb\PODataLaravel\Models\ObjectMap\Entities\Associations\AssociationStubRelationType;
8
use AlgoWeb\PODataLaravel\Models\ObjectMap\Entities\EntityField;
9
use AlgoWeb\PODataLaravel\Models\ObjectMap\Entities\EntityFieldPrimitiveType;
10
use AlgoWeb\PODataLaravel\Models\ObjectMap\Entities\EntityFieldType;
11
use AlgoWeb\PODataLaravel\Models\ObjectMap\Entities\EntityGubbins;
12
use Illuminate\Database\Eloquent\Model;
13
use Illuminate\Database\Eloquent\Relations\BelongsTo;
14
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
15
use Illuminate\Database\Eloquent\Relations\HasManyThrough;
16
use Illuminate\Database\Eloquent\Relations\MorphMany;
17
use Illuminate\Database\Eloquent\Relations\MorphOne;
18
use Illuminate\Database\Eloquent\Relations\MorphToMany;
19
use Illuminate\Database\Eloquent\Relations\Relation;
20
use Illuminate\Support\Facades\App;
21
use Mockery\Mock;
22
use POData\Common\InvalidOperationException;
23
use POData\Providers\Metadata\Type\IType;
24
25
/**
26
 * Trait MetadataTrait
27
 * @package AlgoWeb\PODataLaravel\Models
28 3
 * @mixin Model
29
 */
30 3
trait MetadataTrait
31
{
32
    use MetadataRelationsTrait;
33 2
34 2
    protected $loadEagerRelations = [];
35
    protected static $tableColumns = [];
36 2
    protected static $tableColumnsDoctrine = [];
37
    protected static $tableData = [];
38 2
    protected static $dontCastTypes = ['object', 'array', 'collection', 'int'];
39 1
40
    /**
41
     * Retrieve and assemble this model's metadata for OData packaging.
42 1
     * @throws InvalidOperationException
43 1
     * @throws \Doctrine\DBAL\DBALException
44 1
     * @return array
45
     */
46 1
    public function metadata()
47
    {
48 1
        if (!$this instanceof Model) {
49 1
            throw new InvalidOperationException(get_class($this));
50 1
        }
51
52 1
        if (0 !== count(self::$tableData)) {
53 1
            return self::$tableData;
54 1
        } elseif (isset($this->odata)) {
55
            return self::$tableData = $this->odata;
56 1
        }
57
58 1
        // Break these out separately to enable separate reuse
59 1
        $connect = $this->getConnection();
60 1
        $builder = $connect->getSchemaBuilder();
61 1
62 1
        $table = $this->getTable();
63 1
64 1
        if (!$builder->hasTable($table)) {
65
            return self::$tableData = [];
66 1
        }
67
68
        /** @var array $columns */
69
        $columns = $this->getTableColumns();
70
        /** @var array $mask */
71
        $mask = $this->metadataMask();
72
        $columns = array_intersect($columns, $mask);
73 4
74
        $tableData = [];
75 4
76
        $rawFoo = $this->getTableDoctrineColumns();
77 4
        $foo = [];
78 4
        /** @var array $getters */
79 4
        $getters = $this->collectGetters();
80 2
        $getters = array_intersect($getters, $mask);
81 4
        $casts = $this->retrieveCasts();
82 1
83 1
        foreach ($rawFoo as $key => $val) {
84
            // Work around glitch in Doctrine when reading from MariaDB which added ` characters to root key value
85 4
            $key = trim($key, '`"');
86
            $foo[$key] = $val;
87
        }
88
89
        foreach ($columns as $column) {
90
            // Doctrine schema manager returns columns with lowercased names
91 5
            $rawColumn = $foo[strtolower($column)];
92
            /** @var IType $rawType */
93 5
            $rawType = $rawColumn->getType();
94 5
            $type = $rawType->getName();
95 1
            $default = $this->$column;
96
            $tableData[$column] = ['type' => $type,
97
                'nullable' => !($rawColumn->getNotNull()),
98 4
                'fillable' => in_array($column, $this->getFillable()),
99
                'default' => $default
100 4
            ];
101
        }
102 4
103 4
        foreach ($getters as $get) {
104 4
            if (isset($tableData[$get])) {
105 4
                continue;
106 4
            }
107 4
            $default = $this->$get;
108
            $tableData[$get] = ['type' => 'text', 'nullable' => true, 'fillable' => false, 'default' => $default];
109 4
        }
110 1
111 1
        // now, after everything's gathered up, apply Eloquent model's $cast array
112 1
        foreach ($casts as $key => $type) {
113 1
            $type = strtolower($type);
114
            if (array_key_exists($key, $tableData) && !in_array($type, self::$dontCastTypes)) {
115 4
                $tableData[$key]['type'] = $type;
116 4
            }
117
        }
118 4
119
        self::$tableData = $tableData;
120
        return $tableData;
121
    }
122
123
    /**
124
     * Return the set of fields that are permitted to be in metadata
125
     * - following same visible-trumps-hidden guideline as Laravel.
126
     *
127
     * @return array
128
     */
129
    public function metadataMask()
130
    {
131
        $attribs = array_keys($this->getAllAttributes());
132
133
        $visible = $this->getVisible();
134
        $hidden = $this->getHidden();
135
        if (0 < count($visible)) {
136
            $attribs = array_intersect($visible, $attribs);
137
        } elseif (0 < count($hidden)) {
138
            $attribs = array_diff($attribs, $hidden);
139
        }
140
141
        return $attribs;
142
    }
143
144
    /*
145
     * Get the endpoint name being exposed
146
     *
147
     * @return null|string;
148
     */
149
    public function getEndpointName()
150
    {
151
        $endpoint = isset($this->endpoint) ? $this->endpoint : null;
152
153
        if (!isset($endpoint)) {
154
            $bitter = get_class($this);
155
            $name = substr($bitter, strrpos($bitter, '\\')+1);
156
            return ($name);
157
        }
158
        return ($endpoint);
159
    }
160
161
    protected function getAllAttributes()
162
    {
163
        // Adapted from http://stackoverflow.com/a/33514981
164
        // $columns = $this->getFillable();
165
        // Another option is to get all columns for the table like so:
166
        $columns = $this->getTableColumns();
167
        // but it's safer to just get the fillable fields
168
169
        $attributes = $this->getAttributes();
170
171
        foreach ($columns as $column) {
172
            if (!array_key_exists($column, $attributes)) {
173
                $attributes[$column] = null;
174
            }
175 3
        }
176
177 3
        $methods = $this->collectGetters();
178
179 3
        foreach ($methods as $method) {
180 3
            $attributes[$method] = null;
181 3
        }
182 3
183 3
        return $attributes;
184 3
    }
185 3
186 3
    /**
187 3
     * Get the visible attributes for the model.
188 3
     *
189
     * @return array
190 3
     */
191
    abstract public function getVisible();
192 3
193 3
    /**
194 3
     * Get the hidden attributes for the model.
195 3
     *
196 3
     * @return array
197 3
     */
198 3
    abstract public function getHidden();
199 3
200 3
    /**
201 3
     * Get the primary key for the model.
202
     *
203 3
     * @return string
204 3
     */
205 3
    abstract public function getKeyName();
206 3
207 3
    /**
208 3
     * Get the current connection name for the model.
209 3
     *
210 3
     * @return string
211
     */
212 3
    abstract public function getConnectionName();
213 3
214 3
    /**
215
     * Get the database connection for the model.
216 3
     *
217 3
     * @return \Illuminate\Database\Connection
218 3
     */
219 3
    abstract public function getConnection();
220 3
221
    /**
222 1
     * Get all of the current attributes on the model.
223 3
     *
224
     * @return array
225 1
     */
226
    abstract public function getAttributes();
227 1
228
    /**
229 1
     * Get the table associated with the model.
230
     *
231 3
     * @return string
232 2
     */
233 2
    abstract public function getTable();
234 3
235 3
    /**
236 3
     * Get the fillable attributes for the model.
237 3
     *
238 3
     * @return array
239 3
     */
240 3
    abstract public function getFillable();
241
242
    /**
243
     * Dig up all defined getters on the model.
244
     *
245
     * @return array
246
     */
247
    protected function collectGetters()
248
    {
249
        $getterz = [];
250
        $methods = get_class_methods($this);
251
        foreach ($methods as $method) {
252
            if (12 < strlen($method) && 'get' == substr($method, 0, 3)) {
253
                if ('Attribute' == substr($method, -9)) {
254
                    $getterz[] = $method;
255
                }
256
            }
257
        }
258
        $methods = [];
259
260
        foreach ($getterz as $getter) {
261
            $residual = substr($getter, 3);
262
            $residual = substr(/* @scrutinizer ignore-type */$residual, 0, -9);
263
            $methods[] = $residual;
264
        }
265
        return $methods;
266
    }
267
268
    /**
269
     * Supplemental function to retrieve cast array for Laravel versions that do not supply hasCasts.
270
     *
271
     * @return array
272
     */
273
    public function retrieveCasts()
274
    {
275
        $exists = method_exists($this, 'getCasts');
276
        return $exists ? (array)$this->getCasts() : (array)$this->casts;
277
    }
278
279
    /**
280
     * Return list of relations to be eager-loaded by Laravel query provider.
281
     *
282
     * @return array
283
     */
284
    public function getEagerLoad()
285
    {
286
        return $this->loadEagerRelations;
287
    }
288
289
    /**
290
     * Set list of relations to be eager-loaded.
291
     *
292
     * @param array $relations
293
     */
294
    public function setEagerLoad(array $relations)
295
    {
296
        $this->loadEagerRelations = array_map('strval', $relations);
297
    }
298
299
    /**
300
     * Extract entity gubbins detail for later downstream use.
301
     *
302
     * @throws InvalidOperationException
303
     * @throws \ReflectionException
304
     * @throws \Doctrine\DBAL\DBALException
305
     * @throws \Exception
306
     * @return EntityGubbins
307
     */
308
    public function extractGubbins()
309
    {
310
        $gubbins = new EntityGubbins();
311
        $gubbins->setName($this->getEndpointName());
312
        $gubbins->setClassName(get_class($this));
313
314
        $lowerNames = [];
315
316
        $fields = $this->metadata();
317
        $entityFields = [];
318
        foreach ($fields as $name => $field) {
319
            if (in_array(strtolower($name), $lowerNames)) {
320
                $msg = 'Property names must be unique, without regard to case';
321
                throw new \Exception($msg);
322
            }
323
            $lowerNames[] = strtolower($name);
324
            $nuField = new EntityField();
325
            $nuField->setName($name);
326
            $nuField->setIsNullable($field['nullable']);
327
            $nuField->setReadOnly(false);
328
            $nuField->setCreateOnly(false);
329
            $nuField->setDefaultValue($field['default']);
330
            $nuField->setIsKeyField($this->getKeyName() == $name);
331
            $nuField->setFieldType(EntityFieldType::PRIMITIVE());
332
            $nuField->setPrimitiveType(new EntityFieldPrimitiveType($field['type']));
333
            $entityFields[$name] = $nuField;
334
        }
335
        $isEmpty = (0 === count($entityFields));
336
        if (!($isEmpty && $this->isRunningInArtisan())) {
337
            $gubbins->setFields($entityFields);
338
        }
339
340
        $rawRels = $this->getRelationships();
341
        $stubs = [];
342
        foreach ($rawRels as $propertyName) {
343
            if (in_array(strtolower($propertyName), $lowerNames)) {
344
                $msg = 'Property names must be unique, without regard to case';
345
                throw new \Exception($msg);
346
            }
347
            $stub = AssociationStubFactory::associationStubFromRelation(/** @scrutinizer ignore-type */$this, $propertyName);
348
            $stubs[$propertyName] = $stub;
349
        }
350
        $gubbins->setStubs($stubs);
351
352
        return $gubbins;
353
    }
354
355
    public function isRunningInArtisan()
356
    {
357
        return App::runningInConsole() && !App::runningUnitTests();
358
    }
359
360
    /**
361
     * Get columns for selected table.
362
     *
363
     * @return array
364
     */
365
    protected function getTableColumns()
366
    {
367
        if (0 === count(self::$tableColumns)) {
368
            $table = $this->getTable();
369
            $connect = $this->getConnection();
370
            $builder = $connect->getSchemaBuilder();
371
            $columns = $builder->getColumnListing($table);
372
373
            self::$tableColumns = (array)$columns;
374
        }
375
        return self::$tableColumns;
376
    }
377
378
    /**
379
     * Get Doctrine columns for selected table.
380
     *
381
     * @throws \Doctrine\DBAL\DBALException
382
     * @return array
383
     */
384
    protected function getTableDoctrineColumns()
385
    {
386
        if (0 === count(self::$tableColumnsDoctrine)) {
387
            $table = $this->getTable();
388
            $connect = $this->getConnection();
389
            $columns = $connect->getDoctrineSchemaManager()->listTableColumns($table);
390
391
            self::$tableColumnsDoctrine = $columns;
392
        }
393
        return self::$tableColumnsDoctrine;
394
    }
395
396
    public function reset()
397
    {
398
        self::$tableData = [];
399
        self::$tableColumnsDoctrine = [];
400
        self::$tableColumns = [];
401
    }
402
}
403