class-ecs-drb-source-json.php
| 1 | <?php |
| 2 | /** |
| 3 | * Dynamic Repeater Builder — Raw JSON Source |
| 4 | */ |
| 5 | |
| 6 | if ( ! defined( 'ABSPATH' ) ) { |
| 7 | exit; |
| 8 | } |
| 9 | |
| 10 | class ECS_DRB_Source_JSON extends ECS_DRB_Source_Base { |
| 11 | |
| 12 | public function get_id(): string { |
| 13 | return 'json'; |
| 14 | } |
| 15 | |
| 16 | public function get_label(): string { |
| 17 | return __( 'Raw JSON', 'ele-custom-skin' ); |
| 18 | } |
| 19 | |
| 20 | public function get_config_schema(): array { |
| 21 | return [ |
| 22 | [ |
| 23 | 'type' => 'info', |
| 24 | 'text' => __( 'Paste any JSON array here — each object becomes a repeater row. Useful for static data (menus, pricing, team members) or data copied from an external API. Go to Mapping to connect JSON keys to repeater fields, then Apply.', 'ele-custom-skin' ), |
| 25 | ], |
| 26 | [ |
| 27 | 'key' => 'json', |
| 28 | 'label' => __( 'JSON Array', 'ele-custom-skin' ), |
| 29 | 'type' => 'textarea', |
| 30 | 'default' => '[]', |
| 31 | 'placeholder' => '[{"field":"value"},{"field":"value2"}]', |
| 32 | ], |
| 33 | ]; |
| 34 | } |
| 35 | |
| 36 | public function get_available_fields( array $config ): array { |
| 37 | $rows = $this->get_rows( $config ); |
| 38 | if ( empty( $rows ) ) { |
| 39 | return []; |
| 40 | } |
| 41 | $keys = array_keys( $rows[0] ); |
| 42 | return array_map( fn( $k ) => [ 'key' => $k, 'label' => $k ], $keys ); |
| 43 | } |
| 44 | |
| 45 | public function get_rows( array $config ): array { |
| 46 | $json = $config['json'] ?? '[]'; |
| 47 | $data = json_decode( $json, true ); |
| 48 | |
| 49 | if ( ! is_array( $data ) ) { |
| 50 | return []; |
| 51 | } |
| 52 | |
| 53 | $rows = array_values( array_filter( $data, 'is_array' ) ); |
| 54 | |
| 55 | // Flatten scalar values. |
| 56 | return array_map( function ( $row ) { |
| 57 | $clean = []; |
| 58 | foreach ( $row as $key => $val ) { |
| 59 | $clean[ sanitize_key( $key ) ] = is_array( $val ) ? wp_json_encode( $val ) : (string) $val; |
| 60 | } |
| 61 | return $clean; |
| 62 | }, $rows ); |
| 63 | } |
| 64 | } |
| 65 |