Completed
Push — master ( 72ef67...f5a041 )
by Derek Stephen
01:41
created

ApplicationPackage::setupPdoConnection()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1.3847

Importance

Changes 0
Metric Value
dl 0
loc 18
ccs 3
cts 11
cp 0.2727
rs 9.6666
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1.3847
1
<?php
2
3
namespace Bone\Mvc;
4
5
use Barnacle\Container;
6
use Barnacle\Exception\NotFoundException;
7
use Barnacle\RegistrationInterface;
8
use Bone\Firewall\FirewallPackage;
9
use Bone\Http\Middleware\Stack;
10
use Bone\Http\MiddlewareAwareInterface;
11
use Bone\I18n\I18nPackage;
12
use Bone\I18n\I18nRegistrationInterface;
13
use Bone\I18n\View\Extension\LocaleLink;
14
use Bone\I18n\View\Extension\Translate;
15
use Bone\Mvc\Controller\DownloadController;
16
use Bone\Mvc\Router;
17
use Bone\Mvc\Router\Decorator\ExceptionDecorator;
18
use Bone\Mvc\Router\Decorator\NotAllowedDecorator;
19
use Bone\Mvc\Router\Decorator\NotFoundDecorator;
20
use Bone\Mvc\Router\PlatesStrategy;
21
use Bone\Mvc\Router\RouterConfigInterface;
22
use Bone\Mvc\View\Extension\Plates\AlertBox;
23
use Bone\Mvc\View\ViewEngine;
24
use Bone\View\Helper\Paginator;
25
use Bone\Mvc\View\PlatesEngine;
26
use Bone\I18n\Service\TranslatorFactory;
27
use League\Plates\Template\Folders;
28
use League\Route\Strategy\ApplicationStrategy;
29
use League\Route\Strategy\JsonStrategy;
30
use Locale;
31
use PDO;
32
use Laminas\Diactoros\ResponseFactory;
33
use Laminas\I18n\Translator\Loader\Gettext;
34
use Laminas\I18n\Translator\Translator;
35
use Psr\Http\Server\MiddlewareInterface;
36
37
class ApplicationPackage implements RegistrationInterface
38
{
39
    /** @var array $config */
40
    private $config;
41
42
    /** @var Router $router */
43
    private $router;
44
45
    /** @var bool $i18nEnabledSite */
46
    private $i18nEnabledSite = false;
47
48
    /** @var array $supportedLocales */
49
    private $supportedLocales = [];
50
51
    /**
52
     * ApplicationPackage constructor.
53
     * @param array $config
54
     * @param Router $router
55
     */
56 9
    public function __construct(array $config, Router $router)
57
    {
58 9
        $this->config = $config;
59 9
        $this->router = $router;
60 9
    }
61
62
    /**
63
     * @param Container $c
64
     */
65 9
    public function addToContainer(Container $c)
66
    {
67 9
        $this->setConfigArray($c);
68 9
        $this->setLocale($c);
69 9
        $this->setupLogs($c);
70 9
        $this->setupPdoConnection($c);
71 9
        $this->setupViewEngine($c);
72 9
        $this->initMiddlewareStack($c);
73 9
        $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 9
    private function setLocale(Container $c)
95
    {
96 9
        $i18n = $c->get('i18n');
97 9
        $this->i18nEnabledSite = $i18n['enabled'];
98 9
        $this->supportedLocales = $i18n['supported_locales'];
99 9
        $defaultLocale = $i18n['default_locale'];
100 9
        Locale::setDefault($defaultLocale);
101 9
    }
102
103
    /**
104
     * @param Container $c
105
     */
106 9
    private function setupViewEngine(Container $c)
107
    {
108
        // set up the view engine dependencies
109 9
        $viewEngine = new PlatesEngine($c->get('viewFolder'));
110 9
        $viewEngine->loadExtension(new AlertBox());
111
112 9
        $c[PlatesEngine::class] = $viewEngine;
113
114 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...
115 9
            $layout = $c->get('default_layout');
116 9
            $templates = $c->get('error_pages');
117 9
            $viewEngine = $c->get(PlatesEngine::class);
118 9
            $notFoundDecorator = new NotFoundDecorator($viewEngine, $templates);
119 9
            $notFoundDecorator->setLayout($layout);
120
121 9
            return $notFoundDecorator;
122 9
        });
123
124 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...
125 9
            $layout = $c->get('default_layout');
126 9
            $templates = $c->get('error_pages');
127 9
            $viewEngine = $c->get(PlatesEngine::class);
128 9
            $notAllowedDecorator = new NotAllowedDecorator($viewEngine, $templates);
129 9
            $notAllowedDecorator->setLayout($layout);
130
131 9
            return $notAllowedDecorator;
132 9
        });
133
134 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...
135 9
            $viewEngine = $c->get(PlatesEngine::class);
136 9
            $layout = $c->get('default_layout');
137 9
            $templates = $c->get('error_pages');
138 9
            $decorator = new ExceptionDecorator($viewEngine, $templates);
139 9
            $decorator->setLayout($layout);
140
141 9
            return $decorator;
142 9
        });
143
144
        $c[PlatesStrategy::class] = $c->factory(function (Container $c) {
145 9
            $viewEngine = $c->get(PlatesEngine::class);
146 9
            $notFoundDecorator = $c->get(NotFoundDecorator::class);
147 9
            $notAllowedDecorator = $c->get(NotAllowedDecorator::class);
148 9
            $exceptionDecorator = $c->get(ExceptionDecorator::class);
149 9
            $layout = $c->get('default_layout');
150 9
            $strategy = new PlatesStrategy($viewEngine, $notFoundDecorator, $notAllowedDecorator, $layout, $exceptionDecorator);
151
152 9
            return $strategy;
153 9
        });
154
155
        /** @var PlatesStrategy $strategy */
156 9
        $strategy = $c->get(PlatesStrategy::class);
157 9
        $strategy->setContainer($c);
158
159 9
        if ($this->i18nEnabledSite === true) {
160 8
            $strategy->setI18nEnabled(true);
161 8
            $strategy->setSupportedLocales($this->supportedLocales);
162
        }
163
164 9
        $this->router->setStrategy($strategy);
165 9
    }
166
167
    /**
168
     * @param Container $c
169
     */
170
    private function setupModules(Container $c)
171
    {
172
        // set up the modules and vendor package modules
173
        $packages = $c->get('packages');
174
        $i18n = $c->get('i18n');
175
        /** @var Translator $translator */
176
        $translator = $c->get(Translator::class);
177
178
        foreach ($packages as $packageName) {
179
            if (class_exists($packageName)) {
180
                /** @var RegistrationInterface $package */
181
                $package = new $packageName();
182
183
                if ($package->hasEntityPath()) {
184
                    $paths = $c['entity_paths'];
185
                    $paths[] = $package->getEntityPath();
186
                    $c['entity_paths'] = $paths;
187
                }
188
            }
189
        }
190
        reset($packages);
191
        foreach ($packages as $packageName) {
192
            if (class_exists($packageName)) {
193
                /** @var RegistrationInterface $package */
194
                $package = new $packageName();
195
                $package->addToContainer($c);
196
197
                if ($package instanceof RouterConfigInterface) {
198
                    $package->addRoutes($c, $this->router);
199
                }
200
201
                if ($package instanceof I18nRegistrationInterface) {
0 ignored issues
show
Bug introduced by
The class Bone\I18n\I18nRegistrationInterface does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
202
                    foreach ($i18n['supported_locales'] as $locale) {
203
                        $factory = new TranslatorFactory();
204
                        $factory->addPackageTranslations($translator, $package, $locale);
205
                    }
206
                }
207
208
                if ($package instanceof MiddlewareAwareInterface) {
209
                    $stack = $c->get(Stack::class);
210
                    $package->addMiddleware($stack);
211
                }
212
            }
213
        }
214
    }
215
216
    /**
217
     * @param Container $c
218
     */
219 9
    private function setupTranslator(Container $c)
220
    {
221 9
        $package = new I18nPackage();
222 9
        $package->addToContainer($c);
223 9
        $package->addMiddleware($c->get(Stack::class), $c);
224
    }
225
226
227
    /**
228
     * @param Container $c
229
     */
230 9
    private function setupPdoConnection(Container $c)
231
    {
232
        // set up a db connection
233
        $c[PDO::class] = $c->factory(function (Container $c): PDO {
234
            $credentials = $c->get('db');
235
            $host = $credentials['host'];
236
            $db = $credentials['database'];
237
            $user = $credentials['user'];
238
            $pass = $credentials['pass'];
239
240
            $dbConnection = new PDO('mysql:host=' . $host . ';dbname=' . $db, $user, $pass, [
241
                PDO::ATTR_EMULATE_PREPARES => false,
242
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
243
            ]);
244
245
            return $dbConnection;
246 9
        });
247 9
    }
248
249
    /**
250
     * @param Container $c
251
     */
252
    private function setupDownloadController(Container $c): void
253
    {
254
        $uploadDirectory = $c->get('uploads_dir');
255
        $c[DownloadController::class] = new DownloadController($uploadDirectory);
256
        $strategy = new JsonStrategy(new ResponseFactory());
257
        $strategy->setContainer($c);
258
        $this->router->map('GET', '/download', [DownloadController::class, 'downloadAction'])->setStrategy($strategy);
259
    }
260
261
    /**
262
     * @param Container $c
263
     */
264
    private function setupRouteFirewall(Container $c): void
265
    {
266
        $firewallPackage = new FirewallPackage();
267
        $firewallPackage->addToContainer($c);
268
    }
269
270
    /**
271
     * @param Container $c
272
     */
273 9
    private function setupLogs(Container $c)
274
    {
275 9
        if ($c->has('display_errors')) {
276
            ini_set('display_errors', $c->get('display_errors'));
277
        }
278
279 9
        if ($c->has('error_reporting')) {
280
            error_reporting($c->get('error_reporting'));
281
        }
282
283 9
        if ($c->has('error_log')) {
284
            $errorLog = $c->get('error_log');
285
            if (!file_exists($errorLog)) {
286
                file_put_contents($errorLog, '');
287
                chmod($errorLog, 0775);
288
            }
289
            ini_set($c->get('error_log'), $errorLog);
290
        }
291 9
    }
292
293
    /**
294
     * @param Container $c
295
     */
296
    private function setupModuleViewOverrides(Container $c): void
297
    {
298
        /** @var PlatesEngine $viewEngine */
299
        $viewEngine = $c->get(PlatesEngine::class);
300
        $views = $c->get('views');
301
        $registeredViews = $viewEngine->getFolders();
302
303
        foreach ($views as $view => $folder) {
304
            $this->overrideViewFolder($view, $folder, $registeredViews);
305
        }
306
    }
307
308
    /**
309
     * @param string $view
310
     * @param string $folder
311
     * @param array $registeredViews
312
     * @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...
313
     */
314
    private function overrideViewFolder(string $view, string $folder, Folders $registeredViews): void
315
    {
316
        if ($registeredViews->exists($view)) {
317
            /** @var \League\Plates\Template\Folder $currentFolder */
318
            $currentFolder = $registeredViews->get($view);
319
            $currentFolder->setPath($folder);
320
        }
321
    }
322
323
    /**
324
     * @return string
325
     */
326 1
    public function getEntityPath(): string
327
    {
328 1
        return '';
329
    }
330
331
    /**
332
     * @return bool
333
     */
334 1
    public function hasEntityPath(): bool
335
    {
336 1
        return false;
337
    }
338
339
    /**
340
     * @param Container $c
341
     */
342 9
    private function initMiddlewareStack(Container $c): void
343
    {
344 9
        $router = $c->get(Router::class);
345 9
        $c[Stack::class] = new Stack($router);
346 9
    }
347
348
    /**
349
     * @param Container $c
350
     */
351
    private function setupMiddlewareStack(Container $c): void
352
    {
353
        $stack = $c->get(Stack::class);
354
        $middlewareStack = $c->has('stack') ? $c->get('stack') : [];
355
356
        foreach ($middlewareStack as $middleware) {
357
            if ($middleware instanceof MiddlewareInterface) {
358
                $stack->addMiddleWare($middleware);
359
            } elseif ($c->has($middleware)) {
360
                $stack->addMiddleWare($c->get($middleware));
361
            } else {
362
                $stack->addMiddleWare(new $middleware());
363
            }
364
        }
365
    }
366
}