| 1 |
<?php |
| 2 |
|
| 3 |
namespace Elementor\Modules\AtomicWidgets\CssConverter\ValueParsers; |
| 4 |
|
| 5 |
if ( ! defined( 'ABSPATH' ) ) { |
| 6 |
exit; // Exit if accessed directly. |
| 7 |
} |
| 8 |
|
| 9 |
/** |
| 10 |
* Stateless parser for the CSS box shorthands (padding/margin/border-width/border-radius): a raw |
| 11 |
* value -> 1..4 Size leaves, or null to decline (the caller routes the declaration to custom_css). |
| 12 |
* It never touches the registry, context, or PropTypes; the caller maps the result onto its own keys. |
| 13 |
* |
| 14 |
* Tokenizing is paren-aware so function values such as calc(100% / 4) survive as one token (and are |
| 15 |
* parsed as a Size leaf). This also makes the elliptical border-radius form (a "/" separator) decline |
| 16 |
* for free: a bare "/" is an unparsable token, and "a / b" exceeds four tokens. |
| 17 |
* |
| 18 |
* - 1 token -> [ 'single' => <Size leaf> ] (the union's Size member) |
| 19 |
* - 2-4 tokens -> [ 'sides' => [ s0, s1, s2, s3 ] ] (expanded via the CSS box rule) |
| 20 |
* - 0 / >4 tokens, or any unparsable token -> null |
| 21 |
*/ |
| 22 |
class Box_Shorthand_Parser { |
| 23 |
const MAX_SIDES = 4; |
| 24 |
|
| 25 |
/** |
| 26 |
* @return array{single: array}|array{sides: array<int, array>}|null |
| 27 |
*/ |
| 28 |
public static function parse( string $value ): ?array { |
| 29 |
$tokens = Css_Token_Splitter::split_by_whitespace( trim( $value ) ); |
| 30 |
$count = count( $tokens ); |
| 31 |
|
| 32 |
if ( $count < 1 || $count > self::MAX_SIDES ) { |
| 33 |
return null; |
| 34 |
} |
| 35 |
|
| 36 |
$sizes = []; |
| 37 |
|
| 38 |
foreach ( $tokens as $token ) { |
| 39 |
$parsed = Size_Value_Parser::parse( $token ); |
| 40 |
|
| 41 |
if ( null === $parsed ) { |
| 42 |
return null; |
| 43 |
} |
| 44 |
|
| 45 |
$sizes[] = $parsed; |
| 46 |
} |
| 47 |
|
| 48 |
if ( 1 === $count ) { |
| 49 |
return [ 'single' => $sizes[0] ]; |
| 50 |
} |
| 51 |
|
| 52 |
return [ 'sides' => self::expand_box( $sizes ) ]; |
| 53 |
} |
| 54 |
|
| 55 |
/** |
| 56 |
* Expand 2..4 values onto four sides via the CSS box rule. The result is positional and the same |
| 57 |
* for every box shorthand; the caller assigns the four slots to its own keys. |
| 58 |
* |
| 59 |
* @param array<int, array> $sizes 2..4 parsed Size leaves. |
| 60 |
* @return array{0: array, 1: array, 2: array, 3: array} |
| 61 |
*/ |
| 62 |
private static function expand_box( array $sizes ): array { |
| 63 |
switch ( count( $sizes ) ) { |
| 64 |
case 2: |
| 65 |
return [ $sizes[0], $sizes[1], $sizes[0], $sizes[1] ]; |
| 66 |
case 3: |
| 67 |
return [ $sizes[0], $sizes[1], $sizes[2], $sizes[1] ]; |
| 68 |
default: |
| 69 |
return [ $sizes[0], $sizes[1], $sizes[2], $sizes[3] ]; |
| 70 |
} |
| 71 |
} |
| 72 |
} |
| 73 |
|