Completed
Pull Request — master (#78)
by Franco
01:37
created

SilverStripeCollector   A

Complexity

Total Complexity 29

Size/Duplication

Total Lines 274
Duplicated Lines 3.28 %

Coupling/Cohesion

Components 1
Dependencies 12

Importance

Changes 0
Metric Value
wmc 29
lcom 1
cbo 12
dl 9
loc 274
rs 10
c 0
b 0
f 0

14 Methods

Rating   Name   Duplication   Size   Complexity  
A getAssets() 9 9 1
A collect() 0 18 2
A getTemplateData() 0 8 1
A getRequirementsData() 0 15 2
B getRequestParameters() 0 19 5
A getCookieData() 0 4 1
B getSessionData() 0 20 5
A getConfigData() 0 4 1
A setDebugData() 0 10 2
A setController() 0 5 1
A getController() 0 4 1
A getName() 0 4 1
B getWidgets() 0 103 4
A getPartialCacheInfo() 0 8 2

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace LeKoala\DebugBar\Collector;
4
5
use DebugBar\DataCollector\AssetProvider;
6
use DebugBar\DataCollector\DataCollector;
7
use DebugBar\DataCollector\Renderable;
8
use LeKoala\DebugBar\DebugBar;
9
use LeKoala\DebugBar\Proxy\SSViewerProxy;
10
use Psr\SimpleCache\CacheInterface;
11
use SilverStripe\Admin\LeftAndMain;
12
use SilverStripe\Control\Controller;
13
use SilverStripe\Control\Cookie;
14
use SilverStripe\Control\Session;
15
use SilverStripe\Core\Convert;
16
use SilverStripe\Core\Injector\Injector;
17
use SilverStripe\i18n\i18n;
18
use SilverStripe\Security\Member;
19
use SilverStripe\SiteConfig\SiteConfig;
20
use SilverStripe\View\Requirements;
21
22
class SilverStripeCollector extends DataCollector implements Renderable, AssetProvider
23
{
24
    protected static $debug = [];
25
    protected static $controller;
26
27
    public function collect()
28
    {
29
        $data = array(
30
            'debugcount' => count(self::$debug),
31
            'debug' => self::$debug,
32
            'session' => self::getSessionData(),
33
            'config' => self::getConfigData(),
34
            'locale' => i18n::get_locale(),
35
            'version' => LeftAndMain::create()->CMSVersion(),
36
            'cookies' => self::getCookieData(),
37
            'parameters' => self::getRequestParameters(),
38
            'requirements' => self::getRequirementsData(),
39
            'user' => Member::currentUserID() ? Member::currentUser()->Title : 'Not logged in',
0 ignored issues
show
Deprecated Code introduced by
The method SilverStripe\Security\Member::currentUserID() has been deprecated with message: 5.0.0 use Security::getCurrentUser()

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
Deprecated Code introduced by
The method SilverStripe\Security\Member::currentUser() has been deprecated with message: 5.0.0 use Security::getCurrentUser()

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
40
            'templates' => self::getTemplateData(),
41
            'partialCache' => self::getPartialCacheInfo()
42
        );
43
        return $data;
44
    }
45
46
    /**
47
     * Returns the names of all the templates rendered.
48
     *
49
     * @return array
50
     */
51
    public static function getTemplateData()
52
    {
53
        $templates = SSViewerProxy::getTemplatesUsed();
54
        return array(
55
            'templates' => $templates,
56
            'count' => count($templates)
57
        );
58
    }
59
60
    public static function getRequirementsData()
61
    {
62
        $backend = Requirements::backend();
63
64
        $requirements = array_merge(
65
            $backend->getCSS(),
66
            $backend->getJavascript()
67
        );
68
69
        $output = [];
70
        foreach ($requirements as $asset => $specs) {
71
            $output[] = $asset . ': ' . Convert::raw2json($specs);
72
        }
73
        return $output;
74
    }
75
76
    public static function getRequestParameters()
77
    {
78
        if (!self::$controller) {
79
            return [];
80
        }
81
        $request = self::$controller->getRequest();
82
83
        $p = [];
84
        foreach ($request->getVars() as $k => $v) {
85
            $p["GET - $k"] = $v;
86
        }
87
        foreach ($request->postVars() as $k => $v) {
88
            $p["POST - $k"] = $v;
89
        }
90
        foreach ($request->params() as $k => $v) {
91
            $p["ROUTE - $k"] = $v;
92
        }
93
        return $p;
94
    }
95
96
    public static function getCookieData()
97
    {
98
        return Cookie::get_all();
99
    }
100
101
    public static function getSessionData()
102
    {
103
        $data = DebugBar::getRequest()->getSession()->getAll();
104
        $filtered = [];
105
106
        // Filter not useful data
107
        foreach ($data as $k => $v) {
108
            if (strpos($k, 'gf_') === 0) {
109
                continue;
110
            }
111
            if ($k === 'PHPDEBUGBAR_STACK_DATA') {
112
                continue;
113
            }
114
            if (is_array($v)) {
115
                $v = json_encode($v, JSON_PRETTY_PRINT);
116
            }
117
            $filtered[$k] = $v;
118
        }
119
        return $filtered;
120
    }
121
122
    public static function getConfigData()
123
    {
124
        return SiteConfig::current_site_config()->toMap();
125
    }
126
127
    /**
128
     * This method will try to matches all messages into a proper array
129
     *
130
     * @param string $data
131
     */
132
    public static function setDebugData($data)
133
    {
134
        $matches = null;
135
136
        preg_match_all("/<p class=\"message warning\">\n(.*?)<\/p>/s", $data, $matches);
137
138
        if (!empty($matches[1])) {
139
            self::$debug = $matches[1];
140
        }
141
    }
142
143
    /**
144
     * @param Controller $controller
145
     * @return $this
146
     */
147
    public function setController($controller)
148
    {
149
        self::$controller = $controller;
150
        return $this;
151
    }
152
153
    /**
154
     * @return Controller
155
     */
156
    public function getController()
157
    {
158
        return self::$controller;
159
    }
160
161
    public function getName()
162
    {
163
        return 'silverstripe';
164
    }
165
166
    public function getWidgets()
167
    {
168
        $name = $this->getName();
169
170
        $userIcon = 'user-times';
171
        $userText = 'Not logged in';
172
        if (Member::currentUserID()) {
0 ignored issues
show
Deprecated Code introduced by
The method SilverStripe\Security\Member::currentUserID() has been deprecated with message: 5.0.0 use Security::getCurrentUser()

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
173
            $member = Member::currentUser();
0 ignored issues
show
Deprecated Code introduced by
The method SilverStripe\Security\Member::currentUser() has been deprecated with message: 5.0.0 use Security::getCurrentUser()

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
174
            $memberTag = $member->getTitle() . ' (#' . $member->ID . ')';
175
176
            $userIcon = 'user';
177
            $userText = 'Logged in as ' . $memberTag;
178
179
            // Masquerade integration
180
            if (DebugBar::getRequest()->getSession()->get('Masquerade.Old.loggedInAs')) {
181
                $userIcon = 'user-secret';
182
                $userText = 'Masquerading as member ' . $memberTag;
183
            }
184
        }
185
186
        $widgets = array(
187
            'user' => array(
188
                'icon' => $userIcon,
189
                'tooltip' => $userText,
190
                "default" => "",
191
            ),
192
            "version" => array(
193
                "icon" => "desktop",
194
                "tooltip" => LeftAndMain::create()->CMSVersion(),
195
                "default" => ""
196
            ),
197
            "locale" => array(
198
                "icon" => "globe",
199
                "tooltip" => i18n::get_locale(),
200
                "default" => "",
201
            ),
202
            "session" => array(
203
                "icon" => "archive",
204
                "widget" => "PhpDebugBar.Widgets.VariableListWidget",
205
                "map" => "$name.session",
206
                "default" => "{}"
207
            ),
208
            "cookies" => array(
209
                "icon" => "asterisk",
210
                "widget" => "PhpDebugBar.Widgets.VariableListWidget",
211
                "map" => "$name.cookies",
212
                "default" => "{}"
213
            ),
214
            "parameters" => array(
215
                "icon" => "arrow-right",
216
                "widget" => "PhpDebugBar.Widgets.VariableListWidget",
217
                "map" => "$name.parameters",
218
                "default" => "{}"
219
            ),
220
            "SiteConfig" => array(
221
                "icon" => "gear",
222
                "widget" => "PhpDebugBar.Widgets.VariableListWidget",
223
                "map" => "$name.config",
224
                "default" => "{}"
225
            ),
226
            "requirements" => array(
227
                "icon" => "file-o ",
228
                "widget" => "PhpDebugBar.Widgets.ListWidget",
229
                "map" => "$name.requirements",
230
                "default" => "{}"
231
            ),
232
            'templates' => array(
233
                'icon' => 'edit',
234
                'widget' => 'PhpDebugBar.Widgets.ListWidget',
235
                'map' => "$name.templates.templates",
236
                'default' => '{}'
237
            ),
238
            'templates:badge' => array(
239
                'map' => "$name.templates.count",
240
                'default' => 0
241
            ),
242
            'partialCache' => array(
243
                'icon' => 'asterisk',
244
                'widget' => 'PhpDebugBar.Widgets.ConfigWidget',
245
                'map' => "$name.partialCache.calls",
246
                'default' => '{}'
247
            ),
248
            'partialCache:badge' => array(
249
                'map' => "$name.partialCache.count",
250
                'default' => 0
251
            )
252
        );
253
254
        if (!empty(self::$debug)) {
255
            $widgets["debug"] = array(
256
                "icon" => "list-alt",
257
                "widget" => "PhpDebugBar.Widgets.ListWidget",
258
                "map" => "$name.debug",
259
                "default" => "[]"
260
            );
261
            $widgets["debug:badge"] = array(
262
                "map" => "$name.debugcount",
263
                "default" => "null"
264
            );
265
        }
266
267
        return $widgets;
268
    }
269
270
    /**
271
     * @return array
272
     */
273 View Code Duplication
    public function getAssets()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
274
    {
275
        return array(
276
            'base_path' => '/' . DEBUGBAR_DIR . '/javascript',
277
            'base_url' => DEBUGBAR_DIR . '/javascript',
278
            'css' => [],
279
            'js' => 'widgets.js',
280
        );
281
    }
282
283
    /**
284
     * Returns a list of partial cache hits and misses as well as the total items contained in the array
285
     * @return array
286
     */
287
    public static function getPartialCacheInfo()
288
    {
289
        $templates = (Injector::inst()->get(CacheInterface::class . '.backend')->templateCache) ?: array();
290
        return array(
291
            'count' => count($templates),
292
            'calls' => $templates,
293
        );
294
    }
295
}
296