Test Failed
Pull Request — master (#36)
by Alex
11:11
created

MetadataProvider::getCandidateModels()   B

Complexity

Conditions 7
Paths 24

Size

Total Lines 21
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 21
ccs 0
cts 14
cp 0
rs 7.551
cc 7
eloc 14
nc 24
nop 0
crap 56
1
<?php
2
3
namespace AlgoWeb\PODataLaravel\Providers;
4
5
use Illuminate\Support\Facades\App;
6
use Illuminate\Support\ServiceProvider;
7
use Illuminate\Support\Facades\Cache;
8
use POData\Providers\Metadata\IMetadataProvider;
9
use POData\Providers\Metadata\SimpleMetadataProvider;
10
use Illuminate\Support\Facades\Route;
11
use Illuminate\Support\Facades\Schema as Schema;
12
13
class MetadataProvider extends ServiceProvider
14
{
15
    protected static $METANAMESPACE = "Data";
16
17
    /**
18
     * Bootstrap the application services.  Post-boot.
19
     *
20 1
     * @return void
21
     */
22 1
    public function boot()
23
    {
24
        self::$METANAMESPACE = env('ODataMetaNamespace', 'Data');
25 1
        // If we aren't migrated, there's no DB tables to pull metadata _from_, so bail out early
26
        try {
27
            if (!Schema::hasTable('migrations')) {
28 1
                return;
29 1
            }
30
        } catch (\Exception $e) {
31
            return;
32
        }
33
34
        self::setupRoute();
35
        $isCaching = true === $this->checkIsCaching();
36
        $hasCache = Cache::has('metadata');
37
38
        if ($isCaching && $hasCache) {
39
            $meta = Cache::get('metadata');
40
            App::instance('metadata', $meta);
1 ignored issue
show
Bug introduced by
The method instance() does not exist on Illuminate\Support\Facades\App. Did you maybe mean clearResolvedInstance()?

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...
41
            return;
42
        }
43
        $meta = App::make('metadata');
44
45
        $modelNames = $this->getCandidateModels();
46
47
        list($EntityTypes, $ResourceSets, $ends) = $this->getEntityTypesAndResourceSets($meta, $modelNames);
48
49
        // now that endpoints are hooked up, tackle the relationships
50
        // if we'd tried earlier, we'd be guaranteed to try to hook a relation up to null, which would be bad
51
        foreach ($ends as $bitter) {
52
            $fqModelName = $bitter;
53
            $instance = new $fqModelName();
54
            $instance->hookUpRelationships($EntityTypes, $ResourceSets);
55
        }
56 View Code Duplication
        if ($isCaching) {
0 ignored issues
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...
57
            if (!$hasCache) {
58
                $cacheTime = env('APP_METADATA_CACHE_DURATION', null);
59
                $cacheTime = !is_numeric($cacheTime) ? 10 : abs($cacheTime);
60
                Cache::put('metadata', $meta, $cacheTime);
61
            }
62
        } else {
63
            Cache::forget('metadata');
64
        }
65
    }
66
67
    private static function setupRoute()
68
    {
69
        $valueArray = [];
0 ignored issues
show
Unused Code introduced by
$valueArray is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
70
71
        Route::any('odata.svc/{section}', 'AlgoWeb\PODataLaravel\Controllers\ODataController@index')
72
            ->where(['section' => '.*']);
73
        Route::any('odata.svc', 'AlgoWeb\PODataLaravel\Controllers\ODataController@index');
74
    }
75
76
    /**
77
     * Register the application services.  Boot-time only.
78
     *
79
     * @return void
80
     */
81
    public function register()
82
    {
83
        $this->app->singleton('metadata', function ($app) {
0 ignored issues
show
Unused Code introduced by
The parameter $app is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
84
            return new SimpleMetadataProvider('Data', self::$METANAMESPACE);
85
        });
86
    }
87
88
    /**
89
     * @return array
90
     */
91
    protected function getCandidateModels()
92
    {
93
        $classes = get_declared_classes();
94
        $AutoClass = null;
95
        foreach ($classes as $class) {
96
            if (\Illuminate\Support\Str::startsWith($class, "Composer\\Autoload\\ComposerStaticInit")) {
97
                $AutoClass = $class;
98
            }
99
        }
100
        $ends = [];
101
        $Classes = $AutoClass::$classMap;
102
        $startName = defined('PODATA_LARAVEL_APP_ROOT_NAMESPACE') ? PODATA_LARAVEL_APP_ROOT_NAMESPACE : "App";
103
        foreach ($Classes as $name => $file) {
104
            if (\Illuminate\Support\Str::startsWith($name, $startName)) {
105
                if (in_array("AlgoWeb\\PODataLaravel\\Models\\MetadataTrait", class_uses($name))) {
106
                    $ends[] = $name;
107
                }
108
            }
109
        }
110
        return $ends;
111
    }
112
113
    /**
114
     * @param $meta
115
     * @param $ends
116
     * @return array
117
     */
118
    protected function getEntityTypesAndResourceSets($meta, $ends)
119
    {
120
        assert($meta instanceof IMetadataProvider, get_class($meta));
121
        $EntityTypes = [];
122
        $ResourceSets = [];
123
        $begins = [];
124
        $numEnds = count($ends);
125
126
        for ($i = 0; $i < $numEnds; $i++) {
127
            $bitter = $ends[$i];
128
            $fqModelName = $bitter;
129
130
            $instance = App::make($fqModelName);
131
            $name = strtolower($instance->getEndpointName());
132
            $metaSchema = $instance->getXmlSchema();
133
            // if for whatever reason we don't get an XML schema, move on to next entry and drop current one from
134
            // further processing
135
            if (null == $metaSchema) {
136
                continue;
137
            }
138
            $EntityTypes[$fqModelName] = $metaSchema;
139
            $ResourceSets[$fqModelName] = $meta->addResourceSet($name, $metaSchema);
140
            $begins[] = $bitter;
141
        }
142
143
        return array($EntityTypes, $ResourceSets, $begins);
144
    }
145
146
    /**
147
     * @return mixed
148
     */
149
    protected function checkIsCaching()
150
    {
151
        return true === env('APP_METADATA_CACHING', false);
152
    }
153
}
154