Test Setup Failed
Pull Request — master (#46)
by Alex
13:47
created

MetadataTrait::getTable()

Size

Total Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 1
ccs 0
cts 0
cp 0
nc 1
1
<?php
2
namespace AlgoWeb\PODataLaravel\Models;
3
4
use Illuminate\Database\Eloquent\Relations\BelongsTo;
5
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
6
use Illuminate\Database\Eloquent\Relations\MorphMany;
7
use Illuminate\Database\Eloquent\Relations\MorphOne;
8
use Illuminate\Database\Eloquent\Relations\MorphToMany;
9
use Illuminate\Support\Facades\App as App;
10
use Illuminate\Database\Eloquent\Relations\Relation;
11
use POData\Providers\Metadata\ResourceStreamInfo;
12
use POData\Providers\Metadata\Type\EdmPrimitiveType;
13
use Illuminate\Database\Eloquent\Model;
14
15
trait MetadataTrait
16
{
17
    /*
18
     * Array to record mapping between doctrine types and OData types
19
     */
20
    protected $mapping = [
21
        'integer' => EdmPrimitiveType::INT32,
22
        'string' => EdmPrimitiveType::STRING,
23
        'datetime' => EdmPrimitiveType::DATETIME,
24
        'float' => EdmPrimitiveType::SINGLE,
25
        'decimal' => EdmPrimitiveType::DECIMAL,
26
        'text' => EdmPrimitiveType::STRING,
27
        'boolean' => EdmPrimitiveType::BOOLEAN,
28 3
        'blob' => "stream"
29
    ];
30 3
31
    /*
32
     * Retrieve and assemble this model's metadata for OData packaging
33 2
     */
34 2
    public function metadata()
35
    {
36 2
        assert($this instanceof Model, get_class($this));
37
38 2
        // Break these out separately to enable separate reuse
39 1
        $connect = $this->getConnection();
40
        $builder = $connect->getSchemaBuilder();
41
42 1
        $table = $this->getTable();
43 1
44 1
        if (!$builder->hasTable($table)) {
45
            return [];
46 1
        }
47
48 1
        $columns = $builder->getColumnListing($table);
49 1
        $mask = $this->metadataMask();
50 1
        $columns = array_intersect($columns, $mask);
51
52 1
        $tableData = [];
53 1
54 1
        $rawFoo = $connect->getDoctrineSchemaManager()->listTableColumns($table);
55
        $foo = [];
56 1
        $getters = $this->collectGetters();
57
58 1
        foreach ($rawFoo as $key => $val) {
59 1
            // Work around glitch in Doctrine when reading from MariaDB which added ` characters to root key value
60 1
            $key = trim($key, '`');
61 1
            $foo[$key] = $val;
62 1
        }
63 1
64 1
        foreach ($columns as $column) {
65
            // Doctrine schema manager returns columns with lowercased names
66 1
            $rawColumn = $foo[strtolower($column)];
67
            $nullable = !($rawColumn->getNotNull());
68
            $fillable = in_array($column, $this->getFillable());
69
            $rawType = $rawColumn->getType();
70
            $type = $rawType->getName();
71
            $tableData[$column] = ['type' => $type, 'nullable' => $nullable, 'fillable' => $fillable];
72
        }
73 4
74
        foreach ($getters as $get) {
75 4
            $tableData[$get] = ['type' => 'text', 'nullable' => false, 'fillable' => false];
76
        }
77 4
78 4
        return $tableData;
79 4
    }
80 2
81 4
    /*
82 1
     * Return the set of fields that are permitted to be in metadata
83 1
     * - following same visible-trumps-hidden guideline as Laravel
84
     */
85 4
    public function metadataMask()
86
    {
87
        $attribs = array_keys($this->getAllAttributes());
88
89
        $visible = $this->getVisible();
90
        $hidden = $this->getHidden();
91 5
        if (0 < count($visible)) {
92
            assert(!empty($visible));
93 5
            $attribs = array_intersect($visible, $attribs);
94 5
        } elseif (0 < count($hidden)) {
95 1
            assert(!empty($hidden));
96
            $attribs = array_diff($attribs, $hidden);
97
        }
98 4
99
        return $attribs;
100 4
    }
101
102 4
    /*
103 4
     * Get the endpoint name being exposed
104 4
     *
105 4
     */
106 4
    public function getEndpointName()
107 4
    {
108
        $endpoint = isset($this->endpoint) ? $this->endpoint : null;
109 4
110 1
        if (!isset($endpoint)) {
111 1
            $bitter = get_class();
112 1
            $name = substr($bitter, strrpos($bitter, '\\')+1);
113 1
            return strtolower($name);
114
        }
115 4
        return strtolower($endpoint);
116 4
    }
117
118 4
    /*
119
     * Assemble this model's OData metadata as xml schema
120
     */
121
    public function getXmlSchema($MetaNamespace = "Data")
122
    {
123
        $raw = $this->metadata();
124
        if ([] == $raw) {
125
            return null;
126
        }
127
128
        $metadata = App::make('metadata');
129
130
        $rf = new \ReflectionClass(get_class($this));
131
        $complex = $metadata->addEntityType($rf, $rf->getShortName(), $MetaNamespace);
132
        $keyName = $this->getKeyName();
133
        if (null != $keyName) {
134
            $metadata->addKeyProperty($complex, $keyName, $this->mapping[$raw[$keyName]['type']]);
135
        }
136
137
        foreach ($raw as $key => $secret) {
138
            if ($key == $keyName) {
139
                continue;
140
            }
141
            if ($secret['type'] == "blob") {
142
                $complex->setMediaLinkEntry(true);
143
                $streamInfo = new ResourceStreamInfo($key);
144
                assert($complex->isMediaLinkEntry());
145
                $complex->addNamedStream($streamInfo);
146
                continue;
147
            }
148
            $metadata->addPrimitiveProperty($complex, $key, $this->mapping[$secret['type']]); // tag as isBag?
149
        }
150
151
        return $complex;
152
    }
153
154
    public function hookUpRelationships($entityTypes, $resourceSets)
155
    {
156
        assert(is_array($entityTypes) && is_array($resourceSets), "Both entityTypes and resourceSets must be arrays");
157
        $metadata = App::make('metadata');
158
        $rel = $this->getRelationshipsFromMethods();
159
        $thisClass = get_class($this);
160
        $thisInTypes = array_key_exists($thisClass, $entityTypes);
161
        $thisInSets = array_key_exists($thisClass, $resourceSets);
162
163
        if (!($thisInSets && $thisInTypes)) {
164
            return $rel;
165
        }
166
167
        $resourceType = $entityTypes[$thisClass];
168
        // if $r is in $combined keys, then its in keyspaces of both $entityTypes and $resourceSets
169
        $combinedKeys = array_intersect(array_keys($entityTypes), array_keys($resourceSets));
170 View Code Duplication
        foreach ($rel["HasOne"] as $n => $r) {
171
            $r = trim($r, '\\');
172
            if (in_array($r, $combinedKeys)) {
173
                $targResourceSet = $resourceSets[$r];
174
                $metadata->addResourceReferenceProperty($resourceType, $n, $targResourceSet);
175 3
            }
176
        }
177 3 View Code Duplication
        foreach ($rel["HasMany"] as $n => $r) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
178
            $r = trim($r, '\\');
179 3
            if (in_array($r, $combinedKeys)) {
180 3
                $targResourceSet = $resourceSets[$r];
181 3
                $metadata->addResourceSetReferenceProperty($resourceType, $n, $targResourceSet);
182 3
            }
183 3
        }
184 3
        return $rel;
185 3
    }
186 3
187 3
    public function getRelationships()
188 3
    {
189
        $hooks = [];
190 3
191
        $rels = $this->getRelationshipsFromMethods(true);
192 3
193 3
        foreach ($rels['UnknownPolyMorphSide'] as $property => $foo) {
194 3
            $isMany = $foo instanceof MorphToMany;
195 3
            $targ = get_class($foo->getRelated());
196 3
            $mult = $isMany ? '*' : '1';
197 3
198 3
            $keyRaw = $isMany ? $foo->getQualifiedForeignKeyName() : $foo->getForeignKey();
0 ignored issues
show
Bug introduced by
The method getQualifiedForeignKeyName() does not exist on Illuminate\Database\Eloquent\Relations\MorphToMany. Did you maybe mean getQualifiedForeignPivotKeyName()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
199 3
            $keySegments = explode('.', $keyRaw);
200 3
            $keyName = $keySegments[count($keySegments) - 1];
201 3
            $localRaw = $isMany ? $foo->getQualifiedRelatedKeyName() : $foo->getQualifiedParentKeyName();
0 ignored issues
show
Bug introduced by
The method getQualifiedRelatedKeyName() does not exist on Illuminate\Database\Eloquent\Relations\MorphToMany. Did you maybe mean getQualifiedRelatedPivotKeyName()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
202
            $localSegments = explode('.', $localRaw);
203 3
            $localName = $localSegments[count($localSegments) - 1];
204 3
205 3
            $first = $keyName;
206 3
            $last = $localName;
207 3
            if (!isset($hooks[$first])) {
208 3
                $hooks[$first] = [];
209 3
            }
210 3
            $hooks[$first][$targ] = [
211
                'property' => $property,
212 3
                'local' => $last,
213 3
                'multiplicity' => $mult
214 3
            ];
215
        }
216 3
217 3
        foreach ($rels['KnownPolyMorphSide'] as $property => $foo) {
218 3
            $isMany = $foo instanceof MorphToMany;
219 3
            $targ = get_class($foo->getRelated());
220 3
            $mult = $isMany ? '*' : $foo instanceof MorphMany ? '*' : '1';
221
            $mult = $foo instanceof MorphOne ? '0..1' : $mult;
222 1
223 3
            $keyRaw = $isMany ? $foo->getQualifiedForeignKeyName() : $foo->getForeignKeyName();
0 ignored issues
show
Bug introduced by
The method getQualifiedForeignKeyName() does not exist on Illuminate\Database\Eloquent\Relations\MorphToMany. Did you maybe mean getQualifiedForeignPivotKeyName()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
224
            $keySegments = explode('.', $keyRaw);
225 1
            $keyName = $keySegments[count($keySegments) - 1];
226
            $localRaw = $isMany ? $foo->getQualifiedRelatedKeyName() : $foo->getQualifiedParentKeyName();
0 ignored issues
show
Bug introduced by
The method getQualifiedRelatedKeyName() does not exist on Illuminate\Database\Eloquent\Relations\MorphToMany. Did you maybe mean getQualifiedRelatedPivotKeyName()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
227 1
            $localSegments = explode('.', $localRaw);
228
            $localName = $localSegments[count($localSegments) - 1];
229 1
            $first = $isMany ? $keyName : $localName;
230
            $last = $isMany ? $localName : $keyName;
231 3
            if (!isset($hooks[$first])) {
232 2
                $hooks[$first] = [];
233 2
            }
234 3
            $hooks[$first][$targ] = [
235 3
                'property' => $property,
236 3
                'local' => $last,
237 3
                'multiplicity' => $mult
238 3
            ];
239 3
        }
240 3
241
        foreach ($rels['HasOne'] as $property => $foo) {
242
            if ($foo instanceof MorphOne) {
243
                continue;
244
            }
245
            $isBelong = $foo instanceof BelongsTo;
246
            $mult = $isBelong ? '1' : '0..1';
247
            $targ = get_class($foo->getRelated());
248
            $keyName = $isBelong ? $foo->getForeignKey() : $foo->getForeignKeyName();
249
            $localRaw = $isBelong ? $foo->getOwnerKey() : $foo->getQualifiedParentKeyName();
250
            $localSegments = explode('.', $localRaw);
251
            $localName = $localSegments[count($localSegments) - 1];
252
            $first = $isBelong ? $localName : $keyName;
253
            $last = $isBelong ? $keyName : $localName;
254
            if (!isset($hooks[$first])) {
255
                $hooks[$first] = [];
256
            }
257
            $hooks[$first][$targ] = [
258
                'property' => $property,
259
                'local' => $last,
260
                'multiplicity' => $mult
261
            ];
262
        }
263
        foreach ($rels['HasMany'] as $property => $foo) {
264
            if ($foo instanceof MorphMany || $foo instanceof MorphToMany) {
265
                continue;
266
            }
267
            $isBelong = $foo instanceof BelongsToMany;
268
            $mult = '*';
269
            $targ = get_class($foo->getRelated());
270
            $keyRaw = $isBelong ? $foo->getQualifiedForeignKeyName() : $foo->getForeignKeyName();
0 ignored issues
show
Bug introduced by
The method getQualifiedForeignKeyName() does not exist on Illuminate\Database\Eloq...Relations\BelongsToMany. Did you maybe mean getQualifiedForeignPivotKeyName()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
271
            $keySegments = explode('.', $keyRaw);
272
            $keyName = $keySegments[count($keySegments) - 1];
273
            $localRaw = $isBelong ? $foo->getQualifiedRelatedKeyName() : $foo->getQualifiedParentKeyName();
0 ignored issues
show
Bug introduced by
The method getQualifiedRelatedKeyName() does not exist on Illuminate\Database\Eloq...Relations\BelongsToMany. Did you maybe mean getQualifiedRelatedPivotKeyName()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
274
            $localSegments = explode('.', $localRaw);
275
            $localName = $localSegments[count($localSegments) - 1];
276
            if (!isset($hooks[$keyName])) {
277
                $hooks[$keyName] = [];
278
            }
279
            $hooks[$keyName][$targ] = [
280
                'property' => $property,
281
                'local' => $localName,
282
                'multiplicity' => $mult
283
            ];
284
        }
285
286
        return $hooks;
287
    }
288
289
    protected function getAllAttributes()
290
    {
291
        // Adapted from http://stackoverflow.com/a/33514981
292
        // $columns = $this->getFillable();
293
        // Another option is to get all columns for the table like so:
294
        $builder = $this->getConnection()->getSchemaBuilder();
295
        $columns = $builder->getColumnListing($this->getTable());
296
        // but it's safer to just get the fillable fields
297
298
        $attributes = $this->getAttributes();
299
300
        foreach ($columns as $column) {
301
            if (!array_key_exists($column, $attributes)) {
302
                $attributes[$column] = null;
303
            }
304
        }
305
306
        $methods = $this->collectGetters();
307
308
        foreach ($methods as $method) {
309
            $attributes[$method] = null;
310
        }
311
312
        return $attributes;
313
    }
314
315
    protected function getRelationshipsFromMethods($biDir = false)
316
    {
317
        $model = $this;
318
        $relationships = array(
319
            "HasOne" => array(),
320
            "UnknownPolyMorphSide"=>array(),
321
            "HasMany"=>array(),
322
            "KnownPolyMorphSide"=>array()
323
        );
324
        $methods = get_class_methods($model);
325
        if (!empty($methods)) {
326
            foreach ($methods as $method) {
327
                if (!method_exists('Illuminate\Database\Eloquent\Model', $method)
328
                ) {
329
                    //Use reflection to inspect the code, based on Illuminate/Support/SerializableClosure.php
330
                    $reflection = new \ReflectionMethod($model, $method);
331
332
                    $file = new \SplFileObject($reflection->getFileName());
333
                    $file->seek($reflection->getStartLine()-1);
334
                    $code = '';
335
                    while ($file->key() < $reflection->getEndLine()) {
336
                        $code .= $file->current();
337
                        $file->next();
338
                    }
339
340
                    $code = trim(preg_replace('/\s\s+/', '', $code));
341
                    assert(false !== stripos($code, 'function'), 'Function definition must have keyword \'function\'');
342
                    $begin = strpos($code, 'function(');
343
                    $code = substr($code, $begin, strrpos($code, '}')-$begin+1);
344
                    $lastCode = $code[strlen($code)-1];
345
                    assert("}" == $lastCode, "Final character of function definition must be closing brace");
346
                    foreach (array(
347
                                'hasMany',
348
                                'hasManyThrough',
349
                                'belongsToMany',
350
                                'hasOne',
351
                                'belongsTo',
352
                                'morphOne',
353
                                'morphTo',
354
                                'morphMany',
355
                                'morphToMany',
356
                                'morphedByMany'
357
                                ) as $relation) {
358
                        $search = '$this->'.$relation.'(';
359
                        if ($pos = stripos($code, $search)) {
360
                            //Resolve the relation's model to a Relation object.
361
                            $relationObj = $model->$method();
362
                            if ($relationObj instanceof Relation) {
363
                                $relatedModel = '\\'.get_class($relationObj->getRelated());
364
                                $relations = [
365
                                    'hasManyThrough',
366
                                    'belongsToMany',
367
                                    'hasMany',
368
                                    'morphMany',
369
                                    'morphToMany',
370
                                    'morphedByMany'
371
                                ];
372
                                if (in_array($relation, $relations)) {
373
                                    //Collection or array of models (because Collection is Arrayable)
374
                                    $relationships["HasMany"][$method] = $biDir ? $relationObj : $relatedModel;
375
                                } elseif ($relation === "morphTo") {
376
                                    // Model isn't specified because relation is polymorphic
377
                                    $relationships["UnknownPolyMorphSide"][$method] =
378
                                        $biDir ? $relationObj : '\Illuminate\Database\Eloquent\Model|\Eloquent';
379
                                } else {
380
                                    //Single model is returned
381
                                    $relationships["HasOne"][$method] = $biDir ? $relationObj : $relatedModel;
382
                                }
383
                                if (in_array($relation, ["morphMany", "morphOne", "morphedByMany"])) {
384
                                    $relationships["KnownPolyMorphSide"][$method] =
385
                                        $biDir ? $relationObj : $relatedModel;
386
                                }
387
                                if (in_array($relation, ["morphToMany"])) {
388
                                    $relationships["UnknownPolyMorphSide"][$method] =
389
                                        $biDir ? $relationObj : $relatedModel;
390
                                }
391
                            }
392
                        }
393
                    }
394
                }
395
            }
396
        }
397
        return $relationships;
398
    }
399
400
    /**
401
     * Get the visible attributes for the model.
402
     *
403
     * @return array
404
     */
405
    public abstract function getVisible();
406
407
    /**
408
     * Get the hidden attributes for the model.
409
     *
410
     * @return array
411
     */
412
    public abstract function getHidden();
413
414
    /**
415
     * Get the primary key for the model.
416
     *
417
     * @return string
418
     */
419
    public abstract function getKeyName();
420
421
    /**
422
     * Get the current connection name for the model.
423
     *
424
     * @return string
425
     */
426
    public abstract function getConnectionName();
427
428
    /**
429
     * Get the database connection for the model.
430
     *
431
     * @return \Illuminate\Database\Connection
432
     */
433
    public abstract function getConnection();
434
435
    /**
436
     * Get all of the current attributes on the model.
437
     *
438
     * @return array
439
     */
440
    public abstract function getAttributes();
441
442
    /**
443
     * Get the table associated with the model.
444
     *
445
     * @return string
446
     */
447
    public abstract function getTable();
448
449
    /**
450
     * Get the fillable attributes for the model.
451
     *
452
     * @return array
453
     */
454
    public abstract function getFillable();
455
456
    /**
457
     * Dig up all defined getters on the model
458
     *
459
     * @return array
460
     */
461
    protected function collectGetters()
462
    {
463
        $getterz = [];
464
        $methods = get_class_methods($this);
465
        foreach ($methods as $method) {
466
            if (starts_with($method, 'get') && ends_with($method, 'Attribute') && 'getAttribute' != $method) {
467
                $getterz[] = $method;
468
            }
469
        }
470
        $methods = [];
471
472
        foreach ($getterz as $getter) {
473
            $residual = substr($getter, 3);
474
            $residual = substr($residual, 0, -9);
475
            $methods[] = $residual;
476
        }
477
        return $methods;
478
    }
479
}
480