Passed
Push — master ( 2009cc...a406f9 )
by Paul
04:50 queued 21s
created

ListTableController::saveBulkEditFields()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 6

Importance

Changes 0
Metric Value
cc 4
eloc 5
c 0
b 0
f 0
nc 3
nop 1
dl 0
loc 8
ccs 3
cts 6
cp 0.5
crap 6
rs 10
1
<?php
2
3
namespace GeminiLabs\SiteReviews\Controllers;
4
5
use GeminiLabs\SiteReviews\Application;
6
use GeminiLabs\SiteReviews\Controllers\ListTableController\Columns;
7
use GeminiLabs\SiteReviews\Database;
8
use GeminiLabs\SiteReviews\Helpers\Arr;
9
use GeminiLabs\SiteReviews\Helpers\Str;
10
use GeminiLabs\SiteReviews\Modules\Html\Builder;
11
use WP_Post;
12
use WP_Query;
13
use WP_Screen;
14
15
class ListTableController extends Controller
16
{
17
    /**
18
     * @return void
19
     * @action admin_action_approve
20
     */
21
    public function approve()
22
    {
23
        if (Application::ID != filter_input(INPUT_GET, 'plugin')) {
24
            return;
25
        }
26
        check_admin_referer('approve-review_'.($postId = $this->getPostId()));
27
        wp_update_post([
28
            'ID' => $postId,
29
            'post_status' => 'publish',
30
        ]);
31
        wp_safe_redirect(wp_get_referer());
32
        exit;
33
    }
34
35
    /**
36
     * @param array $messages
37
     * @return array
38
     * @filter bulk_post_updated_messages
39
     */
40
    public function filterBulkUpdateMessages($messages, array $counts)
41
    {
42
        $messages = Arr::consolidateArray($messages);
43
        $messages[Application::POST_TYPE] = [
44
            'updated' => _n('%s review updated.', '%s reviews updated.', $counts['updated'], 'site-reviews'),
45
            'locked' => _n('%s review not updated, somebody is editing it.', '%s reviews not updated, somebody is editing them.', $counts['locked'], 'site-reviews'),
46
            'deleted' => _n('%s review permanently deleted.', '%s reviews permanently deleted.', $counts['deleted'], 'site-reviews'),
47
            'trashed' => _n('%s review moved to the Trash.', '%s reviews moved to the Trash.', $counts['trashed'], 'site-reviews'),
48
            'untrashed' => _n('%s review restored from the Trash.', '%s reviews restored from the Trash.', $counts['untrashed'], 'site-reviews'),
49
        ];
50
        return $messages;
51
    }
52
53
    /**
54
     * @param array $columns
55
     * @return array
56
     * @filter manage_.Application::POST_TYPE._posts_columns
57
     */
58
    public function filterColumnsForPostType($columns)
59
    {
60
        $columns = Arr::consolidateArray($columns);
61
        $postTypeColumns = glsr()->postTypeColumns[Application::POST_TYPE];
62
        foreach ($postTypeColumns as $key => &$value) {
63
            if (!array_key_exists($key, $columns) || !empty($value)) {
64
                continue;
65
            }
66
            $value = $columns[$key];
67
        }
68
        if (count(glsr(Database::class)->getReviewsMeta('review_type')) < 2) {
69
            unset($postTypeColumns['review_type']);
70
        }
71
        return array_filter($postTypeColumns, 'strlen');
72
    }
73
74
    /**
75
     * @param string $status
76
     * @param WP_Post $post
77
     * @return string
78
     * @filter post_date_column_status
79
     */
80
    public function filterDateColumnStatus($status, $post)
81
    {
82
        if (Application::POST_TYPE == Arr::get($post, 'post_type')) {
83
            $status = __('Submitted', 'site-reviews');
84
        }
85
        return $status;
86
    }
87
88
    /**
89
     * @param array $hidden
90
     * @param WP_Screen $post
91
     * @return array
92
     * @filter default_hidden_columns
93
     */
94
    public function filterDefaultHiddenColumns($hidden, $screen)
95
    {
96
        if (Arr::get($screen, 'id') == 'edit-'.Application::POST_TYPE) {
97
            $hidden = Arr::consolidateArray($hidden);
98
            $hidden = array_unique(array_merge($hidden, [
99
                'email', 'ip_address', 'response', 'reviewer',
100
            ]));
101
        }
102
        return $hidden;
103
    }
104
105
    /**
106
     * @param array $postStates
107
     * @param WP_Post $post
108
     * @return array
109
     * @filter display_post_states
110
     */
111
    public function filterPostStates($postStates, $post)
112
    {
113
        $postStates = Arr::consolidateArray($postStates);
114
        if (Application::POST_TYPE == Arr::get($post, 'post_type') && array_key_exists('pending', $postStates)) {
115
            $postStates['pending'] = __('Unapproved', 'site-reviews');
116
        }
117
        return $postStates;
118
    }
119
120
    /**
121
     * @param array $actions
122
     * @param WP_Post $post
123
     * @return array
124
     * @filter post_row_actions
125
     */
126
    public function filterRowActions($actions, $post)
127
    {
128
        if (Application::POST_TYPE != Arr::get($post, 'post_type') || 'trash' == $post->post_status) {
129
            return $actions;
130
        }
131
        unset($actions['inline hide-if-no-js']); //Remove Quick-edit
132
        $rowActions = [
133
            'approve' => esc_attr__('Approve', 'site-reviews'),
134
            'unapprove' => esc_attr__('Unapprove', 'site-reviews'),
135
        ];
136
        $newActions = [];
137
        foreach ($rowActions as $key => $text) {
138
            $newActions[$key] = glsr(Builder::class)->a($text, [
139
                'aria-label' => sprintf(esc_attr_x('%s this review', 'Approve the review', 'site-reviews'), $text),
140
                'class' => 'glsr-change-status',
141
                'href' => wp_nonce_url(
142
                    admin_url('post.php?post='.$post->ID.'&action='.$key.'&plugin='.Application::ID),
143
                    $key.'-review_'.$post->ID
144
                ),
145
            ]);
146
        }
147
        return $newActions + Arr::consolidateArray($actions);
148
    }
149
150
    /**
151
     * @param array $columns
152
     * @return array
153
     * @filter manage_edit-.Application::POST_TYPE._sortable_columns
154
     */
155
    public function filterSortableColumns($columns)
156
    {
157
        $columns = Arr::consolidateArray($columns);
158
        $postTypeColumns = glsr()->postTypeColumns[Application::POST_TYPE];
159
        unset($postTypeColumns['cb']);
160
        foreach ($postTypeColumns as $key => $value) {
161
            if (Str::startsWith('taxonomy', $key)) {
162
                continue;
163
            }
164
            $columns[$key] = $key;
165
        }
166
        return $columns;
167
    }
168
169
    /**
170
     * Customize the post_type status text.
171
     * @param string $translation
172
     * @param string $single
173
     * @param string $plural
174
     * @param int $number
175
     * @param string $domain
176
     * @return string
177
     * @filter ngettext
178
     */
179 1
    public function filterStatusText($translation, $single, $plural, $number, $domain)
180
    {
181 1
        if ($this->canModifyTranslation($domain)) {
182
            $strings = [
183
                'Published' => __('Approved', 'site-reviews'),
184
                'Pending' => __('Unapproved', 'site-reviews'),
185
            ];
186
            foreach ($strings as $search => $replace) {
187
                if (false === strpos($single, $search)) {
188
                    continue;
189
                }
190
                $translation = $this->getTranslation([
191
                    'number' => $number,
192
                    'plural' => str_replace($search, $replace, $plural),
193
                    'single' => str_replace($search, $replace, $single),
194
                ]);
195
            }
196
        }
197 1
        return $translation;
198
    }
199
200
    /**
201
     * @param string $columnName
202
     * @param string $postType
203
     * @return void
204
     * @action bulk_edit_custom_box
205
     */
206
    public function renderBulkEditFields($columnName, $postType)
207
    {
208
        if ('assigned_to' == $columnName && Application::POST_TYPE == $postType) {
209
            glsr()->render('partials/editor/bulk-edit-assigned-to');
210
        }
211
    }
212
213
    /**
214
     * @param string $postType
215
     * @return void
216
     * @action restrict_manage_posts
217
     */
218
    public function renderColumnFilters($postType)
219
    {
220
        glsr(Columns::class)->renderFilters($postType);
221
    }
222
223
    /**
224
     * @param string $column
225
     * @param string $postId
226
     * @return void
227
     * @action manage_posts_custom_column
228
     */
229
    public function renderColumnValues($column, $postId)
230
    {
231
        glsr(Columns::class)->renderValues($column, $postId);
232
    }
233
234
    /**
235
     * @param int $postId
236
     * @return void
237
     * @action save_post_.Application::POST_TYPE
238
     */
239 1
    public function saveBulkEditFields($postId)
240
    {
241 1
        if (!current_user_can('edit_posts')) {
242 1
            return;
243
        }
244
        $assignedTo = filter_input(INPUT_GET, 'assigned_to');
245
        if ($assignedTo && get_post($assignedTo)) {
246
            glsr(Database::class)->update($postId, 'assigned_to', $assignedTo);
247
        }
248
    }
249
250
    /**
251
     * @return void
252
     * @action pre_get_posts
253
     */
254 1
    public function setQueryForColumn(WP_Query $query)
255
    {
256 1
        if (!$this->hasPermission($query)) {
257 1
            return;
258
        }
259
        $this->setMetaQuery($query, [
260
            'rating', 'review_type',
261
        ]);
262
        $this->setOrderby($query);
263
    }
264
265
    /**
266
     * @return void
267
     * @action admin_action_unapprove
268
     */
269
    public function unapprove()
270
    {
271
        if (Application::ID != filter_input(INPUT_GET, 'plugin')) {
272
            return;
273
        }
274
        check_admin_referer('unapprove-review_'.($postId = $this->getPostId()));
275
        wp_update_post([
276
            'ID' => $postId,
277
            'post_status' => 'pending',
278
        ]);
279
        wp_safe_redirect(wp_get_referer());
280
        exit;
281
    }
282
283
    /**
284
     * Check if the translation string can be modified.
285
     * @param string $domain
286
     * @return bool
287
     */
288 1
    protected function canModifyTranslation($domain = 'default')
289
    {
290 1
        $screen = glsr_current_screen();
291 1
        return 'default' == $domain
292 1
            && 'edit' == $screen->base
293 1
            && Application::POST_TYPE == $screen->post_type;
294
    }
295
296
    /**
297
     * Get the modified translation string.
298
     * @return string
299
     */
300
    protected function getTranslation(array $args)
301
    {
302
        $defaults = [
303
            'number' => 0,
304
            'plural' => '',
305
            'single' => '',
306
            'text' => '',
307
        ];
308
        $args = (object) wp_parse_args($args, $defaults);
309
        $translations = get_translations_for_domain(Application::ID);
310
        return $args->text
311
            ? $translations->translate($args->text)
312
            : $translations->translate_plural($args->single, $args->plural, $args->number);
313
    }
314
315
    /**
316
     * @return bool
317
     */
318 1
    protected function hasPermission(WP_Query $query)
319
    {
320 1
        global $pagenow;
321 1
        return is_admin()
322 1
            && $query->is_main_query()
323 1
            && Application::POST_TYPE == $query->get('post_type')
324 1
            && 'edit.php' == $pagenow;
325
    }
326
327
    /**
328
     * @return void
329
     */
330
    protected function setMetaQuery(WP_Query $query, array $metaKeys)
331
    {
332
        foreach ($metaKeys as $key) {
333
            if (!($value = filter_input(INPUT_GET, $key))) {
334
                continue;
335
            }
336
            $metaQuery = (array) $query->get('meta_query');
337
            $metaQuery[] = [
338
                'key' => Str::prefix('_', $key, '_'),
339
                'value' => $value,
340
            ];
341
            $query->set('meta_query', $metaQuery);
342
        }
343
    }
344
345
    /**
346
     * @return void
347
     */
348
    protected function setOrderby(WP_Query $query)
349
    {
350
        $orderby = $query->get('orderby');
351
        $columns = glsr()->postTypeColumns[Application::POST_TYPE];
352
        unset($columns['cb'], $columns['title'], $columns['date']);
353
        if (in_array($orderby, array_keys($columns))) {
354
            if ('reviewer' == $orderby) {
355
                $orderby = 'author';
356
            }
357
            $query->set('meta_key', Str::prefix('_', $orderby, '_'));
358
            $query->set('orderby', 'meta_value');
359
        }
360
    }
361
}
362