-
Notifications
You must be signed in to change notification settings - Fork 1
/
ContrastRatio.php
80 lines (68 loc) · 1.46 KB
/
ContrastRatio.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
<?php
namespace HarmsTyler\ContrastRatioCalculator;
/**
* Class ContrastRatio
*/
class ContrastRatio
{
/**
* @var float
*/
private $ratio;
/**
* @var Color
*/
private $primaryColor;
/**
* @var Color
*/
private $secondaryColor;
/**
* ContrastRatio constructor.
* @param Color $primaryColor
* @param Color $secondaryColor
*/
public function __construct(Color $primaryColor, Color $secondaryColor)
{
$this->primaryColor = $primaryColor;
$this->secondaryColor = $secondaryColor;
$this->ratio = $this->calculateContrastRatio();
}
/**
* @return Color
*/
public function getPrimaryColor(): Color
{
return $this->primaryColor;
}
/**
* @return Color
*/
public function getSecondaryColor(): Color
{
return $this->secondaryColor;
}
/**
* @return float
*/
public function getRatio(): float
{
return $this->ratio;
}
/**
* Formula: http://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef
*
* @return float
*/
public function calculateContrastRatio(): float
{
$l1 = $this->primaryColor->getLuminance();
$l2 = $this->secondaryColor->getLuminance();
$ratio = ($l1 + 0.05) / ($l2 + 0.05);
if ($l2 > $l1) {
$ratio = 1 / $ratio;
}
$ratio = round($ratio, 1);
return $ratio;
}
}