Completed
Push — master ( ee40ad...c11639 )
by Derek Stephen
53s
created

ApplicationPackage::setupDownloadController()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 1

Importance

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