Passed
Push — master ( 6fa460...6bbb33 )
by Paul
18:19 queued 07:35
created

EnqueueAdminAssets::inlineScript()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 68
Code Lines 56

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
eloc 56
c 0
b 0
f 0
dl 0
loc 68
ccs 0
cts 68
cp 0
rs 8.9599
cc 2
nc 2
nop 0
crap 6

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 GeminiLabs\SiteReviews\Commands;
4
5
use GeminiLabs\SiteReviews\Contracts\CommandContract as Contract;
6
use GeminiLabs\SiteReviews\Controllers\ListTableColumns\ColumnFilterAssignedPost;
7
use GeminiLabs\SiteReviews\Controllers\ListTableColumns\ColumnFilterAssignedUser;
8
use GeminiLabs\SiteReviews\Controllers\ListTableColumns\ColumnFilterAuthor;
9
use GeminiLabs\SiteReviews\Helper;
10
use GeminiLabs\SiteReviews\Helpers\Arr;
11
use GeminiLabs\SiteReviews\Helpers\Str;
12
use GeminiLabs\SiteReviews\Modules\Rating;
13
use GeminiLabs\SiteReviews\Shortcodes\SiteReviewsFormShortcode;
14
use GeminiLabs\SiteReviews\Shortcodes\SiteReviewsShortcode;
15
use GeminiLabs\SiteReviews\Shortcodes\SiteReviewsSummaryShortcode;
16
17
class EnqueueAdminAssets implements Contract
18
{
19
    public $pointers;
20
21
    public function __construct()
22
    {
23
        $this->pointers = $this->generatePointers([[
24
            'content' => _x('You can pin exceptional reviews so that they are always shown first.', 'admin-text', 'site-reviews'),
25
            'id' => 'glsr-pointer-pinned',
26
            'position' => [
27
                'edge' => 'right',
28
                'align' => 'middle',
29
            ],
30
            'screen' => glsr()->post_type,
31
            'target' => '#misc-pub-pinned',
32
            'title' => _x('Pin Your Reviews', 'admin-text', 'site-reviews'),
33
        ]]);
34
    }
35
36
    /**
37
     * @return void
38
     */
39
    public function handle()
40
    {
41
        $this->enqueueAssets();
42
    }
43
44
    /**
45
     * @return void
46
     */
47
    public function enqueueAssets()
48
    {
49
        if (!$this->isCurrentScreen()) {
50
            return;
51
        }
52
        wp_enqueue_style('wp-color-picker'); 
53
        wp_enqueue_style(
54
            glsr()->id.'/admin',
55
            glsr()->url('assets/styles/admin/admin.css'),
56
            ['wp-list-reusable-blocks'], // load the :root admin theme colors
57
            glsr()->version
58
        );
59
        wp_enqueue_script(
60
            glsr()->id.'/admin',
61
            glsr()->url('assets/scripts/'.glsr()->id.'-admin.js'),
62
            $this->getDependencies(),
63
            glsr()->version,
64
            false
65
        );
66
        if (!empty($this->pointers)) {
67
            wp_enqueue_style('wp-pointer');
68
            wp_enqueue_script('wp-pointer');
69
        }
70
        wp_add_inline_script(glsr()->id.'/admin', $this->inlineScript(), 'before');
71
        wp_add_inline_script(glsr()->id.'/admin', glsr()->filterString('enqueue/admin/inline-script/after', ''));
72
    }
73
74
    /**
75
     * @return string
76
     */
77
    public function inlineScript()
78
    {
79
        $licenses = array_filter(Arr::consolidate(glsr_get_option('licenses')));
80
        $variables = [
81
            'action' => glsr()->prefix.'action',
82
            'addons' => [],
83
            'addonsurl' => glsr_admin_url('addons'),
84
            'ajaxurl' => admin_url('admin-ajax.php'),
85
            'displayoptions' => [
86
                'site_reviews' => glsr(SiteReviewsShortcode::class)->getDisplayOptions(),
87
                'site_reviews_form' => glsr(SiteReviewsFormShortcode::class)->getDisplayOptions(),
88
                'site_reviews_summary' => glsr(SiteReviewsSummaryShortcode::class)->getDisplayOptions(),
89
            ],
90
            'filters' => [
91
                'assigned_post' => glsr(ColumnFilterAssignedPost::class)->options(),
92
                'assigned_user' => glsr(ColumnFilterAssignedUser::class)->options(),
93
                'author' => glsr(ColumnFilterAuthor::class)->options(),
94
                'post_author' => (object) [
95
                    '' => sprintf('&mdash; %s &mdash;', _x('No Change', 'admin-text', 'site-reviews')),
96
                    0 => _x('No Author', 'admin-text', 'site-reviews'),
97
                ],
98
                'post_author_override' => (object) [
99
                    0 => _x('Author Unknown', 'admin-text', 'site-reviews'),
100
                ],
101
            ],
102
            'hideoptions' => [
103
                'site_reviews' => glsr(SiteReviewsShortcode::class)->getHideOptions(),
104
                'site_reviews_form' => glsr(SiteReviewsFormShortcode::class)->getHideOptions(),
105
                'site_reviews_summary' => glsr(SiteReviewsSummaryShortcode::class)->getHideOptions(),
106
            ],
107
            'isLicensed' => Helper::ifTrue(empty($licenses), 'no', 'yes'),
108
            'maxrating' => glsr()->constant('MAX_RATING', Rating::class),
109
            'minrating' => glsr()->constant('MIN_RATING', Rating::class),
110
            'nameprefix' => glsr()->id,
111
            'nonce' => [
112
                'clear-console' => wp_create_nonce('clear-console'),
113
                'console-level' => wp_create_nonce('console-level'),
114
                'fetch-console' => wp_create_nonce('fetch-console'),
115
                'filter-assigned_post' => wp_create_nonce('filter-assigned_post'),
116
                'filter-assigned_user' => wp_create_nonce('filter-assigned_user'),
117
                'filter-author' => wp_create_nonce('filter-author'),
118
                'mce-shortcode' => wp_create_nonce('mce-shortcode'),
119
                'search-posts' => wp_create_nonce('search-posts'),
120
                'search-translations' => wp_create_nonce('search-translations'),
121
                'search-users' => wp_create_nonce('search-users'),
122
                'sync-reviews' => wp_create_nonce('sync-reviews'),
123
                'toggle-filters' => wp_create_nonce('toggle-filters'),
124
                'toggle-pinned' => wp_create_nonce('toggle-pinned'),
125
                'toggle-status' => wp_create_nonce('toggle-status'),
126
            ],
127
            'pointers' => $this->pointers,
128
            'premiumurl' => 'https://niftyplugins.com/plugins/site-reviews-premium/',
129
            'shortcodes' => [],
130
            'text' => [
131
                'premium' => _x('Try Premium', 'admin-text', 'site-reviews'),
132
                'rate' => _x('Please rate %s on %s and help us spread the word. Thank you so much!', 'admin-text', 'site-reviews'),
133
                'rollback_error' => _x('Rollback failed', 'admin-text', 'site-reviews'),
134
                'searching' => _x('Searching...', 'admin-text', 'site-reviews'),
135
            ],
136
            'tinymce' => [
137
                'glsr_shortcode' => glsr()->url('assets/scripts/mce-plugin.js'),
138
            ],
139
        ];
140
        if (user_can_richedit()) {
141
            $variables['shortcodes'] = $this->localizeShortcodes();
142
        }
143
        $variables = glsr()->filterArray('enqueue/admin/localize', $variables);
144
        return $this->buildInlineScript($variables);
145
    }
146
147
    /**
148
     * @return string
149
     */
150
    protected function buildInlineScript(array $variables)
151
    {
152
        $script = 'window.hasOwnProperty("GLSR")||(window.GLSR={});';
153
        foreach ($variables as $key => $value) {
154
            $script .= sprintf('GLSR.%s=%s;', $key, json_encode($value, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
155
        }
156
        $pattern = '/\"([a-zA-Z]+)\"(:[{\[\"])/'; // remove unnecessary quotes surrounding object keys
157
        $optimizedScript = preg_replace($pattern, '$1$2', $script);
158
        return glsr()->filterString('enqueue/admin/inline-script', $optimizedScript, $script, $variables);
159
    }
160
161
    /**
162
     * @return array
163
     */
164
    protected function getDependencies()
165
    {
166
        $dependencies = glsr()->filterArray('enqueue/admin/dependencies', []);
167
        $dependencies = array_merge($dependencies, [
168
            'jquery', 'jquery-ui-sortable', 'underscore', 'wp-color-picker', 'wp-util',
169
        ]);
170
        return $dependencies;
171
    }
172
173
    /**
174
     * @return array
175
     */
176
    protected function generatePointer(array $pointer)
177
    {
178
        return [
179
            'id' => $pointer['id'],
180
            'options' => [
181
                'content' => '<h3>'.$pointer['title'].'</h3><p>'.$pointer['content'].'</p>',
182
                'position' => $pointer['position'],
183
            ],
184
            'screen' => $pointer['screen'],
185
            'target' => $pointer['target'],
186
        ];
187
    }
188
189
    /**
190
     * @return array
191
     */
192
    protected function generatePointers(array $pointers)
193
    {
194
        $dismissedPointers = get_user_meta(get_current_user_id(), 'dismissed_wp_pointers', true);
195
        $dismissedPointers = explode(',', (string) $dismissedPointers);
196
        $generatedPointers = [];
197
        foreach ($pointers as $pointer) {
198
            if ($pointer['screen'] != glsr_current_screen()->id) {
199
                continue;
200
            }
201
            if (in_array($pointer['id'], $dismissedPointers)) {
202
                continue;
203
            }
204
            $generatedPointers[] = $this->generatePointer($pointer);
205
        }
206
        return $generatedPointers;
207
    }
208
209
    /**
210
     * @return bool
211
     */
212
    protected function isCurrentScreen()
213
    {
214
        $screen = glsr_current_screen();
215
        $screenIds = [
216
            'dashboard',
217
            'dashboard_page_'.glsr()->id.'-welcome',
218
            'plugins_page_'.glsr()->id,
219
            'widgets',
220
        ];
221
        return Str::startsWith(glsr()->post_type, $screen->post_type)
222
            || in_array($screen->id, $screenIds)
223
            || 'post' == $screen->base;
224
    }
225
226
    /**
227
     * @return array
228
     */
229
    protected function localizeShortcodes()
230
    {
231
        $variables = [];
232
        foreach (glsr()->retrieveAs('array', 'mce', []) as $tag => $args) {
233
            if (empty($args['required'])) {
234
                continue;
235
            }
236
            $variables[$tag] = $args['required'];
237
        }
238
        return $variables;
239
    }
240
}
241