Completed
Push — master ( 70dfc9...fb2e0c )
by Michael
03:05
created

Wiring::wireConfig()   D

Complexity

Conditions 9
Paths 48

Size

Total Lines 44
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 8
Bugs 1 Features 0
Metric Value
c 8
b 1
f 0
dl 0
loc 44
rs 4.909
cc 9
eloc 29
nc 48
nop 0
1
<?php
2
/**
3
 * Contains Wiring class.
4
 *
5
 * PHP version 5.5
6
 *
7
 * LICENSE:
8
 * This file is part of Yet Another Php Eve Api Library also know as Yapeal
9
 * which can be used to access the Eve Online API data and place it into a
10
 * database.
11
 * Copyright (C) 2014-2016 Michael Cummings
12
 *
13
 * This program is free software: you can redistribute it and/or modify it
14
 * under the terms of the GNU Lesser General Public License as published by the
15
 * Free Software Foundation, either version 3 of the License, or (at your
16
 * option) any later version.
17
 *
18
 * This program is distributed in the hope that it will be useful, but WITHOUT
19
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
20
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
21
 * for more details.
22
 *
23
 * You should have received a copy of the GNU Lesser General Public License
24
 * along with this program. If not, see
25
 * <http://www.gnu.org/licenses/>.
26
 *
27
 * You should be able to find a copy of this license in the LICENSE.md file. A
28
 * copy of the GNU GPL should also be available in the GNU-GPL.md file.
29
 *
30
 * @copyright 2014-2016 Michael Cummings
31
 * @license   http://www.gnu.org/copyleft/lesser.html GNU LGPL
32
 * @author    Michael Cummings <[email protected]>
33
 */
34
namespace Yapeal\Configuration;
35
36
use FilePathNormalizer\FilePathNormalizerTrait;
37
use FilesystemIterator;
38
use Monolog\ErrorHandler;
39
use Monolog\Formatter\LineFormatter;
40
use Monolog\Logger;
41
use PDO;
42
use RecursiveArrayIterator;
43
use RecursiveCallbackFilterIterator;
44
use RecursiveDirectoryIterator;
45
use RecursiveIteratorIterator;
46
use Symfony\Component\Yaml\Exception\ParseException;
47
use Symfony\Component\Yaml\Parser;
48
use Traversable;
49
use Twig_Environment;
50
use Twig_Loader_Filesystem;
51
use Twig_SimpleFilter;
52
use Yapeal\Container\ContainerInterface;
53
use Yapeal\Exception\YapealDatabaseException;
54
use Yapeal\Exception\YapealException;
55
use Yapeal\Network\GuzzleNetworkRetriever;
56
57
/**
58
 * Class Wiring
59
 */
60
class Wiring
61
{
62
    use FilePathNormalizerTrait;
63
    /**
64
     * @param ContainerInterface $dic
65
     */
66
    public function __construct(ContainerInterface $dic)
67
    {
68
        $this->dic = $dic;
69
    }
70
    /**
71
     * @return self Fluent interface.
72
     * @throws \DomainException
73
     * @throws \InvalidArgumentException
74
     * @throws YapealException
75
     * @throws YapealDatabaseException
76
     */
77
    public function wireAll()
78
    {
79
        $this->wireConfig()
80
            ->wireError()
81
            ->wireEvent()
82
            ->wireLog()
83
            ->wireSql()
84
            ->wireXml()
85
            ->wireXsl()
86
            ->wireXsd()
87
            ->wireCache()
88
            ->wireNetwork()
89
            ->wireEveApi();
90
        return $this;
91
    }
92
    /**
93
     * @param array $settings
94
     *
95
     * @return array
96
     * @throws \DomainException
97
     * @throws \InvalidArgumentException
98
     */
99
    protected function doSubs(array $settings)
100
    {
101
        if (0 === count($settings)) {
102
            return [];
103
        }
104
        $depth = 0;
105
        $maxDepth = 10;
106
        $regEx = '/(?<all>\{(?<name>Yapeal(?:\.\w+)+)\})/';
107
        $dic = $this->dic;
108
        do {
109
            $settings = preg_replace_callback(
110
                $regEx,
111
                function ($match) use ($settings, $dic) {
112
                    if (!empty($settings[$match['name']])) {
113
                        return $settings[$match['name']];
114
                    }
115
                    if (!empty($dic[$match['name']])) {
116
                        return $dic[$match['name']];
117
                    }
118
                    return $match['all'];
119
                },
120
                $settings,
121
                -1,
122
                $count
123
            );
124
            if (++$depth > $maxDepth) {
125
                $mess = 'Exceeded maximum depth, check for possible circular reference(s)';
126
                throw new \DomainException($mess);
127
            }
128
            $lastError = preg_last_error();
129
            if (PREG_NO_ERROR !== $lastError) {
130
                $constants = array_flip(get_defined_constants(true)['pcre']);
131
                $lastError = $constants[$lastError];
132
                $mess = 'Received preg error ' . $lastError;
133
                throw new \DomainException($mess);
134
            }
135
        } while ($count > 0);
136
        return $settings;
137
    }
138
    /**
139
     * @return array
140
     */
141
    protected function getFilteredEveApiSubscriberList()
142
    {
143
        $flags = FilesystemIterator::CURRENT_AS_FILEINFO
144
            | FilesystemIterator::KEY_AS_PATHNAME
145
            | FilesystemIterator::SKIP_DOTS
146
            | FilesystemIterator::UNIX_PATHS;
147
        $rdi = new RecursiveDirectoryIterator($this->dic['Yapeal.EveApi.dir']);
148
        $rdi->setFlags($flags);
149
        $rcfi = new RecursiveCallbackFilterIterator(
150
            $rdi, function ($current, $key, $rdi) {
151
            /**
152
             * @type \RecursiveDirectoryIterator $rdi
153
             */
154
            if ($rdi->hasChildren()) {
155
                return true;
156
            }
157
            $dirs = ['Account', 'Api', 'Char', 'Corp', 'Eve', 'Map', 'Server'];
158
            /**
159
             * @type \SplFileInfo $current
160
             */
161
            $dirExists = in_array(basename(dirname($key)), $dirs, true);
162
            return ($dirExists && $current->isFile() && 'php' === $current->getExtension());
163
        }
164
        );
165
        $rii = new RecursiveIteratorIterator(
166
            $rcfi, RecursiveIteratorIterator::LEAVES_ONLY, RecursiveIteratorIterator::CATCH_GET_CHILD
167
        );
168
        $rii->setMaxDepth(3);
169
        $fpn = $this->getFpn();
170
        $files = [];
171
        foreach ($rii as $file) {
172
            $files[] = $fpn->normalizeFile($file->getPathname());
173
        }
174
        return $files;
175
    }
176
    /**
177
     * @param string $configFile
178
     * @param array  $settings
179
     *
180
     * @return array|string
181
     * @throws \DomainException
182
     * @throws \InvalidArgumentException
183
     * @throws YapealException
184
     */
185
    protected function parserConfigFile($configFile, $settings)
186
    {
187
        if (!is_readable($configFile) || !is_file($configFile)) {
188
            return $settings;
189
        }
190
        try {
191
            /**
192
             * @type RecursiveIteratorIterator|Traversable $rItIt
193
             */
194
            $rItIt = new RecursiveIteratorIterator(
195
                new RecursiveArrayIterator(
196
                    (new Parser())->parse(
197
                        file_get_contents($configFile),
198
                        true,
199
                        false
200
                    )
201
                )
202
            );
203
        } catch (ParseException $exc) {
204
            $mess = sprintf(
205
                'Unable to parse the YAML configuration file %2$s.' . ' The error message was %1$s',
206
                $exc->getMessage(),
207
                $configFile
208
            );
209
            throw new YapealException($mess, 0, $exc);
210
        }
211
        foreach ($rItIt as $leafValue) {
212
            $keys = [];
213
            /** @noinspection DisconnectedForeachInstructionInspection */
214
            /**
215
             * @type array $depths
216
             */
217
            $depths = range(0, $rItIt->getDepth());
218
            foreach ($depths as $depth) {
219
                $keys[] = $rItIt->getSubIterator($depth)
220
                    ->key();
221
            }
222
            $settings[implode('.', $keys)] = $leafValue;
223
        }
224
        return $this->doSubs($settings);
225
    }
226
    /**
227
     * @return self Fluent interface.
228
     */
229
    protected function wireCache()
230
    {
231
        $dic = $this->dic;
232
        if ('none' !== $dic['Yapeal.Cache.fileSystemMode']) {
233
            if (empty($dic['Yapeal.FileSystem.CachePreserver'])) {
234
                $dic['Yapeal.FileSystem.CachePreserver'] = function () use ($dic) {
235
                    return new $dic['Yapeal.Cache.Handlers.preserve']($dic['Yapeal.Cache.dir']);
236
                };
237
            }
238
            if (empty($dic['Yapeal.FileSystem.CacheRetriever'])) {
239
                $dic['Yapeal.FileSystem.CacheRetriever'] = function () use ($dic) {
240
                    return new $dic['Yapeal.Cache.Handlers.retrieve']($dic['Yapeal.Cache.dir']);
241
                };
242
            }
243
            /**
244
             * @type \Yapeal\Event\MediatorInterface $mediator
245
             */
246
            $mediator = $dic['Yapeal.Event.Mediator'];
247
            $mediator->addServiceSubscriberByEventList(
248
                'Yapeal.FileSystem.CachePreserver',
249
                ['Yapeal.EveApi.cache' => ['preserveEveApi', 'last']]
250
            );
251
            $mediator->addServiceSubscriberByEventList(
252
                'Yapeal.FileSystem.CacheRetriever',
253
                ['Yapeal.EveApi.retrieve' => ['retrieveEveApi', 'last']]
254
            );
255
        }
256
        return $this;
257
    }
258
    /**
259
     * @return self Fluent interface.
260
     * @throws \DomainException
261
     * @throws \InvalidArgumentException
262
     * @throws YapealException
263
     */
264
    protected function wireConfig()
265
    {
266
        $dic = $this->dic;
267
        $fpn = $this->getFpn();
268
        $path = $fpn->normalizePath(dirname(dirname(__DIR__)));
269
        if (empty($dic['Yapeal.baseDir'])) {
270
            $dic['Yapeal.baseDir'] = $path;
271
        }
272
        if (empty($dic['Yapeal.libDir'])) {
273
            $dic['Yapeal.libDir'] = $path . 'lib/';
274
        }
275
        $configFiles = [
276
            $fpn->normalizeFile(__DIR__ . '/yapeal_defaults.yaml'),
277
            $fpn->normalizeFile($dic['Yapeal.baseDir'] . 'config/yapeal.yaml')
278
        ];
279
        if (empty($dic['Yapeal.vendorParentDir'])) {
280
            $vendorPos = strpos(
281
                $path,
282
                'vendor/'
283
            );
284
            if (false !== $vendorPos) {
285
                $dic['Yapeal.vendorParentDir'] = substr($path, 0, $vendorPos);
286
                $configFiles[] = $fpn->normalizeFile($dic['Yapeal.vendorParentDir'] . 'config/yapeal.yaml');
287
            }
288
        } else {
289
            $configFiles[] = $fpn->normalizeFile($dic['Yapeal.vendorParentDir'] . 'config/yapeal.yaml');
290
        }
291
        $settings = [];
292
        // Process each file in turn so any substitutions are done in a more
293
        // consistent way.
294
        foreach ($configFiles as $configFile) {
295
            $settings = $this->parserConfigFile(
296
                $configFile,
297
                $settings
298
            );
299
        }
300
        if (0 !== count($settings)) {
301
            // Assure NOT overwriting already existing settings.
302
            foreach ($settings as $key => $value) {
303
                $dic[$key] = empty($dic[$key]) ? $value : $dic[$key];
304
            }
305
        }
306
        return $this;
307
    }
308
    /**
309
     * @return self Fluent interface.
310
     */
311
    protected function wireError()
312
    {
313
        if (!empty($this->dic['Yapeal.Error.Logger'])) {
314
            return $this;
315
        }
316
        $this->dic['Yapeal.Error.Logger'] = function ($dic) {
317
            /**
318
             * @type Logger $logger
319
             */
320
            $logger = new $dic['Yapeal.Error.class']($dic['Yapeal.Error.channel']);
321
            $group = [];
322
            if ('cli' === PHP_SAPI) {
323
                $group[] = new $dic['Yapeal.Error.Handlers.stream'](
324
                    'php://stderr', 100
325
                );
326
            }
327
            $group[] = new $dic['Yapeal.Error.Handlers.stream'](
328
                $dic['Yapeal.Error.dir'] . $dic['Yapeal.Error.fileName'], 100
329
            );
330
            $logger->pushHandler(
331
                new $dic['Yapeal.Error.Handlers.fingersCrossed'](
332
                    new $dic['Yapeal.Error.Handlers.group']($group),
333
                    (int)$dic['Yapeal.Error.threshold'],
334
                    (int)$dic['Yapeal.Error.bufferSize']
335
                )
336
            );
337
            /**
338
             * @type ErrorHandler $error
339
             */
340
            $error = $dic['Yapeal.Error.Handlers.error'];
341
            $error::register(
342
                $logger,
343
                [],
344
                (int)$dic['Yapeal.Error.threshold'],
345
                (int)$dic['Yapeal.Error.threshold']
346
            );
347
            return $error;
348
        };
349
        // Activate error logger now since it is needed to log any future fatal
350
        // errors or exceptions.
351
        $this->dic['Yapeal.Error.Logger'];
352
        return $this;
353
    }
354
    /**
355
     * @return self Fluent interface.
356
     */
357
    protected function wireEveApi()
358
    {
359
        /**
360
         * @type ContainerInterface|\ArrayObject $dic
361
         */
362
        $dic = $this->dic;
363
        /**
364
         * @type \Yapeal\Event\MediatorInterface $mediator
365
         */
366
        $mediator = $dic['Yapeal.Event.Mediator'];
367
        $internal = $this->getFilteredEveApiSubscriberList();
368
        if (0 !== count($internal)) {
369
            $base = 'Yapeal.EveApi';
370
            /**
371
             * @type \SplFileInfo $subscriber
372
             */
373
            foreach ($internal as $subscriber) {
374
                $service = sprintf(
375
                    '%1$s.%2$s.%3$s',
376
                    $base,
377
                    basename(dirname($subscriber)),
378
                    basename($subscriber, '.php')
379
                );
380
                if (!array_key_exists($service, $dic)) {
381
                    $dic[$service] = function () use ($dic, $service, $mediator) {
382
                        $class = '\\' . str_replace('.', '\\', $service);
383
                        /**
384
                         * @type \Yapeal\EveApi\EveApiToolsTrait $callable
385
                         */
386
                        $callable = new $class();
387
                        return $callable->setCsq($dic['Yapeal.Sql.CommonQueries'])
388
                            ->setPdo($dic['Yapeal.Sql.Connection']);
389
                    };
390
                }
391
                $events = [$service . '.start' => ['startEveApi', 'last']];
392
                if (false === strpos($subscriber, 'Section')) {
393
                    $events[$service . '.preserve'] = ['preserveEveApi', 'last'];
394
                }
395
                $mediator->addServiceSubscriberByEventList($service, $events);
396
            }
397
        }
398
        if (empty($dic['Yapeal.EveApi.Creator'])) {
399
            $dic['Yapeal.EveApi.Creator'] = function () use ($dic) {
400
                $loader = new Twig_Loader_Filesystem($dic['Yapeal.EveApi.dir']);
401
                $twig = new Twig_Environment(
402
                    $loader, ['debug' => true, 'strict_variables' => true, 'autoescape' => false]
403
                );
404
                $filter = new Twig_SimpleFilter(
405
                    'ucFirst', function ($value) {
406
                    return ucfirst($value);
407
                }
408
                );
409
                $twig->addFilter($filter);
410
                $filter = new Twig_SimpleFilter(
411
                    'lcFirst', function ($value) {
412
                    return lcfirst($value);
413
                }
414
                );
415
                $twig->addFilter($filter);
416
                /**
417
                 * @type \Yapeal\EveApi\Creator $create
418
                 */
419
                $create = new $dic['Yapeal.EveApi.create']($twig, $dic['Yapeal.EveApi.dir']);
420
                if (array_key_exists('Yapeal.Create.overwrite', $dic)) {
421
                    $create->setOverwrite($dic['Yapeal.Create.overwrite']);
422
                }
423
                return $create;
424
            };
425
            $mediator->addServiceSubscriberByEventList(
426
                'Yapeal.EveApi.Creator',
427
                ['Yapeal.EveApi.create' => ['createEveApi', 'last']]
428
            );
429
        }
430
        return $this;
431
    }
432
    /**
433
     * @return self Fluent interface.
434
     * @throws \InvalidArgumentException
435
     */
436
    protected function wireEvent()
437
    {
438
        $dic = $this->dic;
439
        if (empty($dic['Yapeal.Event.EveApiEvent'])) {
440
            $dic['Yapeal.Event.EveApi'] = $dic->factory(
441
                function ($dic) {
442
                    return new $dic['Yapeal.Event.Factories.eveApi']();
443
                }
444
            );
445
        }
446
        if (empty($this->dic['Yapeal.Event.LogEvent'])) {
447
            $this->dic['Yapeal.Event.LogEvent'] = $this->dic->factory(
448
                function ($dic) {
449
                    return new $dic['Yapeal.Event.Factories.log'];
450
                }
451
            );
452
        }
453
        if (empty($dic['Yapeal.Event.Mediator'])) {
454
            $dic['Yapeal.Event.Mediator'] = function ($dic) {
455
                return new $dic['Yapeal.Event.mediator']($dic);
456
            };
457
        }
458
        return $this;
459
    }
460
    /**
461
     * @return self Fluent interface.
462
     */
463
    protected function wireLog()
464
    {
465
        $dic = $this->dic;
466
        $class = $dic['Yapeal.Log.class'];
467
        if (empty($dic['Yapeal.Log.Logger'])) {
468
            $dic['Yapeal.Log.Logger'] = function () use ($dic, $class) {
469
                $group = [];
470
                $lineFormatter = new LineFormatter;
471
                $lineFormatter->includeStacktraces();
472
                /**
473
                 * @type \Monolog\Handler\StreamHandler $handler
474
                 */
475
                if (PHP_SAPI === 'cli') {
476
                    $handler = new $dic['Yapeal.Log.Handlers.stream'](
477
                        'php://stderr', 100
478
                    );
479
                    $handler->setFormatter($lineFormatter);
480
                    $group[] = $handler;
481
                }
482
                $handler = new $dic['Yapeal.Log.Handlers.stream'](
483
                    $dic['Yapeal.Log.dir'] . $dic['Yapeal.Log.fileName'], 100
484
                );
485
                $handler->setFormatter($lineFormatter);
486
                $group[] = $handler;
487
                return new $class(
488
                    $dic['Yapeal.Log.channel'], [
489
                        new $dic['Yapeal.Log.Handlers.fingersCrossed'](
490
                            new $dic['Yapeal.Log.Handlers.group']($group),
491
                            (int)$dic['Yapeal.Log.threshold'],
492
                            (int)$dic['Yapeal.Log.bufferSize']
493
                        )
494
                    ]
495
                );
496
            };
497
        }
498
        /**
499
         * @type \Yapeal\Event\MediatorInterface $mediator
500
         */
501
        $mediator = $dic['Yapeal.Event.Mediator'];
502
        $mediator->addServiceSubscriberByEventList(
503
            'Yapeal.Log.Logger',
504
            ['Yapeal.Log.log' => ['logEvent', 'last']]
505
        );
506
        return $this;
507
    }
508
    /**
509
     * @return self Fluent interface.
510
     */
511
    protected function wireNetwork()
512
    {
513
        $dic = $this->dic;
514
        if (empty($dic['Yapeal.Network.Client'])) {
515
            $dic['Yapeal.Network.Client'] = function ($dic) {
516
                $appComment = $dic['Yapeal.Network.appComment'];
517
                $appName = $dic['Yapeal.Network.appName'];
518
                $appVersion = $dic['Yapeal.Network.appVersion'];
519
                if ('' === $appName) {
520
                    $appComment = '';
521
                    $appVersion = '';
522
                }
523
                $userAgent = trim(
524
                    str_replace(
525
                        [
526
                            '{machineType}',
527
                            '{osName}',
528
                            '{osRelease}',
529
                            '{phpVersion}',
530
                            '{appComment}',
531
                            '{appName}',
532
                            '{appVersion}'
533
                        ],
534
                        [
535
                            php_uname('m'),
536
                            php_uname('s'),
537
                            php_uname('r'),
538
                            PHP_VERSION,
539
                            $appComment,
540
                            $appName,
541
                            $appVersion
542
                        ],
543
                        $dic['Yapeal.Network.userAgent']
544
                    )
545
                );
546
                $userAgent = ltrim(
547
                    $userAgent,
548
                    '/ '
549
                );
550
                $headers = [
551
                    'Accept'          => $dic['Yapeal.Network.Headers.Accept'],
552
                    'Accept-Charset'  => $dic['Yapeal.Network.Headers.Accept-Charset'],
553
                    'Accept-Encoding' => $dic['Yapeal.Network.Headers.Accept-Encoding'],
554
                    'Accept-Language' => $dic['Yapeal.Network.Headers.Accept-Language'],
555
                    'Connection'      => $dic['Yapeal.Network.Headers.Connection'],
556
                    'Keep-Alive'      => $dic['Yapeal.Network.Headers.Keep-Alive']
557
                ];
558
                // Clean up any extra spaces and EOL chars from Yaml.
559
                foreach ($headers as &$value) {
560
                    /** @noinspection ReferenceMismatchInspection */
561
                    $value = trim(
562
                        str_replace(
563
                            ' ',
564
                            '',
565
                            $value
566
                        )
567
                    );
568
                }
569
                unset($value);
570
                if ('' !== $userAgent) {
571
                    $headers['User-Agent'] = $userAgent;
572
                }
573
                $defaults = [
574
                    'base_uri'        => $dic['Yapeal.Network.baseUrl'],
575
                    'connect_timeout' => (int)$dic['Yapeal.Network.connect_timeout'],
576
                    'headers'         => $headers,
577
                    'timeout'         => (int)$dic['Yapeal.Network.timeout'],
578
                    'verify'          => $dic['Yapeal.Network.verify']
579
                ];
580
                return new $dic['Yapeal.Network.class']($defaults);
581
            };
582
        }
583
        if (empty($dic['Yapeal.Network.Retriever'])) {
584
            $dic['Yapeal.Network.Retriever'] = function ($dic) {
585
                return new GuzzleNetworkRetriever($dic['Yapeal.Network.Client']);
586
            };
587
        }
588
        /**
589
         * @type \Yapeal\Event\MediatorInterface $mediator
590
         */
591
        $mediator = $dic['Yapeal.Event.Mediator'];
592
        $mediator->addServiceSubscriberByEventList(
593
            'Yapeal.Network.Retriever',
594
            ['Yapeal.EveApi.retrieve' => ['retrieveEveApi', 'last']]
595
        );
596
        return $this;
597
    }
598
    /**
599
     * @return self Fluent interface.
600
     * @throws \InvalidArgumentException
601
     * @throws YapealDatabaseException
602
     */
603
    protected function wireSql()
604
    {
605
        $dic = $this->dic;
606
        if (empty($dic['Yapeal.Sql.CommonQueries'])) {
607
            $dic['Yapeal.Sql.CommonQueries'] = function ($dic) {
608
                return new $dic['Yapeal.Sql.sharedSql'](
609
                    $dic['Yapeal.Sql.database'], $dic['Yapeal.Sql.tablePrefix']
610
                );
611
            };
612
        }
613
        if (!empty($dic['Yapeal.Sql.Connection'])) {
614
            return $this;
615
        }
616
        if ('mysql' !== $dic['Yapeal.Sql.platform']) {
617
            $mess = 'Unknown platform, was given ' . $dic['Yapeal.Sql.platform'];
618
            throw new YapealDatabaseException($mess);
619
        }
620
        $dic['Yapeal.Sql.Connection'] = function ($dic) {
621
            $dsn = $dic['Yapeal.Sql.platform'] . ':host=' . $dic['Yapeal.Sql.hostName'] . ';charset=utf8';
622
            if (!empty($dic['Yapeal.Sql.port'])) {
623
                $dsn .= ';port=' . $dic['Yapeal.Sql.port'];
624
            }
625
            /**
626
             * @type PDO $database
627
             */
628
            $database = new $dic['Yapeal.Sql.class'](
629
                $dsn, $dic['Yapeal.Sql.userName'], $dic['Yapeal.Sql.password']
630
            );
631
            $database->setAttribute(
632
                PDO::ATTR_ERRMODE,
633
                PDO::ERRMODE_EXCEPTION
634
            );
635
            $database->exec('SET SESSION SQL_MODE=\'ANSI,TRADITIONAL\'');
636
            $database->exec('SET SESSION TRANSACTION ISOLATION LEVEL SERIALIZABLE');
637
            $database->exec('SET SESSION TIME_ZONE=\'+00:00\'');
638
            $database->exec('SET NAMES utf8mb4 COLLATE utf8mb4_unicode_520_ci');
639
            $database->exec('SET COLLATION_CONNECTION=utf8mb4_unicode_520_ci');
640
            $database->exec('SET DEFAULT_STORAGE_ENGINE=' . $dic['Yapeal.Sql.engine']);
641
            return $database;
642
        };
643 View Code Duplication
        if (empty($dic['Yapeal.Sql.Creator'])) {
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...
644
            $dic['Yapeal.Sql.Creator'] = $dic->factory(
645
                function ($dic) {
646
                    $loader = new Twig_Loader_Filesystem($dic['Yapeal.Sql.dir']);
647
                    $twig = new Twig_Environment(
648
                        $loader, ['debug' => true, 'strict_variables' => true, 'autoescape' => false]
649
                    );
650
                    $filter = new Twig_SimpleFilter(
651
                        'ucFirst', function ($value) {
652
                        return ucfirst($value);
653
                    }
654
                    );
655
                    $twig->addFilter($filter);
656
                    $filter = new Twig_SimpleFilter(
657
                        'lcFirst', function ($value) {
658
                        return lcfirst($value);
659
                    }
660
                    );
661
                    $twig->addFilter($filter);
662
                    /**
663
                     * @type \Yapeal\Sql\Creator $create
664
                     */
665
                    $create = new $dic['Yapeal.Sql.create']($twig, $dic['Yapeal.Sql.dir'], $dic['Yapeal.Sql.platform']);
666
                    if (array_key_exists('Yapeal.Create.overwrite', $dic)) {
667
                        $create->setOverwrite($dic['Yapeal.Create.overwrite']);
668
                    }
669
                    return $create;
670
                }
671
            );
672
        }
673
        /**
674
         * @type \Yapeal\Event\MediatorInterface $mediator
675
         */
676
        $mediator = $dic['Yapeal.Event.Mediator'];
677
        $mediator->addServiceSubscriberByEventList(
678
            'Yapeal.Sql.Creator',
679
            ['Yapeal.EveApi.create' => ['createSql', 'last']]
680
        );
681
        return $this;
682
    }
683
    /**
684
     * Wire Xml section.
685
     *
686
     * @return self Fluent interface.
687
     * @throws \InvalidArgumentException
688
     */
689
    protected function wireXml()
690
    {
691
        if (empty($this->dic['Yapeal.Xml.Data'])) {
692
            $this->dic['Yapeal.Xml.Data'] = $this->dic->factory(
693
                function ($dic) {
694
                    return new $dic['Yapeal.Xml.data']();
695
                }
696
            );
697
        }
698
        return $this;
699
    }
700
    /**
701
     * Wire Xsd section.
702
     *
703
     * @return self Fluent interface.
704
     * @throws \InvalidArgumentException
705
     */
706
    protected function wireXsd()
707
    {
708
        $dic = $this->dic;
709 View Code Duplication
        if (empty($dic['Yapeal.Xsd.Creator'])) {
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...
710
            $dic['Yapeal.Xsd.Creator'] = $dic->factory(
711
                function ($dic) {
712
                    $loader = new Twig_Loader_Filesystem($dic['Yapeal.Xsd.dir']);
713
                    $twig = new Twig_Environment(
714
                        $loader, ['debug' => true, 'strict_variables' => true, 'autoescape' => false]
715
                    );
716
                    $filter = new Twig_SimpleFilter(
717
                        'ucFirst', function ($value) {
718
                        return ucfirst($value);
719
                    }
720
                    );
721
                    $twig->addFilter($filter);
722
                    $filter = new Twig_SimpleFilter(
723
                        'lcFirst', function ($value) {
724
                        return lcfirst($value);
725
                    }
726
                    );
727
                    $twig->addFilter($filter);
728
                    /**
729
                     * @type \Yapeal\Xsd\Creator $create
730
                     */
731
                    $create = new $dic['Yapeal.Xsd.create']($twig, $dic['Yapeal.Xsd.dir']);
732
                    if (array_key_exists('Yapeal.Create.overwrite', $dic)) {
733
                        $create->setOverwrite($dic['Yapeal.Create.overwrite']);
734
                    }
735
                    return $create;
736
                }
737
            );
738
        }
739
        if (empty($dic['Yapeal.Xsd.Validator'])) {
740
            $dic['Yapeal.Xsd.Validator'] = $dic->factory(
741
                function ($dic) {
742
                    return new $dic['Yapeal.Xsd.validate']($dic['Yapeal.Xsd.dir']);
743
                }
744
            );
745
        }
746
        /**
747
         * @type \Yapeal\Event\MediatorInterface $mediator
748
         */
749
        $mediator = $dic['Yapeal.Event.Mediator'];
750
        $mediator->addServiceSubscriberByEventList(
751
            'Yapeal.Xsd.Creator',
752
            ['Yapeal.EveApi.create' => ['createXsd', 'last']]
753
        );
754
        $mediator->addServiceSubscriberByEventList(
755
            'Yapeal.Xsd.Validator',
756
            ['Yapeal.EveApi.validate' => ['validateEveApi', 'last']]
757
        );
758
        return $this;
759
    }
760
    /**
761
     * Wire Xsl section.
762
     *
763
     * @return self Fluent interface.
764
     * @throws \InvalidArgumentException
765
     */
766
    protected function wireXsl()
767
    {
768
        $dic = $this->dic;
769
        if (empty($dic['Yapeal.Xsl.Transformer'])) {
770
            $dic['Yapeal.Xsl.Transformer'] = $dic->factory(
771
                function ($dic) {
772
                    return new $dic['Yapeal.Xsl.transform']($dic['Yapeal.Xsl.dir']);
773
                }
774
            );
775
        }
776
        /**
777
         * @type \Yapeal\Event\MediatorInterface $mediator
778
         */
779
        $mediator = $dic['Yapeal.Event.Mediator'];
780
        $mediator->addServiceSubscriberByEventList(
781
            'Yapeal.Xsl.Transformer',
782
            ['Yapeal.EveApi.transform' => ['transformEveApi', 'last']]
783
        );
784
        return $this;
785
    }
786
    /**
787
     * @type ContainerInterface $dic
788
     */
789
    protected $dic;
790
}
791