Completed
Pull Request — componentlibrary (#307)
by
unknown
03:17 queued 01:43
created

componentLogServer.php ➔ consoleDebug()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 2
dl 0
loc 7
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * Usage:
5
 * Add get param `log` to url e.g. `http://localhost:3000/?log` and all the data will be output to via console.log in the dev tools in the browser.
6
 */
7
namespace Flynt\ComponentLogServer;
8
9
use Flynt;
10
11
define(__NAMESPACE__ . '\NS', __NAMESPACE__ . '\\');
12
13
add_action('Flynt/afterRegisterComponents', function () {
14
    if ((WP_ENV === 'development' || current_user_can('editor') || current_user_can('administrator')) && isset($_GET['log'])) {
15
        if (isset($_GET['component']) && !empty($_GET['component'])) {
16
            define(__NAMESPACE__ . '\COMPONENT_WHITELIST', explode(',', $_GET['component']));
17
        }
18
        add_filter("Flynt/addComponentData", NS . 'addDebugInfo', 99999, 2);
19
    }
20
}, 11);
21
22
function addDebugInfo($data, $componentName)
23
{
24
    if (!defined(__NAMESPACE__ . '\COMPONENT_WHITELIST') ||
25
        in_array($componentName, Flynt\ComponentLogServer\COMPONENT_WHITELIST)
26
    ) {
27
        consoleDebug([
28
            'component' => $componentName,
29
            'data' => $data,
30
        ]);
31
    }
32
    return $data;
33
}
34
35
function consoleDebug($data, $postpone = true)
36
{
37
    $type = gettype($data);
0 ignored issues
show
Unused Code introduced by
$type is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
38
    $output = json_encode($data);
39
    $result =  "<script>console.log({$output});</script>\n";
40
    echoDebug($result, $postpone);
41
}
42
43
function consoleTable($data, $postpone = true)
44
{
45
    $output = json_encode($data);
46
    $result =  "<script>console.table({$output});</script>\n";
47
    echoDebug($result, $postpone);
48
}
49
50
function echoDebug($data, $postpone)
51
{
52
    if ($postpone) {
53
        add_action('wp_footer', function () use ($data) {
54
            echo $data;
55
        }, 30);
56
    } else {
57
        echo $data;
58
    }
59
}
60