Passed
Push — master ( 82312b...211f6c )
by Nicolaas
01:54
created

DBColour::getColours()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
1
<?php
2
3
namespace Sunnysideup\SelectedColourPicker\Model\Fields;
4
5
use SilverStripe\Forms\FormField;
6
use SilverStripe\Forms\LiteralField;
7
use SilverStripe\ORM\FieldType\DBVarchar;
8
9
use SilverStripe\Core\Config\Config;
10
use Sunnysideup\SelectedColourPicker\Forms\SelectedColourPickerFormField;
11
use Sunnysideup\SelectedColourPicker\Forms\SelectedColourPickerFormFieldDropdown;
12
use Sunnysideup\SelectedColourPicker\ViewableData\SelectedColourPickerFormFieldSwatches;
13
use TractorCow\Colorpicker\Color;
0 ignored issues
show
Bug introduced by
The type TractorCow\Colorpicker\Color was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
14
15
class DBColour extends Color
16
{
17
    private static $colour_picker_field_class_name = SelectedColourPickerFormFieldDropdown::class;
18
19
    /**
20
     * please set
21
     * must be defined as #AABB99 (hex codes).
22
     * Needs to be set like this:
23
     * ```php
24
     *     [
25
     *         'schema1' => [
26
     *             '#fff000' => 'My Colour 1',
27
     *             '#fff000' => 'My Colour 2',
28
     *         ],
29
     *
30
     *     ]
31
     *
32
     * ```
33
     *
34
     * @var array
35
     */
36
    private static $colours = [
37
        'default' => [
38
            '#FF0000' => 'Red',
39
            '#0000FF' => 'Blue',
40
            '#00FF00' => 'Green',
41
        ]
42
    ];
43
44
    /**
45
     * please set.
46
     *
47
     * @var string`
48
     */
49
    protected const CSS_CLASS_PREFIX = 'db-colour';
50
51
    /**
52
     * please set.
53
     *
54
     * @var bool
55
     */
56
    protected const IS_LIMITED_TO_OPTIONS = true;
57
58
    /**
59
     * please set.
60
     *
61
     * @var bool
62
     */
63
    protected const IS_BG_COLOUR = true;
64
65
    private static $casting = [
66
        'CssClass' => 'Varchar',
67
        'CssClassAlternative' => 'Boolean',
68
        'ReadableColor' => 'Varchar'
69
    ];
70
71
    private static $schema = 'default';
72
73
    public function __construct($name = null, $schema = 'default', $options = [])
74
    {
75
        $this->schema = $schema;
76
        parent::__construct($name, $options);
77
    }
78
79
    public function CssClass(?bool $isTransparent = false): string
80
    {
81
        return $this->getCssClass();
82
    }
83
84
    public function getCssClass(?bool $isTransparent = false): string
85
    {
86
        $colous = $this->getColours();
0 ignored issues
show
Unused Code introduced by
The assignment to $colous is dead and can be removed.
Loading history...
87
        if($isTransparent) {
88
            $name = 'transparent';
89
        } else {
90
            $name = $colours[$this->value] ?? 'colour-error';
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $colours does not exist. Did you maybe mean $colous?
Loading history...
91
        }
92
93
        return $this->classCleanup($name);
94
    }
95
96
    public function CssClassAlternative(?bool $isTransparent = false): string
97
    {
98
        return $this->getCssClassAlternative();
99
    }
100
101
    public function getCssClassAlternative(?bool $isTransparent = false): string
102
    {
103
        if($isTransparent) {
104
            $name = 'ffffff00';
105
        } else {
106
            $name = $this->value ?: 'no-colour';
107
        }
108
        return $this->classCleanup($name);
109
    }
110
111
    public function scaffoldFormField($title = null, $params = null)
112
    {
113
        return static::get_dropdown_field($this->name, $title);
114
    }
115
116
    /**
117
     *
118
     * @param  string $name
119
     * @param  string $title
120
     * @return FormField
121
     */
122
    public static function get_dropdown_field(string $name, ?string $title = '')
123
    {
124
        $className = Config::inst()->get(DBColour::class, 'colour_picker_field_class_name');
125
        return $className::create(
126
            $name,
127
            $title
128
        )
129
            ->setSource(static::COLOURS)
130
            ->setLimitedToOptions(static::IS_LIMITED_TO_OPTIONS)
131
            ->setIsBgColour(static::IS_BG_COLOUR);
132
        ;
133
        return $field;
0 ignored issues
show
Unused Code introduced by
return $field is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
134
    }
135
136
137
138
    public static function get_swatches_field(string $name, string $value): LiteralField
139
    {
140
        return SelectedColourPickerFormFieldSwatches::get_swatches_field((string) $name, (string) $value, static::COLOURS, static::IS_BG_COLOUR);
141
    }
142
143
    public function ReadableColor(): string
144
    {
145
        return $this->getReadableColor();
146
    }
147
    public function getReadableColor(): string
148
    {
149
        // Remove '#' if it's present
150
        $hexColor = ltrim((string) $this->value, '#');
151
152
        // Check if the color is valid
153
        if(strlen($hexColor) == 6) {
154
            // Convert the color from hexadecimal to RGB
155
            $r = hexdec(substr($hexColor, 0, 2)) / 255;
156
            $g = hexdec(substr($hexColor, 2, 2)) / 255;
157
            $b = hexdec(substr($hexColor, 4, 2)) / 255;
158
159
            // Calculate the relative luminance
160
            $luminance = 0.2126 * $r + 0.7152 * $g + 0.0722 * $b;
161
162
            // Return either black or white, depending on the luminance
163
            if($luminance > 0.5) {
164
                return '#000000'; // Black color
165
            } else {
166
                return '#ffffff'; // White color
167
            }
168
        } else {
169
            return false; // Invalid color
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the type-hinted return string.
Loading history...
170
        }
171
    }
172
    private function classCleanup(string $name): string
173
    {
174
        $name = str_replace('#', '', $name);
175
        $name = preg_replace('#[^A-Za-z0-9]#', '-', $name);
176
177
        return static::CSS_CLASS_PREFIX . '-' . trim(trim(strtolower($name), '-'));
178
    }
179
180
    public static function my_colours_for_dropdown(): ?array
181
    {
182
        if ($colours = self::my_colours()) {
183
            $array = [];
184
185
            foreach ($colours as $code => $label) {
186
                $textColor = Helper::isColorLight($code) ? '#000' : '#FFF';
0 ignored issues
show
Bug introduced by
The type Sunnysideup\SelectedColo...ker\Model\Fields\Helper was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
187
188
                $array[$code] = [
189
                    'label' => $label,
190
                    'background_css' => $code,
191
                    'color_css' => $textColor,
192
                    'sample_text' => 'Aa',
193
                ];
194
            }
195
196
            return $array;
197
        }
198
        return null;
199
    }
200
201
202
    /**
203
     * Detects if the given color is light
204
     * @param string $colour HEX color code
205
     */
206
    public static function fontColour($colour): string
207
    {
208
        return self::isColorLight((string) $colour) ? '#000000' : '#ffffff';
209
    }
210
    /**
211
     * @param string $colour HEX color code
212
     */
213
    public static function isDarkColour($colour): bool
214
    {
215
        return self::isColorLight((string) $colour) ? false : true;
216
    }
217
218
    /**
219
     * Detects if the given color is light
220
     * @param string $colour HEX color code
221
     */
222
    public static function isColorLight($colour): bool
223
    {
224
        if ($colour === 'transparent') {
225
            return true;
226
        }
227
        $colourWithoutHash = str_replace('#', '', (string) $colour);
228
        // Convert the color to its RGB values
229
        $rgb = sscanf($colourWithoutHash, "%02x%02x%02x");
230
        if (isset($rgb[0], $rgb[1], $rgb[2])) {
231
            // Calculate the relative luminance of the color using the formula from the W3C
232
            $luminance = 0.2126 * $rgb[0] + 0.7152 * $rgb[1] + 0.0722 * $rgb[2];
233
234
            // If the luminance is greater than 50%, the color is considered light
235
            return $luminance > 128;
236
        }
237
        return true;
238
    }
239
240
241
    protected static function check_colour(?string $colour, ?bool $isBackgroundColour = false): string
242
    {
243
        if(! $colour || strlen($colour) !== 7) {
244
            if($isBackgroundColour) {
245
                $colour = '#ffffff';
246
            } else {
247
                $colour = '#000000';
248
            }
249
        }
250
        return $colour;
251
    }
252
253
    protected function getColours(): array
254
    {
255
        return $this->Config()->get('colours');
256
    }
257
258
    protected function getMyColours(): array
259
    {
260
        $colours = $this->getColours();
261
262
        return $colours[$this->schema] ?? $colours[$this->schema];
263
    }
264
265
}
266
267
//
268
// public static function get_dropdown_field_old(?string $name = 'TextColour', ?string $title = 'Text Colour'): SelectedColourPickerFormField
269
// {
270
//     $field = SelectedColourPickerFormField::create(
271
//         $name,
272
//         $title,
273
//         static::COLOURS
274
//     );
275
//     $js = '
276
//         jQuery("#TextAndBackgroudColourExample").css("color", jQuery(this).val());
277
//     ';
278
//     $field->setAttribute('onchange', $js);
279
//     $field->setAttribute('onhover', $js);
280
//     $field->setAttribute('onclick', $js);
281
//     $field->setAttribute('onfocus', $js);
282
//
283
//     return $field;
284
// }
285
//
286