Test Failed
Push — develop ( 5be0e5...3f5c00 )
by Paul
14:23
created

EnqueueAdminAssets::inlineScript()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 67
Code Lines 55

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

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