Passed
Push — master ( 845957...e458ee )
by Biao
08:48
created

CleanerManager::cleanProviders()   B

Complexity

Conditions 8
Paths 18

Size

Total Lines 28
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 19
nc 18
nop 1
dl 0
loc 28
rs 8.4444
c 0
b 0
f 0
1
<?php
2
3
namespace Hhxsv5\LaravelS\Illuminate;
4
5
use Hhxsv5\LaravelS\Illuminate\Cleaners\CleanerInterface;
6
use Hhxsv5\LaravelS\Illuminate\Cleaners\ConfigCleaner;
7
use Hhxsv5\LaravelS\Illuminate\Cleaners\CookieCleaner;
8
use Hhxsv5\LaravelS\Illuminate\Cleaners\RequestCleaner;
9
use Illuminate\Container\Container;
10
11
class CleanerManager
12
{
13
    /**
14
     * @var Container
15
     */
16
    protected $app;
17
18
    /**
19
     * All cleaners
20
     * @var CleanerInterface[]
21
     */
22
    protected $cleaners = [
23
        ConfigCleaner::class,
24
        CookieCleaner::class,
25
        RequestCleaner::class,
26
    ];
27
28
    /**
29
     * Service providers to be cleaned up
30
     * @var array
31
     */
32
    protected $providers = [];
33
34
    /**
35
     * White list of controllers to be destroyed
36
     * @var array
37
     */
38
    protected $whiteListControllers = [];
39
40
    /**
41
     * @var array
42
     */
43
    protected $config = [];
44
45
    /**
46
     * CleanerManager constructor.
47
     *
48
     * @param Container $app
49
     * @param array $config
50
     */
51
    public function __construct(Container $app, array $config)
52
    {
53
        $this->app = $app;
54
        $this->config = $config;
55
        $this->registerCleaners(isset($this->config['cleaners']) ? $this->config['cleaners'] : []);
56
        $this->registerCleanProviders(isset($config['register_providers']) ? $config['register_providers'] : []);
57
        $this->registerCleanControllerWhiteList(isset($this->config['destroy_controllers']['excluded_list']) ? $this->config['destroy_controllers']['excluded_list'] : []);
58
    }
59
60
    /**
61
     * Register singleton cleaners to application container.
62
     * @param array $cleaners
63
     */
64
    protected function registerCleaners(array $cleaners)
65
    {
66
        $this->cleaners = array_unique(array_merge($cleaners, $this->cleaners));
67
        foreach ($this->cleaners as $cleaner) {
68
            $this->app->singleton($cleaner, function () use ($cleaner) {
69
                if (!isset(class_implements($cleaner)[CleanerInterface::class])) {
70
                    throw new \InvalidArgumentException(sprintf(
71
                            '%s must implement the interface %s',
72
                            $cleaner,
73
                            CleanerInterface::class
74
                        )
75
                    );
76
                }
77
                return new $cleaner();
78
            });
79
        }
80
    }
81
82
    /**
83
     * Clean app after request finished.
84
     *
85
     * @param Container $snapshotApp
86
     */
87
    public function clean($snapshotApp)
88
    {
89
        foreach ($this->cleaners as $cleanerCls) {
90
            /**@var CleanerInterface $cleaner */
91
            $cleaner = $this->app->make($cleanerCls);
0 ignored issues
show
Bug introduced by
$cleanerCls of type Hhxsv5\LaravelS\Illumina...eaners\CleanerInterface is incompatible with the type string expected by parameter $abstract of Illuminate\Container\Container::make(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

91
            $cleaner = $this->app->make(/** @scrutinizer ignore-type */ $cleanerCls);
Loading history...
92
            $cleaner->clean($this->app, $snapshotApp);
93
        }
94
    }
95
96
97
    /**
98
     * Register providers for cleaning.
99
     *
100
     * @param array providers
0 ignored issues
show
Bug introduced by
The type Hhxsv5\LaravelS\Illuminate\providers was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
101
     */
102
    protected function registerCleanProviders(array $providers = [])
103
    {
104
        $this->providers = $providers;
105
    }
106
107
    /**
108
     * Clean Providers.
109
     *
110
     * @param ReflectionApp $reflectionApp
111
     * @throws \ReflectionException
112
     */
113
    public function cleanProviders(ReflectionApp $reflectionApp)
114
    {
115
        $loadedProviders = $reflectionApp->loadedProviders();
116
117
        foreach ($this->providers as $provider) {
118
            if (class_exists($provider, false)) {
119
                if ($this->isLumen()) {
120
                    unset($loadedProviders[get_class(new $provider($this->app))]);
121
                }
122
123
                switch ($reflectionApp->registerMethodParameterCount()) {
124
                    case 1:
125
                        $this->app->register($provider);
0 ignored issues
show
introduced by
The method register() does not exist on Illuminate\Container\Container. Are you sure you never get this type here, but always one of the subclasses? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

125
                        $this->app->/** @scrutinizer ignore-call */ 
126
                                    register($provider);
Loading history...
126
                        break;
127
                    case 2:
128
                        $this->app->register($provider, true);
129
                        break;
130
                    case 3:
131
                        $this->app->register($provider, [], true);
132
                        break;
133
                    default:
134
                        throw new \RuntimeException('The number of parameters of the register method is unknown.');
135
                }
136
            }
137
        }
138
139
        if ($this->isLumen()) {
140
            $reflectionApp->setLoadedProviders($loadedProviders);
141
        }
142
    }
143
144
    /**
145
     * Register white list of controllers for cleaning.
146
     *
147
     * @param array providers
148
     */
149
    protected function registerCleanControllerWhiteList(array $controllers = [])
150
    {
151
        $controllers = array_unique($controllers);
152
        $this->whiteListControllers = array_combine($controllers, $controllers);
0 ignored issues
show
Documentation Bug introduced by
It seems like array_combine($controllers, $controllers) can also be of type false. However, the property $whiteListControllers 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...
153
    }
154
155
    /**
156
     * Clean controllers.
157
     */
158
    public function cleanControllers()
159
    {
160
        if ($this->isLumen()) {
161
            return;
162
        }
163
164
        if (empty($this->config['destroy_controllers']['enable'])) {
165
            return;
166
        }
167
168
        /**@var \Illuminate\Routing\Route $route */
169
        $route = $this->app['router']->current();
170
        if (!$route) {
0 ignored issues
show
introduced by
$route is of type Illuminate\Routing\Route, thus it always evaluated to true.
Loading history...
171
            return;
172
        }
173
174
        if (isset($route->controller)) { // For Laravel 5.4+
175
            if (empty($this->whiteListControllers) || !isset($this->whiteListControllers[get_class($route->controller)])) {
0 ignored issues
show
Bug introduced by
It seems like $route->controller can also be of type string; however, parameter $object of get_class() does only seem to accept object, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

175
            if (empty($this->whiteListControllers) || !isset($this->whiteListControllers[get_class(/** @scrutinizer ignore-type */ $route->controller)])) {
Loading history...
176
                unset($route->controller);
177
            }
178
        } else {
179
            $reflection = new \ReflectionClass(get_class($route));
180
            if ($reflection->hasProperty('controller')) { // For Laravel 5.3
181
                $controller = $reflection->getProperty('controller');
182
                $controller->setAccessible(true);
183
                if (empty($this->whiteListControllers) || !isset($this->whiteListControllers[get_class($controller->getValue($route))])) {
184
                    $controller->setValue($route, null);
185
                }
186
            }
187
        }
188
    }
189
190
    /**
191
     * Determine if is lumen.
192
     *
193
     * @return bool
194
     */
195
    protected function isLumen()
196
    {
197
        return $this->config['is_lumen'];
198
    }
199
}
200