Passed
Push — master ( 211f6c...7a1513 )
by Nicolaas
02:24
created

DBColour::my_colours()   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 1
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 SilverStripe\ORM\FieldType\DBField;
11
use Sunnysideup\SelectedColourPicker\Forms\SelectedColourPickerFormField;
12
use Sunnysideup\SelectedColourPicker\Forms\SelectedColourPickerFormFieldDropdown;
13
use Sunnysideup\SelectedColourPicker\ViewableData\SelectedColourPickerFormFieldSwatches;
14
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...
15
16
class DBColour extends Color
17
{
18
    private static $colour_picker_field_class_name = SelectedColourPickerFormFieldDropdown::class;
19
20
    /**
21
     * please set
22
     * must be defined as #AABB99 (hex codes).
23
     * Needs to be set like this:
24
     * ```php
25
     *     [
26
     *         'schema1' => [
27
     *             '#fff000' => 'My Colour 1',
28
     *             '#fff000' => 'My Colour 2',
29
     *         ],
30
     *
31
     *     ]
32
     *
33
     * ```
34
     *
35
     * @var array
36
     */
37
    private static $colours = [
38
        'default' => self::DEFAULT_COLOURS,
39
    ];
40
41
42
    protected const DEFAULT_COLOURS = [
43
        '#FF0000' => 'Red',
44
        '#0000FF' => 'Blue',
45
        '#00FF00' => 'Green',
46
    ];
47
48
49
50
    /**
51
     * please set.
52
     *
53
     * @var string`
54
     */
55
    protected const CSS_CLASS_PREFIX = 'db-colour';
56
57
    /**
58
     * please set.
59
     *
60
     * @var bool
61
     */
62
    protected const IS_LIMITED_TO_OPTIONS = true;
63
64
    /**
65
     * please set.
66
     *
67
     * @var bool
68
     */
69
    protected const IS_BG_COLOUR = true;
70
71
    private static $casting = [
72
        'CssClass' => 'Varchar',
73
        'CssClassAlternative' => 'Boolean',
74
        'ReadableColor' => 'Varchar'
75
    ];
76
77
    private static $schema = 'default';
78
79
    public function __construct($name = null, $schema = '', $options = [])
80
    {
81
        $this->schema = $schema ?: $name;
82
        parent::__construct($name, $options);
83
    }
84
85
86
87
    public static function my_colours(string $name): array
88
    {
89
        return DBField::create_field(DBColour::class, $name)->getColours();
90
    }
91
92
    public static function get_swatches_field(string $name, string $value): LiteralField
93
    {
94
        return SelectedColourPickerFormFieldSwatches::get_swatches_field(
95
            (string) $name,
96
            (string) $value,
97
            self::my_colours(($name)),
98
            static::IS_BG_COLOUR
99
        );
100
    }
101
102
    /**
103
     *
104
     * @param  string $name
105
     * @param  string $title
106
     * @return FormField
107
     */
108
    public static function get_dropdown_field(string $name, ?string $title = '')
109
    {
110
        $className = Config::inst()->get(DBColour::class, 'colour_picker_field_class_name');
111
        return $className::create(
112
            $name,
113
            $title
114
        )
115
            ->setSource(self::my_colours($name))
116
            ->setLimitedToOptions(static::IS_LIMITED_TO_OPTIONS)
117
            ->setIsBgColour(static::IS_BG_COLOUR);
118
        ;
119
    }
120
121
122
    public function get_colours_for_dropdown(?string $name = 'default'): ?array
123
    {
124
        $colours = self::my_colours($name);
0 ignored issues
show
Bug introduced by
It seems like $name can also be of type null; however, parameter $name of Sunnysideup\SelectedColo...\DBColour::my_colours() does only seem to accept string, 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

124
        $colours = self::my_colours(/** @scrutinizer ignore-type */ $name);
Loading history...
125
        if (!empty($colours)) {
126
            $array = [];
127
128
            foreach ($colours as $code => $label) {
129
                $textColor = $this->getIsColorLight($code) ? '#000000' : '#FFFFFF';
130
131
                $array[$code] = [
132
                    'label' => $label,
133
                    'background_css' => $code,
134
                    'color_css' => $textColor,
135
                    'sample_text' => 'Aa',
136
                ];
137
            }
138
139
            return $array;
140
        }
141
        return null;
142
    }
143
144
145
    /**
146
     * Detects if the given color is light
147
     * @param string $colour HEX color code
148
     */
149
    public static function get_font_colour(?string $colour = ''): string
150
    {
151
        return self::is_light_colour((string) $colour) ? '#000000' : '#ffffff';
152
    }
153
154
    /**
155
     * @param string $colour HEX color code
156
     */
157
    public static function is_dark_colour(?string $colour = ''): bool
158
    {
159
        return self::is_light_colour((string) $colour) ? false : true;
160
    }
161
162
    /**
163
     * Detects if the given color is light
164
     * @param string $colour HEX color code
165
     */
166
    public static function is_light_colour(?string $colour = ''): bool
167
    {
168
        if ($colour === 'transparent') {
169
            return true;
170
        }
171
        $colourWithoutHash = str_replace('#', '', (string) $colour);
172
        // Convert the color to its RGB values
173
        $rgb = sscanf($colourWithoutHash, "%02x%02x%02x");
174
        if (isset($rgb[0], $rgb[1], $rgb[2])) {
175
            // Calculate the relative luminance of the color using the formula from the W3C
176
            $luminance = 0.2126 * $rgb[0] + 0.7152 * $rgb[1] + 0.0722 * $rgb[2];
177
178
            // If the luminance is greater than 50%, the color is considered light
179
            return $luminance > 128;
180
        }
181
        return true;
182
    }
183
184
185
    public static function check_colour(?string $colour, ?bool $isBackgroundColour = false): string
186
    {
187
        $colour = strtolower($colour);
0 ignored issues
show
Bug introduced by
It seems like $colour can also be of type null; however, parameter $string of strtolower() does only seem to accept string, 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

187
        $colour = strtolower(/** @scrutinizer ignore-type */ $colour);
Loading history...
188
        if($colour === 'transparent') {
189
            return 'transparent';
190
        }
191
        if(! strpos($colour, '#')) {
192
            $colour = '#' . $colour;
193
        }
194
        if(! $colour) {
195
            if($isBackgroundColour) {
196
                $colour = '#ffffff';
197
            } else {
198
                $colour = '#000000';
199
            }
200
        }
201
        return $colour;
202
    }
203
204
205
    public function CssClass(?bool $isTransparent = false): string
206
    {
207
        return $this->getCssClass();
208
    }
209
210
    public function getCssClass(?bool $isTransparent = false): string
211
    {
212
        $colours = $this->getColours();
213
        if($isTransparent) {
214
            $name = 'transparent';
215
        } else {
216
            $name = $colours[$this->value] ?? 'colour-error';
217
        }
218
219
        return $this->classCleanup($name);
220
    }
221
222
    public function CssClassAlternative(?bool $isTransparent = false): string
223
    {
224
        return $this->getCssClassAlternative();
225
    }
226
227
    public function getCssClassAlternative(?bool $isTransparent = false): string
228
    {
229
        if($isTransparent) {
230
            $name = 'ffffff00';
231
        } else {
232
            $name = $this->value ?: 'no-colour';
233
        }
234
        return $this->classCleanup($name);
235
    }
236
237
238
    public function ReadableColor(): string
239
    {
240
        return $this->getReadableColor();
241
    }
242
    public function getReadableColor(): string
243
    {
244
        // Remove '#' if it's present
245
        return $this->getFontColour();
246
    }
247
    private function classCleanup(string $name): string
248
    {
249
        $name = str_replace('#', '', $name);
250
        $name = preg_replace('#[^A-Za-z0-9]#', '-', $name);
251
252
        return static::CSS_CLASS_PREFIX . '-' . trim(trim(strtolower($name), '-'));
253
    }
254
255
    public function scaffoldFormField($title = null, $params = null)
256
    {
257
        return static::get_dropdown_field($this->name, $title);
258
    }
259
260
    protected function getColours(): array
261
    {
262
        return $this->Config()->get('colours');
263
    }
264
265
    protected function getMyColours(): array
266
    {
267
        $colours = $this->getColours();
268
269
        return $colours[$this->schema] ?? $colours['default'] ?? self::DEFAULT_COLOURS;
270
    }
271
272
273
274
275
276
}
277