Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
100.00% |
13 / 13 |
|
100.00% |
3 / 3 |
CRAP | |
100.00% |
1 / 1 |
HtmlClassUtils | |
100.00% |
13 / 13 |
|
100.00% |
3 / 3 |
3 | |
100.00% |
1 / 1 |
parseClassString | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
1 | |||
formClassString | |
100.00% |
7 / 7 |
|
100.00% |
1 / 1 |
1 | |||
filterAllowedClasses | |
100.00% |
4 / 4 |
|
100.00% |
1 / 1 |
1 |
1 | <?php |
2 | |
3 | namespace MobileFrontend\Transforms\Utils; |
4 | |
5 | /** |
6 | * Simple utility for working with html classes as with set |
7 | */ |
8 | class HtmlClassUtils { |
9 | /** |
10 | * Parse html class string into set (array of string=>bool) where key is class name |
11 | * and values is always true |
12 | * |
13 | * @param string $classAttr raw `class` attribute's string retrieved from html |
14 | * |
15 | * @return array |
16 | */ |
17 | public static function parseClassString( string $classAttr ): array { |
18 | $classes = preg_split( '/\s+/', $classAttr, -1, PREG_SPLIT_NO_EMPTY ); |
19 | return array_fill_keys( $classes, true ); |
20 | } |
21 | |
22 | /** |
23 | * Forms raw html `class` string from set of classes. Set is a key-value array where |
24 | * key is class name and value is boolean that determines wheather this class should be |
25 | * included to string or not. |
26 | * |
27 | * |
28 | * @param array $classes set of classes that should be formed into string |
29 | * |
30 | * @return string |
31 | */ |
32 | public static function formClassString( array $classes ): string { |
33 | $enabled = array_filter( |
34 | $classes, |
35 | static function ( $enabled ) { |
36 | return $enabled; |
37 | } |
38 | ); |
39 | return implode( ' ', array_keys( $enabled ) ); |
40 | } |
41 | |
42 | /** |
43 | * Filters set of classes by list of allowed classes |
44 | * |
45 | * @param array $classes key-value array of html classes |
46 | * @param string[] $allowedClasses list of allowed classes |
47 | * @param string[] $additional list of additional styles should be added in front of list |
48 | * |
49 | * @return array |
50 | */ |
51 | public static function filterAllowedClasses( array $classes, array $allowedClasses, array $additional ): array { |
52 | return array_fill_keys( $additional, true ) + array_intersect_key( |
53 | $classes, |
54 | array_fill_keys( $allowedClasses, true ) |
55 | ); |
56 | } |
57 | } |