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

SilverStripeCollector::collect()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 18
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 18
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 15
nc 2
nop 0
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 SilverStripe\Admin\LeftAndMain;
11
use SilverStripe\Control\Controller;
12
use SilverStripe\Control\Cookie;
13
use SilverStripe\Control\Session;
14
use SilverStripe\Core\Convert;
15
use SilverStripe\i18n\i18n;
16
use SilverStripe\Security\Member;
17
use SilverStripe\SiteConfig\SiteConfig;
18
use SilverStripe\View\Requirements;
19
20
class SilverStripeCollector extends DataCollector implements Renderable, AssetProvider
21
{
22
    protected static $debug = [];
23
    protected static $controller;
24
    protected static $template_cache_info = [];
25
26
    public function collect()
27
    {
28
        $data = array(
29
            'debugcount' => count(self::$debug),
30
            'debug' => self::$debug,
31
            'session' => self::getSessionData(),
32
            'config' => self::getConfigData(),
33
            'locale' => i18n::get_locale(),
34
            'version' => LeftAndMain::create()->CMSVersion(),
35
            'cookies' => self::getCookieData(),
36
            'parameters' => self::getRequestParameters(),
37
            'requirements' => self::getRequirementsData(),
38
            '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...
39
            'templates' => self::getTemplateData(),
40
            'templateCache' => self::getTemplateCacheInfo()
41
        );
42
        return $data;
43
    }
44
45
    /**
46
     * Returns the names of all the templates rendered.
47
     *
48
     * @return array
49
     */
50
    public static function getTemplateData()
51
    {
52
        $templates = SSViewerProxy::getTemplatesUsed();
53
        return array(
54
            'templates' => $templates,
55
            'count' => count($templates)
56
        );
57
    }
58
59
    public static function getRequirementsData()
60
    {
61
        $backend = Requirements::backend();
62
63
        $requirements = array_merge(
64
            $backend->getCSS(),
65
            $backend->getJavascript()
66
        );
67
68
        $output = [];
69
        foreach ($requirements as $asset => $specs) {
70
            $output[] = $asset . ': ' . Convert::raw2json($specs);
71
        }
72
        return $output;
73
    }
74
75
    public static function getRequestParameters()
76
    {
77
        if (!self::$controller) {
78
            return [];
79
        }
80
        $request = self::$controller->getRequest();
81
82
        $p = [];
83
        foreach ($request->getVars() as $k => $v) {
84
            $p["GET - $k"] = $v;
85
        }
86
        foreach ($request->postVars() as $k => $v) {
87
            $p["POST - $k"] = $v;
88
        }
89
        foreach ($request->params() as $k => $v) {
90
            $p["ROUTE - $k"] = $v;
91
        }
92
        return $p;
93
    }
94
95
    public static function getCookieData()
96
    {
97
        return Cookie::get_all();
98
    }
99
100
    public static function getSessionData()
101
    {
102
        $data = DebugBar::getRequest()->getSession()->getAll();
103
        $filtered = [];
104
105
        // Filter not useful data
106
        foreach ($data as $k => $v) {
107
            if (strpos($k, 'gf_') === 0) {
108
                continue;
109
            }
110
            if ($k === 'PHPDEBUGBAR_STACK_DATA') {
111
                continue;
112
            }
113
            if (is_array($v)) {
114
                $v = json_encode($v, JSON_PRETTY_PRINT);
115
            }
116
            $filtered[$k] = $v;
117
        }
118
        return $filtered;
119
    }
120
121
    public static function getConfigData()
122
    {
123
        return SiteConfig::current_site_config()->toMap();
124
    }
125
126
    /**
127
     * This method will try to matches all messages into a proper array
128
     *
129
     * @param string $data
130
     */
131
    public static function setDebugData($data)
132
    {
133
        $matches = null;
134
135
        preg_match_all("/<p class=\"message warning\">\n(.*?)<\/p>/s", $data, $matches);
136
137
        if (!empty($matches[1])) {
138
            self::$debug = $matches[1];
139
        }
140
    }
141
142
    /**
143
     * @param Controller $controller
144
     * @return $this
145
     */
146
    public function setController($controller)
147
    {
148
        self::$controller = $controller;
149
        return $this;
150
    }
151
152
    /**
153
     * @return Controller
154
     */
155
    public function getController()
156
    {
157
        return self::$controller;
158
    }
159
160
    public function getName()
161
    {
162
        return 'silverstripe';
163
    }
164
165
    public function getWidgets()
166
    {
167
        $name = $this->getName();
168
169
        $userIcon = 'user-times';
170
        $userText = 'Not logged in';
171
        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...
172
            $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...
173
            $memberTag = $member->getTitle() . ' (#' . $member->ID . ')';
174
175
            $userIcon = 'user';
176
            $userText = 'Logged in as ' . $memberTag;
177
178
            // Masquerade integration
179
            if (DebugBar::getRequest()->getSession()->get('Masquerade.Old.loggedInAs')) {
180
                $userIcon = 'user-secret';
181
                $userText = 'Masquerading as member ' . $memberTag;
182
            }
183
        }
184
185
        $widgets = array(
186
            'user' => array(
187
                'icon' => $userIcon,
188
                'tooltip' => $userText,
189
                "default" => "",
190
            ),
191
            "version" => array(
192
                "icon" => "desktop",
193
                "tooltip" => LeftAndMain::create()->CMSVersion(),
194
                "default" => ""
195
            ),
196
            "locale" => array(
197
                "icon" => "globe",
198
                "tooltip" => i18n::get_locale(),
199
                "default" => "",
200
            ),
201
            "session" => array(
202
                "icon" => "archive",
203
                "widget" => "PhpDebugBar.Widgets.VariableListWidget",
204
                "map" => "$name.session",
205
                "default" => "{}"
206
            ),
207
            "cookies" => array(
208
                "icon" => "asterisk",
209
                "widget" => "PhpDebugBar.Widgets.VariableListWidget",
210
                "map" => "$name.cookies",
211
                "default" => "{}"
212
            ),
213
            "parameters" => array(
214
                "icon" => "arrow-right",
215
                "widget" => "PhpDebugBar.Widgets.VariableListWidget",
216
                "map" => "$name.parameters",
217
                "default" => "{}"
218
            ),
219
            "SiteConfig" => array(
220
                "icon" => "gear",
221
                "widget" => "PhpDebugBar.Widgets.VariableListWidget",
222
                "map" => "$name.config",
223
                "default" => "{}"
224
            ),
225
            "requirements" => array(
226
                "icon" => "file-o ",
227
                "widget" => "PhpDebugBar.Widgets.ListWidget",
228
                "map" => "$name.requirements",
229
                "default" => "{}"
230
            ),
231
            'templates' => array(
232
                'icon' => 'edit',
233
                'widget' => 'PhpDebugBar.Widgets.ListWidget',
234
                'map' => "$name.templates.templates",
235
                'default' => '{}'
236
            ),
237
            'templates:badge' => array(
238
                'map' => "$name.templates.count",
239
                'default' => 0
240
            ),
241
            'templateCache' => array(
242
                'icon' => 'asterisk',
243
                'widget' => 'PhpDebugBar.Widgets.ListWidget',
244
                'map' => "$name.templateCache.cache",
245
                'default' => '{}'
246
            ),
247
            'templateCache:badge' => array(
248
                'map' => "$name.templateCache.count",
249
                'default' => 0
250
            )
251
        );
252
253
        if (!empty(self::$debug)) {
254
            $widgets["debug"] = array(
255
                "icon" => "list-alt",
256
                "widget" => "PhpDebugBar.Widgets.ListWidget",
257
                "map" => "$name.debug",
258
                "default" => "[]"
259
            );
260
            $widgets["debug:badge"] = array(
261
                "map" => "$name.debugcount",
262
                "default" => "null"
263
            );
264
        }
265
266
        return $widgets;
267
    }
268
269
    /**
270
     * @return array
271
     */
272 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...
273
    {
274
        return array(
275
            'base_path' => '/' . DEBUGBAR_DIR . '/javascript',
276
            'base_url' => DEBUGBAR_DIR . '/javascript',
277
            'css' => [],
278
            'js' => 'widgets.js',
279
        );
280
    }
281
282
    /**
283
     * Returns a list of partial cache hits and misses as well as the total items contained in the array
284
     * @return array
285
     */
286
    public static function getTemplateCacheInfo()
287
    {
288
        return array(
289
            'count' => count(self::$template_cache_info),
290
            'cache' => self::$template_cache_info
291
        );
292
    }
293
294
    /**
295
     * Adds a cache outcome item to the $template_cache_info collection
296
     * @param $value
297
     */
298
    public static function addTemplateCacheInfo($value)
299
    {
300
        if (!in_array($value, self::$template_cache_info)) {
301
            self::$template_cache_info[] = $value;
302
        }
303
    }
304
}
305