Passed
Push — master ( ef3592...8547eb )
by Evgenii
01:32
created

src/AdminBar.php (1 issue)

Labels
Severity
1
<?php
2
3
namespace Helick\GTM;
4
5
use Helick\GTM\Contracts\Bootable;
6
use RecursiveArrayIterator;
7
use RecursiveIteratorIterator;
8
use WP_Admin_Bar;
9
10
final class AdminBar implements Bootable
11
{
12
    /**
13
     * Boot the service.
14
     *
15
     * @return void
16
     */
17
    public static function boot(): void
18
    {
19
        $self = new static;
20
21
        add_action('admin_bar_menu', [$self, 'extendMenu']);
22
    }
23
24
    /**
25
     * Extend the admin bar menu.
26
     *
27
     * @param WP_Admin_Bar $adminBar
28
     *
29
     * @return void
30
     */
31
    public function extendMenu(WP_Admin_Bar $adminBar): void
32
    {
33
        $isUserAllowed = current_user_can('manage_options');
34
        $isBackend     = is_admin();
35
36
        /**
37
         * Control whether to show the data layer UI.
38
         *
39
         * @param bool $isEnabled
40
         */
41
        $isEnabled = apply_filters('helick_gtm_enable_data_layer_ui', true);
42
43
        if (!$isUserAllowed || $isBackend || !$isEnabled) {
44
            return;
45
        }
46
47
        $adminBar->add_menu([
48
            'id'    => 'helick-gtm',
49
            'title' => sprintf(
50
                '<span class="ab-icon dashicons-filter"></span> <span class="ab-label">%s</span>',
51
                __('Data Layer', DOMAIN)
52
            ),
53
        ]);
54
55
        $dataLayer = dataLayer();
56
57
        // Flatten data layer
58
        $flatten = static function (array $data, string $prefix = '') use (&$flatten) {
59
            $flattened = [];
60
61
            foreach ($data as $key => $value) {
62
                if (is_array($value)) {
63
                    $flattened = array_merge($flattened, $flatten($value, $prefix . $key . '.'));
64
                } else {
65
                    $flattened[$prefix . $key] = trim(json_encode($value), '"');
66
                }
67
            }
68
69
            return $flattened;
70
        };
71
72
        foreach ($flatten($dataLayer) as $key => $value) {
73
            $adminBar->add_node([
74
                'id'     => sanitize_key('helick-gtm-' . $key),
75
                'parent' => 'helick-gtm',
76
                'title'  => sprintf(
77
                    '<span style="font-weight: bold">%s:</span> %s',
78
                    $key,
79
                    esc_html($value)
0 ignored issues
show
The function esc_html was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

79
                    /** @scrutinizer ignore-call */ 
80
                    esc_html($value)
Loading history...
80
                ),
81
            ]);
82
        }
83
    }
84
}
85