-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathColor.php
145 lines (121 loc) · 3.02 KB
/
Color.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
<?php
/**
* ColorMate plugin for Craft CMS 5.x
*
* Color me impressed, mate!
*
* @link https://www.vaersaagod.no
* @copyright Copyright (c) 2024 Værsågod
*/
namespace vaersaagod\colormate\models;
use Craft;
use craft\base\Model;
use craft\validators\ColorValidator;
use vaersaagod\colormate\ColorMate;
/**
* @author Værsågod
* @package ColorMate
* @since 1.0.0
*
* @property null|string $color
*/
class Color extends Model
{
// Public Properties
// =========================================================================
/**
* @var string
*/
public string $handle = '';
/**
* @var string
*/
public string $custom = '';
/**
* @var int
*/
public int $opacity = 100;
/**
* @var string
*/
public string $name = '';
/**
* @var string|null
*/
public ?string $baseColor = null;
/**
* @var null|Preset
*/
public ?Preset $preset = null;
// Public Methods
// =========================================================================
/**
* @inheritdoc
*/
public function rules(): array
{
return [
['handle', 'string'],
['custom', ColorValidator::class, 'when' => function () { return $this->custom !== ''; }, 'message' => Craft::t('colormate', 'Custom color is not a valid hex value')],
['opacity', 'required'],
['opacity', 'default', 'value' => 100],
['opacity', 'integer', 'min' => 0, 'max' => 100]
];
}
/**
* @return string
*/
public function __toString(): string
{
return $this->getColor() ?? '';
}
/**
* @param string $format
*
* @return string|null
*/
public function getColor(string $format = 'rgb'): ?string
{
if ($this->baseColor === null) {
return null;
}
try {
$color = ColorMate::$plugin->color->getColor($this->baseColor);
} catch (\Throwable) {
return null;
}
if ($this->opacity !== 100) {
$opacityAdjust = $this->opacity/100;
$color = ColorMate::$plugin->color->adjustColor($color, ['alpha' => (1 - ($color->getRgb()->getAlpha() * $opacityAdjust)) * -1]);
}
if ($format==='hex') {
return ColorMate::$plugin->color->rgb2hex($color);
}
if ($format === 'hsl') {
return $color->getHsl();
}
return $color->getRgb();
}
/**
* @return bool
*/
public function isCustom(): bool
{
return $this->custom !== '';
}
/**
* @return bool
*/
public function hasTransparency(): bool
{
if ($this->opacity < 100) {
return true;
}
try {
$rgbColor = ColorMate::$plugin->color->getColor($this->baseColor)->getRgb();
} catch (\Throwable) {
return false;
}
return $rgbColor->getAlpha() < 1;
}
}