Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
100.00% |
20 / 20 |
|
100.00% |
3 / 3 |
CRAP | |
100.00% |
1 / 1 |
HtmlStyleUtils | |
100.00% |
20 / 20 |
|
100.00% |
3 / 3 |
8 | |
100.00% |
1 / 1 |
parseStyleString | |
100.00% |
10 / 10 |
|
100.00% |
1 / 1 |
4 | |||
formStyleString | |
100.00% |
6 / 6 |
|
100.00% |
1 / 1 |
3 | |||
filterAllowedStyles | |
100.00% |
4 / 4 |
|
100.00% |
1 / 1 |
1 |
1 | <?php |
2 | |
3 | namespace MobileFrontend\Transforms\Utils; |
4 | |
5 | /** |
6 | * Simple utility class for working with html styles as with key-value array |
7 | */ |
8 | class HtmlStyleUtils { |
9 | /** |
10 | * Parse html `styles` string into kev-value array |
11 | * |
12 | * @param string $styleAttr Element or document to rewrite images in. |
13 | * |
14 | * @return array |
15 | */ |
16 | public static function parseStyleString( string $styleAttr ): array { |
17 | if ( $styleAttr === '' ) { |
18 | return []; |
19 | } |
20 | $styleStrings = preg_split( '/\;/', $styleAttr, -1, PREG_SPLIT_NO_EMPTY ); |
21 | $result = []; |
22 | foreach ( $styleStrings as $styleString ) { |
23 | $styleWithValue = explode( ':', $styleString ); |
24 | $style = trim( $styleWithValue[0] ); |
25 | if ( $style !== '' ) { |
26 | $result[$style] = trim( $styleWithValue[1] ?? '' ); |
27 | } |
28 | } |
29 | return $result; |
30 | } |
31 | |
32 | /** |
33 | * Forms style's string from kev-value array |
34 | * |
35 | * @param array $styles |
36 | * |
37 | * @return string |
38 | */ |
39 | public static function formStyleString( array $styles ): string { |
40 | $styleString = ''; |
41 | foreach ( $styles as $style => $value ) { |
42 | if ( $value === '' ) { |
43 | $styleString .= $style . ';'; |
44 | |
45 | } else { |
46 | $styleString .= $style . ': ' . $value . ';'; |
47 | } |
48 | } |
49 | return $styleString; |
50 | } |
51 | |
52 | /** |
53 | * Filters style key-value array by list of allowed styles, appending them by |
54 | * list of additional styles |
55 | * |
56 | * @param array $styles key-value array of html styles |
57 | * @param string[] $allowedStyles list of allowed styles |
58 | * @param array $additional key-value array of additional styles should be added in front of list |
59 | * |
60 | * @return array |
61 | */ |
62 | public static function filterAllowedStyles( array $styles, array $allowedStyles, array $additional ): array { |
63 | return $additional + array_intersect_key( |
64 | $styles, |
65 | array_fill_keys( $allowedStyles, '' ) |
66 | ); |
67 | } |
68 | } |