| 1 |
<?php |
| 2 |
|
| 3 |
namespace Elementor\Modules\AtomicWidgets\CssConverter\Converters; |
| 4 |
|
| 5 |
use Elementor\Modules\AtomicWidgets\CssConverter\Conversion_Context; |
| 6 |
use Elementor\Modules\AtomicWidgets\CssConverter\Property_Converter_Base; |
| 7 |
use Elementor\Modules\AtomicWidgets\PropTypes\Primitives\String_Prop_Type; |
| 8 |
|
| 9 |
if ( ! defined( 'ABSPATH' ) ) { |
| 10 |
exit; // Exit if accessed directly. |
| 11 |
} |
| 12 |
|
| 13 |
/** |
| 14 |
* Reusable converter for properties backed by a String_Prop_Type (or a subclass with its own |
| 15 |
* `$$type` key, e.g. Font_Family_Prop_Type). One instance per property. When an allowlist is |
| 16 |
* provided the value must be one of it (enum-backed props); otherwise any non-empty value is |
| 17 |
* accepted (free-string props). Emits the canonical PropValue enveloped with the schema's own |
| 18 |
* `$$type` key, sourced from the live schema rather than hardcoded, so subclasses that override |
| 19 |
* get_key() (like Font_Family_Prop_Type) still validate against Props_Parser. |
| 20 |
*/ |
| 21 |
class String_Property_Converter extends Property_Converter_Base { |
| 22 |
private string $property; |
| 23 |
|
| 24 |
/** |
| 25 |
* @var string[]|null |
| 26 |
*/ |
| 27 |
private ?array $allowed_values; |
| 28 |
|
| 29 |
private string $type_key; |
| 30 |
|
| 31 |
/** |
| 32 |
* @param string $property The schema property this converter owns. |
| 33 |
* @param string[]|null $allowed_values Enum allowlist, or null for a free-string property. |
| 34 |
* @param string|null $type_key The `$$type` key to envelope the value with, sourced from |
| 35 |
* the schema's prop type (e.g. `font-family`). Defaults to |
| 36 |
* the plain String_Prop_Type key. |
| 37 |
*/ |
| 38 |
public function __construct( string $property, ?array $allowed_values = null, ?string $type_key = null ) { |
| 39 |
$this->property = $property; |
| 40 |
$this->allowed_values = $allowed_values; |
| 41 |
$this->type_key = $type_key ?? String_Prop_Type::get_key(); |
| 42 |
} |
| 43 |
|
| 44 |
protected function get_supported_properties(): array { |
| 45 |
return [ $this->property ]; |
| 46 |
} |
| 47 |
|
| 48 |
protected function do_convert( Conversion_Context $context, array $rule ): bool { |
| 49 |
$value = trim( $rule['value'] ); |
| 50 |
|
| 51 |
if ( '' === $value ) { |
| 52 |
return false; |
| 53 |
} |
| 54 |
|
| 55 |
if ( null !== $this->allowed_values && ! in_array( $value, $this->allowed_values, true ) ) { |
| 56 |
return false; |
| 57 |
} |
| 58 |
|
| 59 |
$context->set_prop( $this->property, [ |
| 60 |
'$$type' => $this->type_key, |
| 61 |
'value' => $value, |
| 62 |
] ); |
| 63 |
|
| 64 |
return true; |
| 65 |
} |
| 66 |
} |
| 67 |
|