Completed
Pull Request — master (#331)
by Elan
02:10 queued 57s
created

Xhgui_ServiceContainer::_services()   B

Complexity

Conditions 5
Paths 1

Size

Total Lines 86

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 86
rs 7.9943
c 0
b 0
f 0
cc 5
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;
12
use Slim\Views\Twig;
13
use XHGui\Middleware\RenderMiddleware;
14
use XHGui\Searcher\MongoSearcher;
15
use XHGui\Searcher\PdoSearcher;
16
use XHGui\Twig\TwigExtension;
17
18
class ServiceContainer extends Container
19
{
20
    /** @var self */
21
    protected static $_instance;
22
23
    /**
24
     * @return self
25
     */
26
    public static function instance()
27
    {
28
        if (empty(static::$_instance)) {
29
            static::$_instance = new self();
30
        }
31
32
        return static::$_instance;
33
    }
34
35
    public function __construct()
36
    {
37
        parent::__construct();
38
        $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...
39
        $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...
40
        $this->_controllers();
41
    }
42
43
    // Create the Slim app.
44
    protected function _slimApp()
45
    {
46
        $this['view'] = static function ($c) {
47
            $cacheDir = $c['config']['cache'] ?? XHGUI_ROOT_DIR . '/cache';
48
49
            // Configure Twig view for slim
50
            $view = new Twig();
51
52
            $view->twigTemplateDirs = [dirname(__DIR__) . '/templates'];
53
            $view->parserOptions = [
54
                'charset' => 'utf-8',
55
                'cache' => $cacheDir,
56
                'auto_reload' => true,
57
                'strict_variables' => false,
58
                'autoescape' => true,
59
            ];
60
61
            return $view;
62
        };
63
64
        $this['app'] = static function ($c) {
65
            if ($c['config']['timezone']) {
66
                date_default_timezone_set($c['config']['timezone']);
67
            }
68
69
            $app = new Slim($c['config']);
70
71
            // Enable cookie based sessions
72
            $app->add(new SessionCookie([
73
                'httponly' => true,
74
            ]));
75
76
            // Add renderer.
77
            $app->add(new RenderMiddleware());
78
79
            $view = $c['view'];
80
            $view->parserExtensions = [
81
                new TwigExtension($app),
82
            ];
83
            $app->view($view);
84
85
            return $app;
86
        };
87
    }
88
89
    /**
90
     * Add common service objects to the container.
91
     */
92
    protected function _services()
93
    {
94
        $this['config'] = Config::all();
95
96
        $this['db'] = static function ($c) {
97
            $config = $c['config'];
98
            if (empty($config['db.options'])) {
99
                $config['db.options'] = [];
100
            }
101
            if (empty($config['db.driverOptions'])) {
102
                $config['db.driverOptions'] = [];
103
            }
104
            $mongo = new MongoClient($config['db.host'], $config['db.options'], $config['db.driverOptions']);
105
            $mongo->{$config['db.db']}->results->findOne();
106
107
            return $mongo->{$config['db.db']};
108
        };
109
110
        $this['pdo'] = static function ($c) {
111
            $options = [
112
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
113
            ];
114
115
            return new PDO(
116
                $c['config']['pdo']['dsn'],
117
                $c['config']['pdo']['user'],
118
                $c['config']['pdo']['pass'],
119
                $options
120
            );
121
        };
122
123
        $this['searcher.mongodb'] = static function ($c) {
124
            return new MongoSearcher($c['db']);
125
        };
126
127
        $this['searcher.pdo'] = static function ($c) {
128
            return new PdoSearcher($c['pdo'], $c['config']['pdo']['table']);
129
        };
130
131
        $this['searcher'] = static function ($c) {
132
            $saver = $c['config']['save.handler'];
133
134
            return $c["searcher.$saver"];
135
        };
136
137
        $this['saver.mongodb'] = static function ($c) {
138
            $config = $c['config'];
139
140
            if (!class_exists(Manager::class)) {
141
                throw new RuntimeException("Required extension ext-mongodb missing");
142
            }
143
            $mongo = new MongoClient($config['db.host'], $config['db.options'], $config['db.driverOptions']);
144
            $collection = $mongo->{$config['db.db']}->results;
145
            $collection->findOne();
146
147
            return new Saver\MongoSaver($collection);
148
        };
149
150
        $this['saver.pdo'] = static function ($c) {
151
            $config = $c['config'];
152
153
            if (!class_exists(PDO::class)) {
154
                throw new RuntimeException("Required extension ext-pdo is missing");
155
            }
156
157
            $options = [
158
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
159
            ];
160
161
            return new Saver\PdoSaver(
162
                new PDO(
163
                    $config['pdo']['dsn'],
164
                    $config['pdo']['user'],
165
                    $config['pdo']['pass'],
166
                    $options
167
                ),
168
                $config['pdo']['table']
169
            );
170
        };
171
172
        $this['saver'] = static function ($c) {
173
            $saver = $c['config']['save.handler'];
174
175
            return $c["saver.$saver"];
176
        };
177
    }
178
179
    /**
180
     * Add controllers to the DI container.
181
     */
182
    protected function _controllers()
183
    {
184
        $this['watchController'] = $this->factory(static function ($c) {
185
            return new Controller\WatchController($c['app'], $c['searcher']);
186
        });
187
188
        $this['runController'] = $this->factory(static function ($c) {
189
            return new Controller\RunController($c['app'], $c['searcher']);
190
        });
191
192
        $this['customController'] = $this->factory(static function ($c) {
193
            return new Controller\CustomController($c['app'], $c['searcher']);
194
        });
195
196
        $this['waterfallController'] = $this->factory(static function ($c) {
197
            return new Controller\WaterfallController($c['app'], $c['searcher']);
198
        });
199
200
        $this['importController'] = $this->factory(static function ($c) {
201
            return new Controller\ImportController($c['app'], $c['saver'], $c['config']['upload.token']);
202
        });
203
204
        $this['metricsController'] = $this->factory(static function ($c) {
205
            return new Controller\MetricsController($c['app'], $c['searcher']);
206
        });
207
    }
208
}
209