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

MetadataControllerProvider::getIsCaching()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
ccs 0
cts 0
cp 0
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 2
1
<?php
2
3
namespace AlgoWeb\PODataLaravel\Providers;
4
5
use AlgoWeb\PODataLaravel\Controllers\MetadataControllerTrait;
6
use Illuminate\Support\ServiceProvider;
7
use Illuminate\Support\Facades\Cache;
8
use AlgoWeb\PODataLaravel\Controllers\MetadataControllerContainer;
9
use Illuminate\Support\Facades\App;
10
11
class MetadataControllerProvider extends ServiceProvider
12
{
13
    /**
14
     * Bootstrap the application services.  Post-boot.
15
     *
16 68
     * @return void
17
     */
18 68
    public function boot()
19
    {
20 68
        $isCaching = true === $this->getIsCaching();
21
22
        if ($isCaching) {
23
            $hasCache = Cache::has('metadataControllers');
24
            if ($hasCache) {
25
                $meta = Cache::get('metadataControllers');
26 68
                App::instance('metadataControllers', $meta);
27
                return;
28 68
            }
29 68
        }
30 68
31 68
        $meta = App::make('metadataControllers');
32 68
33 68
        $Classes = $this->getClassMap();
34 68
        $ends = $this->getCandidateControllers($Classes);
35
36 68
        // now process each class that uses the metadata controller trait and stick results in $metamix
37 68
        $metamix = [];
38 68
        $map = null;
0 ignored issues
show
Unused Code introduced by
$map 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...
39 68
        foreach ($ends as $end) {
40
            $map = $end->getMappings();
41 68
            // verify uniqueness - must be exactly one mapping for model-verb combo - different verb mappings for
42 68
            // a model can glom onto different controllers
43 68
            foreach ($map as $key => $lock) {
44 68
                if (!array_key_exists($key, $metamix)) {
45 67
                    // if we haven't yet got a mapping for this model, grab it holus-bolus
46 67
                    $metamix[$key] = $lock;
47 68
                    continue;
48
                }
49
                // if we do, make sure we aren't re-adding mappings for any of the CRUD verbs
50 68
                foreach ($lock as $barrel => $roll) {
51
                    assert(
52
                        !array_key_exists($barrel, $metamix[$key]),
53 68
                        'Mapping already defined for model '.$key.' and CRUD verb '.$barrel
54 68
                    );
55 67
                    $metamix[$key][$barrel] = $roll;
56
                }
57
            }
58 67
        }
59 67
60
        $meta->setMetadata($metamix);
61 67
62 67 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...
63
            if (!$hasCache) {
0 ignored issues
show
Bug introduced by
The variable $hasCache does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
64
                $cacheTime = env('APP_METADATA_CACHE_DURATION', null);
65
                $cacheTime = !is_numeric($cacheTime) ? 10 : abs($cacheTime);
66
                Cache::put('metadataControllers', $meta, $cacheTime);
67
            }
68
        } else {
69
            Cache::forget('metadataControllers');
70
        }
71
72
    }
73 67
74 68
    /**
75
     * Register the application services.  Boot-time only.
76 68
     *
77
     * @return void
78 68
     */
79
    public function register()
80
    {
81
        $this->app->singleton('metadataControllers', function ($app) {
1 ignored issue
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...
82
            return new MetadataControllerContainer();
83
        });
84
    }
85
86
    /**
87 68
     * @param $Classes
88 68
     * @return array
89 68
     * @throws \Exception
90 68
     */
91
    protected function getCandidateControllers($Classes)
92
    {
93
        $ends = [];
94
        $startName = defined('PODATA_LARAVEL_APP_ROOT_NAMESPACE') ? PODATA_LARAVEL_APP_ROOT_NAMESPACE : "App";
95
        foreach ($Classes as $name) {
96
            // not in app namespace, keep moving
97
            if (!\Illuminate\Support\Str::startsWith($name, $startName)) {
98
                continue;
99
            }
100
            // if class doesn't exist (for whatever reason), skip it now rather than muck about later
101
            if (!class_exists($name)) {
102
                continue;
103
            }
104
            try {
105
                if (in_array(MetadataControllerTrait::class, class_uses($name, false))) {
106
                    $ends[] = App::make($name);
107
                }
108
            } catch (\Exception $e) {
109
                if (!App::runningInConsole()) {
110
                    throw $e;
111
                }
112
                // Squash exceptions thrown here when running from CLI so app can continue booting
113
            }
114
        }
115
        return $ends;
116
    }
117
118
    /**
119
     * @param $classMap
120
     * @return array
121
     */
122
    protected function getClassMap()
123
    {
124
        $classes = get_declared_classes();
125
        $AutoClass = null;
126
        foreach ($classes as $class) {
127
            if (\Illuminate\Support\Str::startsWith($class, "Composer\\Autoload\\ComposerStaticInit")) {
128
                $AutoClass = $class;
129
            }
130
        }
131
132
        $Classes = $AutoClass::$classMap;
133
        return array_keys($Classes);
134
    }
135
136
    /**
137
     * @return mixed
138
     */
139
    protected function getIsCaching()
140
    {
141
        return true === env('APP_METADATA_CACHING', false);
142
    }
143
}
144