GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Passed
Push — master ( d1c54e...b1afe7 )
by Leonardo
02:57
created

ModuleListTable::getRecordCount()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 2
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 4
ccs 0
cts 4
cp 0
crap 2
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace GraphQLAPI\GraphQLAPI\Admin\Tables;
6
7
use GraphQLAPI\GraphQLAPI\General\RequestParams;
8
use GraphQLAPI\GraphQLAPI\Facades\ModuleRegistryFacade;
9
use GraphQLAPI\GraphQLAPI\Admin\MenuPages\ModulesMenuPage;
10
use GraphQLAPI\GraphQLAPI\Admin\MenuPages\SettingsMenuPage;
11
use PoP\ComponentModel\Facades\Instances\InstanceManagerFacade;
12
use GraphQLAPI\GraphQLAPI\Admin\TableActions\ModuleListTableAction;
13
14
/**
15
 * Module Table
16
 */
17
class ModuleListTable extends AbstractItemListTable
18
{
19
    /**
20
     * Singular name of the listed records
21
     *
22
     * @return string
23
     */
24
    public function getItemSingularName(): string
25
    {
26
        return \__('Module', 'graphql-api');
27
    }
28
29
    /**
30
     * Plural name of the listed records
31
     *
32
     * @return string
33
     */
34
    public function getItemPluralName(): string
35
    {
36
        return \__('Modules', 'graphql-api');
37
    }
38
39
    /**
40
     * Return all the items to display on the table
41
     *
42
     * @return array
43
     */
44
    public function getAllItems(): array
45
    {
46
        $items = [];
47
        $moduleRegistry = ModuleRegistryFacade::getInstance();
48
        $modules = $moduleRegistry->getAllModules();
49
        foreach ($modules as $module) {
50
            $moduleResolver = $moduleRegistry->getModuleResolver($module);
51
            $isEnabled = $moduleRegistry->isModuleEnabled($module);
52
            $items[] = [
53
                'module' => $module,
54
                'module-type' => $moduleResolver->getModuleType($module),
55
                'module-subtype' => $moduleResolver->getModuleSubtype($module),
56
                'id' => $moduleResolver->getID($module),
57
                'is-enabled' => $isEnabled,
58
                'can-be-disabled' => $moduleResolver->canBeDisabled($module),
59
                'can-be-enabled' => !$isEnabled && $moduleRegistry->canModuleBeEnabled($module),
60
                'has-settings' => $moduleResolver->hasSettings($module),
61
                'name' => $moduleResolver->getName($module),
62
                'description' => $moduleResolver->getDescription($module),
63
                'depends-on' => $moduleResolver->getDependedModuleLists($module),
64
                // 'url' => $moduleResolver->getURL($module),
65
                'slug' => $moduleResolver->getSlug($module),
66
                'has-docs' => $moduleResolver->hasDocumentation($module),
67
            ];
68
        }
69
        return $items;
70
    }
71
72
    /**
73
     * List of item data
74
     *
75
     * @param int $per_page
76
     * @param int $page_number
77
     *
78
     * @return mixed
79
     */
80
    public function getItems($per_page = 5, $page_number = 1)
81
    {
82
        $results = $this->getAllItems();
83
        return array_splice(
84
            $results,
85
            ($page_number - 1) * $per_page,
86
            $per_page
87
        );
88
    }
89
90
    /**
91
     * Returns the count of records in the database.
92
     */
93
    public function getRecordCount(): int
94
    {
95
        $results = $this->getAllItems();
96
        return count($results);
97
    }
98
99
    /**
100
     * Render a column when no column specific method exist.
101
     *
102
     * @param object $item
103
	 * @param string $column_name
104
     *
105
     * @return mixed
106
     * phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
107
     */
108
    protected function column_default($item, $column_name)
109
    {
110
        switch ($column_name) {
111
            case 'desc':
112
                $actions = [];
113
                // If it has, add a link to the documentation
114
                $instanceManager = InstanceManagerFacade::getInstance();
115
                $modulesMenuPage = $instanceManager->getInstance(ModulesMenuPage::class);
116
                if ($item['has-docs']) {
117
                    $url = \admin_url(sprintf(
118
                        'admin.php?page=%s&%s=%s&%s=%s&TB_iframe=true&width=600&height=550',
119
                        $modulesMenuPage->getScreenID(),
120
                        RequestParams::TAB,
121
                        RequestParams::TAB_DOCS,
122
                        RequestParams::MODULE,
123
                        urlencode($item['module'])
124
                    ));
125
                    $actions['docs'] = \sprintf(
126
                        '<a href="%s" class="%s" data-title="%s">%s</a>',
127
                        \esc_url($url),
128
                        'thickbox open-plugin-details-modal',
129
                        \esc_attr($item['name']),
130
                        \__('View details', 'graphql-api')
131
                    );
132
                }
133
                return sprintf(
134
                    '<div class="plugin-description"><p>%s</p></div><div class="second">%s</div>',
135
                    $item['description'],
136
                    $this->row_actions($actions, true)
137
                );
138
            case 'depends-on':
139
                // Output the list with AND lists of dependencies
140
                // Each list is an OR list of depended modules
141
                // It's formatted like this: module1, module2, ..., module5 or module6
142
                $items = [];
143
                $moduleRegistry = ModuleRegistryFacade::getInstance();
144
                $dependedModuleLists = $item[$column_name];
145
                if (!$dependedModuleLists) {
146
                    return \__('-', 'graphql-api');
147
                }
148
                /**
149
                 * This is a list of lists of modules, as to model both OR and AND conditions
150
                 */
151
                foreach ($dependedModuleLists as $dependedModuleList) {
152
                    if (!$dependedModuleList) {
153
                        continue;
154
                    }
155
                    $dependedModuleListNames = array_map(
156
                        function ($dependedModule) use ($moduleRegistry) {
157
                            $after = '';
158
                            // Check if it has the "inverse" token at the beginning,
159
                            // then it depends on the module being disabled, not enabled
160
                            if ($moduleRegistry->isInverseDependency($dependedModule)) {
161
                                // Revert to the normal module
162
                                $dependedModule = $moduleRegistry->getInverseDependency($dependedModule);
163
                                $after = \__('⇠ as disabled', 'graphql-api');
164
                            }
165
                            $moduleResolver = $moduleRegistry->getModuleResolver($dependedModule);
166
                            return sprintf(
167
                                '%1$s %2$s %3$s',
168
                                '▹',
169
                                $moduleResolver->getName($dependedModule),
170
                                $after
171
                            );
172
                        },
173
                        $dependedModuleList
174
                    );
175
                    if (count($dependedModuleListNames) >= 2) {
176
                        $lastElem = array_pop($dependedModuleListNames);
177
                        $commaElems = implode(
178
                            \__(', ', 'graphql-api'),
179
                            $dependedModuleListNames
180
                        );
181
                        $items[] = sprintf(
182
                            \__('%s or %s', 'graphql-api'),
183
                            $commaElems,
184
                            $lastElem
185
                        );
186
                    } else {
187
                        $items[] = $dependedModuleListNames[0];
188
                    }
189
                }
190
                return implode('<br/>', $items);
191
            case 'enabled':
192
                return \sprintf(
193
                    '<span role="img" aria-label="%s">%s</span>',
194
                    $item['is-enabled'] ? \__('Yes', 'graphql-api') : \__('No', 'graphql-api'),
195
                    $item['is-enabled'] ? '✅' : '❌'
196
                );
197
        }
198
        return '';
199
    }
200
201
    /**
202
     * Render the bulk edit checkbox
203
     *
204
     * @param object $item
205
     *
206
     * @return string
207
     * phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
208
     */
209
    protected function column_cb($item)
210
    {
211
        return sprintf(
212
            '<input type="checkbox" name="%s[]" value="%s" />',
213
            ModuleListTableAction::INPUT_BULK_ACTION_IDS,
214
            $item['id']
215
        );
216
    }
217
218
    /**
219
     * Method for name column
220
     *
221
     * @param array $item an array of DB data
222
     *
223
     * @return string
224
     * phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
225
     */
226
    public function column_name($item)
227
    {
228
        $nonce = \wp_create_nonce('graphql_api_enable_or_disable_module');
229
        $title = '<strong>' . $item['name'] . '</strong>';
230
        $linkPlaceholder = '<a href="?page=%s&action=%s&item=%s&_wpnonce=%s">%s</a>';
231
        $page = esc_attr($_REQUEST['page']);
232
        $actions = [];
233
        if ($item['is-enabled']) {
234
            // If it is enabled, offer to disable it
235
            // Unless the module cannot be disabled
236
            if ($item['can-be-disabled']) {
237
                $actions['disable'] = \sprintf(
238
                    $linkPlaceholder,
239
                    $page,
240
                    ModuleListTableAction::ACTION_DISABLE,
241
                    $item['id'],
242
                    $nonce,
243
                    \__('Disable', 'graphql-api')
244
                );
245
            } else {
246
                $actions['enabled'] = \__('Enabled', 'graphql-api');
247
            }
248
249
            // Maybe add settings links
250
            if ($item['has-settings']) {
251
                $instanceManager = InstanceManagerFacade::getInstance();
252
                $settingsMenuPage = $instanceManager->getInstance(SettingsMenuPage::class);
253
                $actions['settings'] = \sprintf(
254
                    '<a href="%s">%s</a>',
255
                    sprintf(
256
                        \admin_url(sprintf(
257
                            'admin.php?page=%s&tab=%s',
258
                            $settingsMenuPage->getScreenID(),
259
                            $item['id']
260
                        ))
261
                    ),
262
                    \__('Settings', 'graphql-api')
263
                );
264
            }
265
        } elseif ($item['can-be-enabled']) {
266
            // If not enabled and can be enabled, offer to do it
267
            $actions['enable'] = \sprintf(
268
                $linkPlaceholder,
269
                $page,
270
                ModuleListTableAction::ACTION_ENABLE,
271
                $item['id'],
272
                $nonce,
273
                \__('Enable', 'graphql-api')
274
            );
275
        } else {
276
            // Not enabled and can't be enabled, mention requirements not met
277
            // Not enabled for "striped" table style because, without a link, color contrast is not good:
278
            // gray font color over gray background
279
            // if ($this->usePluginTableStyle()) {
280
            $actions['disabled'] = \__('Disabled', 'graphql-api');
281
            // }
282
        }
283
        return $title . $this->row_actions($actions/*, $this->usePluginTableStyle()*/);
284
    }
285
286
    /**
287
     * Indicate if to show the enabled column or not
288
     */
289
    protected function usePluginTableStyle(): bool
290
    {
291
        return true;
292
    }
293
294
    /**
295
     *  Associative array of columns
296
     *
297
     * @return array
298
     * phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
299
     */
300
    public function get_columns()
301
    {
302
        return array_merge(
303
            [
304
                'cb' => '<input type="checkbox" />',
305
                'name' => \__('Module', 'graphql-api'),
306
            ],
307
            $this->usePluginTableStyle() ?
308
                [] :
309
                [
310
                    'enabled' => \__('Enabled', 'graphql-api'),
311
                ],
312
            [
313
                'desc' => \__('Description', 'graphql-api'),
314
                'depends-on' => \__('Depends on', 'graphql-api'),
315
            ]
316
        );
317
    }
318
319
    /**
320
     * Returns an associative array containing the bulk action
321
     *
322
     * @return array
323
     * phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
324
     */
325
    public function get_bulk_actions()
326
    {
327
        return [
328
            ModuleListTableAction::ACTION_ENABLE => \__('Enable', 'graphql-api'),
329
            ModuleListTableAction::ACTION_DISABLE => \__('Disable', 'graphql-api'),
330
        ];
331
    }
332
333
    /**
334
     * Get a list of CSS classes for the WP_List_Table table tag.
335
     *
336
     * @since 3.1.0
337
     *
338
     * @return string[] Array of CSS classes for the table tag.
339
     * phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
340
     */
341
    protected function get_table_classes()
342
    {
343
        // return array_merge(
344
        //     parent::get_table_classes(),
345
        //     [
346
        //         'plugins'
347
        //     ]
348
        // );
349
        if ($this->usePluginTableStyle()) {
350
            return array( 'widefat', 'plugins', $this->_args['plural'] );
351
        }
352
        return array_diff(
353
            parent::get_table_classes(),
354
            [
355
                'fixed'
356
            ]
357
        );
358
    }
359
360
    /**
361
     * Classnames to add to the row for the item
362
     *
363
     * @param object $item The current item
364
     */
365
    protected function getTableStyleRowClassnames($item): string
366
    {
367
        $classnames = sprintf(
368
            'module-%s',
369
            $item['module-type']
370
        );
371
        if (!is_null($item['module-subtype'])) {
372
            $classnames .= ' ' . sprintf(
373
                'module-%s-%s',
374
                $item['module-type'],
375
                $item['module-subtype']
376
            );
377
        }
378
        return $classnames;
379
    }
380
381
    /**
382
     * Generates content for a single row of the table
383
     *
384
     * @since 3.1.0
385
     *
386
     * @param object $item The current item
387
     * phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
388
     */
389
    public function single_row($item)
390
    {
391
        if ($this->usePluginTableStyle()) {
392
            $classnames = sprintf(
393
                '%s %s',
394
                $this->getTableStyleRowClassnames($item),
395
                $item['is-enabled'] ? 'active' : 'inactive'
396
            );
397
            echo sprintf(
398
                '<tr class="%s">',
399
                $classnames
400
            );
401
            $this->single_row_columns($item);
402
            echo '</tr>';
403
        } else {
404
            parent::single_row($item);
405
        }
406
    }
407
408
    /**
409
     * Handles data query and filter, sorting, and pagination.
410
     *
411
     * phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
412
     */
413
    public function prepare_items()
414
    {
415
        $this->_column_headers = $this->get_column_info();
416
417
        /** Process bulk or single action */
418
        $instanceManager = InstanceManagerFacade::getInstance();
419
        $tableAction = $instanceManager->getInstance(ModuleListTableAction::class);
420
        $tableAction->maybeProcessAction();
421
422
        $per_page = $this->get_items_per_page(
423
            $this->getItemsPerPageOptionName(),
424
            $this->getDefaultItemsPerPage()
425
        );
426
        $current_page = $this->get_pagenum();
427
        $total_items  = $this->getRecordCount();
428
429
        $this->set_pagination_args([
430
            'total_items' => $total_items,
431
            'per_page'    => $per_page,
432
        ]);
433
434
        $this->items = $this->getItems($per_page, $current_page);
435
    }
436
437
    /**
438
     * Enqueue the required assets
439
     *
440
     * @return void
441
     */
442
    public function enqueueAssets(): void
443
    {
444
        parent::enqueueAssets();
445
446
        /**
447
         * Fix the issues with the WP List Table
448
         */
449
        \wp_enqueue_style(
450
            'graphql-api-module-list-table',
451
            \GRAPHQL_API_URL . 'assets/css/module-list-table.css',
452
            array(),
453
            \GRAPHQL_API_VERSION
454
        );
455
    }
456
457
    /**
458
     * Customize the width of the columns
459
     */
460
    public function printStyles(): void
461
    {
462
        parent::printStyles();
463
464
        /*
465
        if ($this->usePluginTableStyle()) {
466
            ?>
467
            <style type="text/css">
468
                .wp-list-table .column-name { width: 25%; }
469
                .wp-list-table .column-description { width: 75%; }
470
            </style>
471
            <?php
472
        } else {
473
            ?>
474
            <style type="text/css">
475
                .wp-list-table .column-name { width: 25%; }
476
                .wp-list-table .column-enabled { width: 10%; }
477
                .wp-list-table .column-description { width: 65%; }
478
            </style>
479
            <?php
480
        }
481
        */
482
    }
483
}
484