Completed
Pull Request — master (#366)
by Elan
01:13
created

ServiceContainer::_services()   C

Complexity

Conditions 8
Paths 1

Size

Total Lines 89

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 89
rs 6.9955
c 0
b 0
f 0
cc 8
nc 1
nop 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace XHGui;
4
5
use MongoClient;
6
use MongoDB\Driver\Manager;
7
use PDO;
8
use Pimple\Container;
9
use RuntimeException;
10
use Slim\Middleware\SessionCookie;
11
use Slim\Slim as App;
12
use Slim\Views\Twig;
13
use XHGui\Db\PdoRepository;
14
use XHGui\Middleware\RenderMiddleware;
15
use XHGui\Saver\NormalizingSaver;
16
use XHGui\Searcher\MongoSearcher;
17
use XHGui\Searcher\PdoSearcher;
18
use XHGui\Twig\TwigExtension;
19
20
class ServiceContainer extends Container
21
{
22
    /** @var self */
23
    protected static $_instance;
24
25
    /**
26
     * @return self
27
     */
28
    public static function instance()
29
    {
30
        if (empty(static::$_instance)) {
31
            static::$_instance = new self();
32
        }
33
34
        return static::$_instance;
35
    }
36
37
    public function __construct()
38
    {
39
        parent::__construct();
40
        $this->_slimApp();
0 ignored issues
show
Unused Code introduced by
The call to the method XHGui\ServiceContainer::_slimApp() seems un-needed as the method has no side-effects.

PHP Analyzer performs a side-effects analysis of your code. A side-effect is basically anything that might be visible after the scope of the method is left.

Let’s take a look at an example:

class User
{
    private $email;

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }
}

If we look at the getEmail() method, we can see that it has no side-effect. Whether you call this method or not, no future calls to other methods are affected by this. As such code as the following is useless:

$user = new User();
$user->getEmail(); // This line could safely be removed as it has no effect.

On the hand, if we look at the setEmail(), this method _has_ side-effects. In the following case, we could not remove the method call:

$user = new User();
$user->setEmail('email@domain'); // This line has a side-effect (it changes an
                                 // instance variable).
Loading history...
41
        $this->_services();
0 ignored issues
show
Unused Code introduced by
The call to the method XHGui\ServiceContainer::_services() seems un-needed as the method has no side-effects.

PHP Analyzer performs a side-effects analysis of your code. A side-effect is basically anything that might be visible after the scope of the method is left.

Let’s take a look at an example:

class User
{
    private $email;

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }
}

If we look at the getEmail() method, we can see that it has no side-effect. Whether you call this method or not, no future calls to other methods are affected by this. As such code as the following is useless:

$user = new User();
$user->getEmail(); // This line could safely be removed as it has no effect.

On the hand, if we look at the setEmail(), this method _has_ side-effects. In the following case, we could not remove the method call:

$user = new User();
$user->setEmail('email@domain'); // This line has a side-effect (it changes an
                                 // instance variable).
Loading history...
42
        $this->_controllers();
43
    }
44
45
    // Create the Slim app.
46
    protected function _slimApp()
47
    {
48
        $this['view'] = static function ($c) {
49
            $cacheDir = $c['config']['cache'] ?? XHGUI_ROOT_DIR . '/cache';
50
51
            // Configure Twig view for slim
52
            $view = new Twig();
53
54
            $view->twigTemplateDirs = [dirname(__DIR__) . '/templates'];
55
            $view->parserOptions = [
56
                'charset' => 'utf-8',
57
                'cache' => $cacheDir,
58
                'auto_reload' => true,
59
                'strict_variables' => false,
60
                'autoescape' => true,
61
            ];
62
63
            return $view;
64
        };
65
66
        $this['app'] = static function ($c) {
67
            if ($c['config']['timezone']) {
68
                date_default_timezone_set($c['config']['timezone']);
69
            }
70
71
            $app = new App($c['config']);
72
73
            // Enable cookie based sessions
74
            $app->add(new SessionCookie([
75
                'httponly' => true,
76
            ]));
77
78
            // Add renderer.
79
            $app->add(new RenderMiddleware());
80
81
            $view = $c['view'];
82
            $view->parserExtensions = [
83
                new TwigExtension($app),
84
            ];
85
            $app->view($view);
86
87
            return $app;
88
        };
89
    }
90
91
    /**
92
     * Add common service objects to the container.
93
     */
94
    protected function _services()
95
    {
96
        $this['config'] = Config::all();
97
98
        $this['db'] = static function ($c) {
99
            $config = $c['config'];
100
            if (empty($config['db.options'])) {
101
                $config['db.options'] = [];
102
            }
103
            if (empty($config['db.driverOptions'])) {
104
                $config['db.driverOptions'] = [];
105
            }
106
            $mongo = new MongoClient($config['db.host'], $config['db.options'], $config['db.driverOptions']);
107
            $mongo->{$config['db.db']}->results->findOne();
108
109
            return $mongo->{$config['db.db']};
110
        };
111
112
        $this['pdo'] = static function ($c) {
113
            if (!class_exists(PDO::class)) {
114
                throw new RuntimeException('Required extension ext-pdo is missing');
115
            }
116
117
            $driver = explode(':', $c['config']['pdo']['dsn'], 2)[0];
118
119
            // check the PDO driver is available
120
            if (!in_array($driver, PDO::getAvailableDrivers(), true)) {
121
                $drivers = implode(',', PDO::getAvailableDrivers()) ?: '(none)';
122
                throw new RuntimeException("Required PDO driver $driver is missing, Available drivers: $drivers");
123
            }
124
125
            $options = [
126
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
127
            ];
128
129
            if ($driver === 'mysql') {
130
                $options[PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET SQL_MODE=ANSI_QUOTES;';
131
            }
132
133
            var_dump($c['config']['pdo']);
0 ignored issues
show
Security Debugging Code introduced by
var_dump($c['config']['pdo']); looks like debug code. Are you sure you do not want to remove it? This might expose sensitive data.
Loading history...
134
            return new PDO(
135
                $c['config']['pdo']['dsn'],
136
                $c['config']['pdo']['user'],
137
                $c['config']['pdo']['pass'],
138
                $options
139
            );
140
        };
141
142
        $this[PdoRepository::class] = static function ($c) {
143
            return new PdoRepository($c['pdo'], $c['config']['pdo']['table']);
144
        };
145
146
        $this['searcher.mongodb'] = static function ($c) {
147
            return new MongoSearcher($c['db']);
148
        };
149
150
        $this['searcher.pdo'] = static function ($c) {
151
            return new PdoSearcher($c[PdoRepository::class]);
152
        };
153
154
        $this['searcher'] = static function ($c) {
155
            $saver = $c['config']['save.handler'];
156
157
            return $c["searcher.$saver"];
158
        };
159
160
        $this['saver.mongodb'] = static function ($c) {
161
            $config = $c['config'];
162
163
            if (!class_exists(Manager::class)) {
164
                throw new RuntimeException('Required extension ext-mongodb missing');
165
            }
166
            $mongo = new MongoClient($config['db.host'], $config['db.options'], $config['db.driverOptions']);
167
            $collection = $mongo->{$config['db.db']}->results;
168
            $collection->findOne();
169
170
            return new Saver\MongoSaver($collection);
171
        };
172
173
        $this['saver.pdo'] = static function ($c) {
174
            return new Saver\PdoSaver($c[PdoRepository::class]);
175
        };
176
177
        $this['saver'] = static function ($c) {
178
            $saver = $c['config']['save.handler'];
179
180
            return new NormalizingSaver($c["saver.$saver"]);
181
        };
182
    }
183
184
    /**
185
     * Add controllers to the DI container.
186
     */
187
    protected function _controllers()
188
    {
189
        $this['watchController'] = $this->factory(static function ($c) {
190
            return new Controller\WatchController($c['app'], $c['searcher']);
191
        });
192
193
        $this['runController'] = $this->factory(static function ($c) {
194
            return new Controller\RunController($c['app'], $c['searcher']);
195
        });
196
197
        $this['customController'] = $this->factory(static function ($c) {
198
            return new Controller\CustomController($c['app'], $c['searcher']);
199
        });
200
201
        $this['waterfallController'] = $this->factory(static function ($c) {
202
            return new Controller\WaterfallController($c['app'], $c['searcher']);
203
        });
204
205
        $this['importController'] = $this->factory(static function ($c) {
206
            return new Controller\ImportController($c['app'], $c['saver'], $c['config']['upload.token']);
207
        });
208
209
        $this['metricsController'] = $this->factory(static function ($c) {
210
            return new Controller\MetricsController($c['app'], $c['searcher']);
211
        });
212
    }
213
}
214