Completed
Push — master ( 2ac5d7...b01e54 )
by Derek Stephen
01:45
created

ApplicationPackage   A

Complexity

Total Complexity 36

Size/Duplication

Total Lines 299
Duplicated Lines 9.03 %

Coupling/Cohesion

Components 1
Dependencies 19

Test Coverage

Coverage 15.75%

Importance

Changes 0
Metric Value
wmc 36
lcom 1
cbo 19
dl 27
loc 299
ccs 23
cts 146
cp 0.1575
rs 9.52
c 0
b 0
f 0

16 Methods

Rating   Name   Duplication   Size   Complexity  
A setConfigArray() 0 6 2
A __construct() 0 5 1
A addToContainer() 0 14 1
B setupViewEngine() 27 55 1
B setupModules() 0 45 10
A setupTranslator() 0 6 1
A setupPdoConnection() 0 5 1
A setupDownloadController() 0 8 1
A setupRouteFirewall() 0 5 1
A setupLogs() 0 19 5
A setupModuleViewOverrides() 0 11 2
A overrideViewFolder() 0 8 2
A getEntityPath() 0 4 1
A hasEntityPath() 0 4 1
A initMiddlewareStack() 0 5 1
A setupMiddlewareStack() 0 15 5

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace Bone\Mvc;
4
5
use Barnacle\Container;
6
use Barnacle\Exception\NotFoundException;
7
use Barnacle\RegistrationInterface;
8
use Bone\Db\DbPackage;
9
use Bone\Firewall\FirewallPackage;
10
use Bone\Http\Middleware\Stack;
11
use Bone\Http\MiddlewareAwareInterface;
12
use Bone\I18n\I18nPackage;
13
use Bone\I18n\I18nRegistrationInterface;
14
use Bone\I18n\View\Extension\LocaleLink;
15
use Bone\I18n\View\Extension\Translate;
16
use Bone\Mvc\Controller\DownloadController;
17
use Bone\Mvc\Router;
18
use Bone\Mvc\Router\Decorator\ExceptionDecorator;
19
use Bone\Mvc\Router\Decorator\NotAllowedDecorator;
20
use Bone\Mvc\Router\Decorator\NotFoundDecorator;
21
use Bone\Mvc\Router\PlatesStrategy;
22
use Bone\Mvc\Router\RouterConfigInterface;
23
use Bone\Mvc\View\Extension\Plates\AlertBox;
24
use Bone\Mvc\View\ViewEngine;
25
use Bone\View\Helper\Paginator;
26
use Bone\Mvc\View\PlatesEngine;
27
use Bone\I18n\Service\TranslatorFactory;
28
use League\Plates\Template\Folders;
29
use League\Route\Strategy\ApplicationStrategy;
30
use League\Route\Strategy\JsonStrategy;
31
use Locale;
32
use PDO;
33
use Laminas\Diactoros\ResponseFactory;
34
use Laminas\I18n\Translator\Loader\Gettext;
35
use Laminas\I18n\Translator\Translator;
36
use Psr\Http\Server\MiddlewareInterface;
37
38
class ApplicationPackage implements RegistrationInterface
39
{
40
    /** @var array $config */
41
    private $config;
42
43
    /** @var Router $router */
44
    private $router;
45
46
    /** @var bool $i18nEnabledSite */
47
    private $i18nEnabledSite = false;
48
49
    /** @var array $supportedLocales */
50
    private $supportedLocales = [];
51
52
    /**
53
     * ApplicationPackage constructor.
54
     * @param array $config
55
     * @param Router $router
56
     */
57 9
    public function __construct(array $config, Router $router)
58
    {
59 9
        $this->config = $config;
60 9
        $this->router = $router;
61 9
    }
62
63
    /**
64
     * @param Container $c
65
     */
66 9
    public function addToContainer(Container $c)
67
    {
68 9
        $this->setConfigArray($c);
69 9
        $this->setupLogs($c);
70 9
        $this->setupPdoConnection($c);
71
        $this->setupViewEngine($c);
72
        $this->initMiddlewareStack($c);
73
        $this->setupTranslator($c);
74
        $this->setupModules($c);
75
        $this->setupModuleViewOverrides($c);
76
        $this->setupDownloadController($c);
77
        $this->setupRouteFirewall($c);
78
        $this->setupMiddlewareStack($c);
79
    }
80
81
    /**
82
     * @param Container $c
83
     */
84 9
    private function setConfigArray(Container $c)
85
    {
86 9
        foreach ($this->config as $key => $value) {
87 9
            $c[$key] = $value;
88
        }
89 9
    }
90
91
    /**
92
     * @param Container $c
93
     */
94
    private function setupViewEngine(Container $c)
95
    {
96
        // set up the view engine dependencies
97
        $viewEngine = new PlatesEngine($c->get('viewFolder'));
98
        $viewEngine->loadExtension(new AlertBox());
99
100
        $c[PlatesEngine::class] = $viewEngine;
101
102 View Code Duplication
        $c[NotFoundDecorator::class] = $c->factory(function (Container $c) {
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...
103
            $layout = $c->get('default_layout');
104
            $templates = $c->get('error_pages');
105
            $viewEngine = $c->get(PlatesEngine::class);
106
            $notFoundDecorator = new NotFoundDecorator($viewEngine, $templates);
107
            $notFoundDecorator->setLayout($layout);
108
109
            return $notFoundDecorator;
110
        });
111
112 View Code Duplication
        $c[NotAllowedDecorator::class] = $c->factory(function (Container $c) {
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...
113
            $layout = $c->get('default_layout');
114
            $templates = $c->get('error_pages');
115
            $viewEngine = $c->get(PlatesEngine::class);
116
            $notAllowedDecorator = new NotAllowedDecorator($viewEngine, $templates);
117
            $notAllowedDecorator->setLayout($layout);
118
119
            return $notAllowedDecorator;
120
        });
121
122 View Code Duplication
        $c[ExceptionDecorator::class] = $c->factory(function (Container $c) {
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...
123
            $viewEngine = $c->get(PlatesEngine::class);
124
            $layout = $c->get('default_layout');
125
            $templates = $c->get('error_pages');
126
            $decorator = new ExceptionDecorator($viewEngine, $templates);
127
            $decorator->setLayout($layout);
128
129
            return $decorator;
130
        });
131
132
        $c[PlatesStrategy::class] = $c->factory(function (Container $c) {
133
            $viewEngine = $c->get(PlatesEngine::class);
134
            $notFoundDecorator = $c->get(NotFoundDecorator::class);
135
            $notAllowedDecorator = $c->get(NotAllowedDecorator::class);
136
            $exceptionDecorator = $c->get(ExceptionDecorator::class);
137
            $layout = $c->get('default_layout');
138
            $strategy = new PlatesStrategy($viewEngine, $notFoundDecorator, $notAllowedDecorator, $layout, $exceptionDecorator);
139
140
            return $strategy;
141
        });
142
143
        /** @var PlatesStrategy $strategy */
144
        $strategy = $c->get(PlatesStrategy::class);
145
        $strategy->setContainer($c);
146
147
        $this->router->setStrategy($strategy);
148
    }
149
150
    /**
151
     * @param Container $c
152
     */
153
    private function setupModules(Container $c)
154
    {
155
        // set up the modules and vendor package modules
156
        $packages = $c->get('packages');
157
        $i18n = $c->get('i18n');
158
        /** @var Translator $translator */
159
        $translator = $c->get(Translator::class);
160
161
        foreach ($packages as $packageName) {
162
            if (class_exists($packageName)) {
163
                /** @var RegistrationInterface $package */
164
                $package = new $packageName();
165
166
                if ($package->hasEntityPath()) {
167
                    $paths = $c['entity_paths'];
168
                    $paths[] = $package->getEntityPath();
169
                    $c['entity_paths'] = $paths;
170
                }
171
            }
172
        }
173
        reset($packages);
174
        foreach ($packages as $packageName) {
175
            if (class_exists($packageName)) {
176
                /** @var RegistrationInterface $package */
177
                $package = new $packageName();
178
                $package->addToContainer($c);
179
180
                if ($package instanceof RouterConfigInterface) {
181
                    $package->addRoutes($c, $this->router);
182
                }
183
184
                if ($package instanceof I18nRegistrationInterface) {
185
                    foreach ($i18n['supported_locales'] as $locale) {
186
                        $factory = new TranslatorFactory();
187
                        $factory->addPackageTranslations($translator, $package, $locale);
188
                    }
189
                }
190
191
                if ($package instanceof MiddlewareAwareInterface) {
192
                    $stack = $c->get(Stack::class);
193
                    $package->addMiddleware($stack);
194
                }
195
            }
196
        }
197
    }
198
199
    /**
200
     * @param Container $c
201
     */
202
    private function setupTranslator(Container $c)
203
    {
204
        $package = new I18nPackage();
205
        $package->addToContainer($c);
206
        $package->addMiddleware($c->get(Stack::class), $c);
207
    }
208
209
210
    /**
211
     * @param Container $c
212
     */
213 9
    private function setupPdoConnection(Container $c)
214
    {
215 9
        $package = new DbPackage();
216
        $package->addToContainer($c);
217
    }
218
219
    /**
220
     * @param Container $c
221
     */
222
    private function setupDownloadController(Container $c): void
223
    {
224
        $uploadDirectory = $c->get('uploads_dir');
225
        $c[DownloadController::class] = new DownloadController($uploadDirectory);
226
        $strategy = new JsonStrategy(new ResponseFactory());
227
        $strategy->setContainer($c);
228
        $this->router->map('GET', '/download', [DownloadController::class, 'downloadAction'])->setStrategy($strategy);
229
    }
230
231
    /**
232
     * @param Container $c
233
     */
234
    private function setupRouteFirewall(Container $c): void
235
    {
236
        $firewallPackage = new FirewallPackage();
237
        $firewallPackage->addToContainer($c);
238
    }
239
240
    /**
241
     * @param Container $c
242
     */
243 9
    private function setupLogs(Container $c)
244
    {
245 9
        if ($c->has('display_errors')) {
246
            ini_set('display_errors', $c->get('display_errors'));
247
        }
248
249 9
        if ($c->has('error_reporting')) {
250
            error_reporting($c->get('error_reporting'));
251
        }
252
253 9
        if ($c->has('error_log')) {
254
            $errorLog = $c->get('error_log');
255
            if (!file_exists($errorLog)) {
256
                file_put_contents($errorLog, '');
257
                chmod($errorLog, 0775);
258
            }
259
            ini_set($c->get('error_log'), $errorLog);
260
        }
261 9
    }
262
263
    /**
264
     * @param Container $c
265
     */
266
    private function setupModuleViewOverrides(Container $c): void
267
    {
268
        /** @var PlatesEngine $viewEngine */
269
        $viewEngine = $c->get(PlatesEngine::class);
270
        $views = $c->get('views');
271
        $registeredViews = $viewEngine->getFolders();
272
273
        foreach ($views as $view => $folder) {
274
            $this->overrideViewFolder($view, $folder, $registeredViews);
275
        }
276
    }
277
278
    /**
279
     * @param string $view
280
     * @param string $folder
281
     * @param array $registeredViews
282
     * @param PlatesEngine $viewEngine
0 ignored issues
show
Bug introduced by
There is no parameter named $viewEngine. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
283
     */
284
    private function overrideViewFolder(string $view, string $folder, Folders $registeredViews): void
285
    {
286
        if ($registeredViews->exists($view)) {
287
            /** @var \League\Plates\Template\Folder $currentFolder */
288
            $currentFolder = $registeredViews->get($view);
289
            $currentFolder->setPath($folder);
290
        }
291
    }
292
293
    /**
294
     * @return string
295
     */
296 1
    public function getEntityPath(): string
297
    {
298 1
        return '';
299
    }
300
301
    /**
302
     * @return bool
303
     */
304 1
    public function hasEntityPath(): bool
305
    {
306 1
        return false;
307
    }
308
309
    /**
310
     * @param Container $c
311
     */
312
    private function initMiddlewareStack(Container $c): void
313
    {
314
        $router = $c->get(Router::class);
315
        $c[Stack::class] = new Stack($router);
316
    }
317
318
    /**
319
     * @param Container $c
320
     */
321
    private function setupMiddlewareStack(Container $c): void
322
    {
323
        $stack = $c->get(Stack::class);
324
        $middlewareStack = $c->has('stack') ? $c->get('stack') : [];
325
326
        foreach ($middlewareStack as $middleware) {
327
            if ($middleware instanceof MiddlewareInterface) {
328
                $stack->addMiddleWare($middleware);
329
            } elseif ($c->has($middleware)) {
330
                $stack->addMiddleWare($c->get($middleware));
331
            } else {
332
                $stack->addMiddleWare(new $middleware());
333
            }
334
        }
335
    }
336
}