Passed
Pull Request — master (#258)
by
unknown
04:23
created

colorBrightness()   B

Complexity

Conditions 7
Paths 30

Size

Total Lines 39
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 39
rs 8.6666
c 0
b 0
f 0
cc 7
eloc 20
nc 30
nop 2
1
<?php
2
3
/**
4
 * Add theme options to customizer
5
 */
6
7
namespace Flynt\CustomizerColors;
8
9
use Flynt\Utils\Asset;
10
use Flynt\Utils\Options;
11
use WP_Customize_Color_Control;
12
13
function getConfig()
14
{
15
    $colorsByTheme = [
16
        'default' => [
17
            'accent' => [
18
                'label'       => 'Accent',
19
                'default'     => '#2b44df',
20
                'description' => ''
21
            ],
22
            'headline' => [
23
                'label'       => 'Headline',
24
                'default'     => '#252525',
25
                'description' => ''
26
            ],
27
            'text' => [
28
                'label'       => 'Text',
29
                'default'     => '#353535',
30
                'description' => ''
31
            ],
32
            'border' => [
33
                'label'       => 'Border',
34
                'default'     => '#8791BA',
35
                'description' => ''
36
            ],
37
            'background' => [
38
                'label'       => 'Background',
39
                'default'     => '#ffffff',
40
                'description' => ''
41
            ],
42
        ],
43
        'light' => [
44
            'accent' => [
45
                'label'       => 'Accent',
46
                'default'     => '#2b44df',
47
                'description' => ''
48
            ],
49
            'headline' => [
50
                'label'       => 'Headline',
51
                'default'     => '#252525',
52
                'description' => ''
53
            ],
54
            'text' => [
55
                'label'       => 'Text',
56
                'default'     => '#353535',
57
                'description' => ''
58
            ],
59
            'border' => [
60
                'label'       => 'Border',
61
                'default'     => '#8791BA',
62
                'description' => ''
63
            ],
64
            'background' => [
65
                'label'       => 'Background',
66
                'default'     => '#F8F9FD',
67
                'description' => ''
68
            ],
69
        ],
70
        'dark' => [
71
            'accent' => [
72
                'label'       => 'Accent',
73
                'default'     => '#ffffff',
74
                'description' => '',
75
            ],
76
            'headline' => [
77
                'label'       => 'Headline',
78
                'default'     => '#FBFBFB',
79
                'description' => '',
80
            ],
81
            'text' => [
82
                'label'       => 'Text',
83
                'default'     => '#E9E9EC',
84
                'description' => '',
85
            ],
86
            'border' => [
87
                'label'       => 'Border',
88
                'default'     => '#C3C4F7',
89
                'description' => '',
90
            ],
91
            'background' => [
92
                'label'       => 'Background',
93
                'default'     => '#10205A',
94
                'description' => '',
95
            ],
96
        ],
97
        'hero' => [
98
            'accent' => [
99
                'label'       => 'Accent',
100
                'default'     => '#ffffff',
101
                'description' => '',
102
            ],
103
            'headline' => [
104
                'label'       => 'Headline',
105
                'default'     => '#FBFBFB',
106
                'description' => '',
107
            ],
108
            'text' => [
109
                'label'       => 'Text',
110
                'default'     => '#E9E9EC',
111
                'description' => '',
112
            ],
113
            'border' => [
114
                'label'       => 'Border',
115
                'default'     => '#CDE2FD',
116
                'description' => '',
117
            ],
118
            'background' => [
119
                'label'       => 'Background',
120
                'default'     => '#2B44DF',
121
                'description' => '',
122
            ],
123
        ],
124
    ];
125
126
    $sectionsByTheme = [
127
        'default' => __('Default', 'flynt'),
128
        'light' => __('Theme Light', 'flynt'),
129
        'dark' => __('Theme Dark', 'flynt'),
130
        'hero' => __('Theme Hero', 'flynt'),
131
    ];
132
133
    return [
134
        'colors' => $colorsByTheme,
135
        'sections' => $sectionsByTheme,
136
    ];
137
}
138
139
add_action('acf/init', function () {
140
    $options = Options::getGlobal('CustomizerColors');
141
    if ($options['enabled']) {
142
        add_action('customize_register', function ($wp_customize) {
143
            $config = getConfig();
144
            $wp_customize->add_panel(
145
                'theme_colors_panel',
146
                [
147
                    'title' => __('Colors', 'flynt'),
148
                    // 'description' => 'description', // Include html tags such as <p>.
149
                    'priority' => 160, // Mixed with top-level-section hierarchy.
150
                ]
151
            );
152
            foreach (($config['sections'] ?? []) as $key => $title) {
153
                $wp_customize->add_section(
154
                    "theme_colors_{$key}",
155
                    [
156
                        'title'      => $title,
157
                        'priority'   => 20,
158
                        'panel' => 'theme_colors_panel'
159
                    ]
160
                );
161
            }
162
            foreach (($config['colors'] ?? []) as $theme => $colors) {
163
                foreach ($colors as $colorName => $colorConfig) {
164
                    // Settings
165
                    $wp_customize->add_setting(
166
                        "theme_colors_{$colorName}_{$theme}",
167
                        [
168
                            'default'   => $colorConfig['default'],
169
                            'transport' => 'postMessage',
170
                        ]
171
                    );
172
                    // Controls
173
                    $wp_customize->add_control(
174
                        new WP_Customize_Color_Control(
175
                            $wp_customize,
176
                            "theme_colors_{$colorName}_{$theme}",
177
                            [
178
                                'section'     => 'theme_colors_' . $theme,
179
                                'label'       => __($colorConfig['label']),
180
                                'description' => __($colorConfig['description']),
181
                            ]
182
                        )
183
                    );
184
                }
185
            }
186
        });
187
188
        add_action('customize_preview_init', function () {
189
            wp_enqueue_script(
190
                'customizer-colors',
191
                Asset::requireUrl('assets/customizer-colors.js'),
192
                array('jquery','customize-preview'),
193
                '',
194
                true
195
            );
196
        });
197
198
        add_action('wp_head', function () {
199
            $config = getConfig();
200
201
            $alphaColorAmount = 0.4;
202
            $darkenColorAmount = -0.1; // -0.1 darken value approximately equals scss darken 5%
203
            ?>
204
            <style type="text/css">
205
                :root.html {
206
                    <?php foreach (($config['colors'] ?? []) as $theme => $colors) {
207
                        foreach ($colors as $colorName => $colorConfig) {
208
                            $colorValue = get_theme_mod("theme_colors_{$colorName}_{$theme}", $colorConfig['default']);
209
                            echo "--theme-color-{$colorName}-{$theme}: {$colorValue};";
210
                        }
211
                        $accentColorValue = get_theme_mod("theme_colors_accent_{$theme}", $colors['accent']['default']);
212
                        $rgbaValue = hex2rgba($accentColorValue, $alphaColorAmount);
213
                        $darkenedValue = colorBrightness($accentColorValue, $darkenColorAmount);
214
                        echo "--theme-color-accent-alpha-{$theme}: {$rgbaValue};";
215
                        echo "--theme-color-accent-hover-{$theme}: {$darkenedValue};";
216
                    } ?>
217
            </style>
218
            <?php
219
        });
220
    }
221
});
222
223
Options::addGlobal('CustomizerColors', [
224
    [
225
        'label' => __('Status', 'flynt'),
226
        'name' => 'enabled',
227
        'type' => 'true_false',
228
        'ui' => 1,
229
        'ui_on_text' => 'Enabled',
230
        'ui_off_text' => 'Disabled',
231
        'default_value' => true,
232
    ],
233
]);
234
235
236
function hex2rgba($color, $opacity = false)
237
{
238
    $default = 'rgb(0,0,0)';
239
240
    // Return default if no color provided
241
    if (empty($color)) {
242
          return $default;
243
    }
244
245
    // Sanitize $color if "#" is provided
246
    if ($color[0] == '#') {
247
        $color = substr($color, 1);
248
    }
249
250
    // Check if color has 6 or 3 characters and get values
251
    if (strlen($color) == 6) {
252
            $hex = array( $color[0] . $color[1], $color[2] . $color[3], $color[4] . $color[5] );
253
    } elseif (strlen($color) == 3) {
254
            $hex = array( $color[0] . $color[0], $color[1] . $color[1], $color[2] . $color[2] );
255
    } else {
256
            return $default;
257
    }
258
259
    // Convert hexadec to rgb
260
    $rgb =  array_map('hexdec', $hex);
261
262
    // Check if opacity is set(rgba or rgb)
263
    if ($opacity) {
264
        if (abs($opacity) > 1) {
265
            $opacity = 1.0;
266
        }
267
        $output = 'rgba(' . implode(",", $rgb) . ',' . $opacity . ')';
268
    } else {
269
        $output = 'rgb(' . implode(",", $rgb) . ')';
270
    }
271
272
    // Return rgb(a) color string
273
    return $output;
274
}
275
276
function colorBrightness($hex, $percent)
277
{
278
    // Work out if hash given
279
    $hash = '';
280
    if (stristr($hex, '#')) {
281
        $hex = str_replace('#', '', $hex);
282
        $hash = '#';
283
    }
284
    // HEX TO RGB
285
    $rgb = [hexdec(substr($hex, 0, 2)), hexdec(substr($hex, 2, 2)), hexdec(substr($hex, 4, 2))];
286
    // CALCULATE
287
    for ($i = 0; $i < 3; $i++) {
288
        // See if brighter or darker
289
        if ($percent > 0) {
290
            // Lighter
291
            $rgb[$i] = round($rgb[$i] * $percent) + round(255 * (1 - $percent));
292
        } else {
293
            // Darker
294
            $positivePercent = $percent - ($percent * 2);
295
            $rgb[$i] = round($rgb[$i] * (1 - $positivePercent)); // round($rgb[$i] * (1-$positivePercent));
296
        }
297
        // In case rounding up causes us to go to 256
298
        if ($rgb[$i] > 255) {
299
            $rgb[$i] = 255;
300
        }
301
    }
302
    // RBG to Hex
303
    $hex = '';
304
    for ($i = 0; $i < 3; $i++) {
305
        // Convert the decimal digit to hex
306
        $hexDigit = dechex($rgb[$i]);
0 ignored issues
show
Bug introduced by
It seems like $rgb[$i] can also be of type double; however, parameter $number of dechex() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

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

306
        $hexDigit = dechex(/** @scrutinizer ignore-type */ $rgb[$i]);
Loading history...
307
        // Add a leading zero if necessary
308
        if (strlen($hexDigit) == 1) {
309
            $hexDigit = "0" . $hexDigit;
310
        }
311
        // Append to the hex string
312
        $hex .= $hexDigit;
313
    }
314
    return $hash . $hex;
315
}
316