jetformbuilder
/
modules
/
advanced-choices
/
block-sanitizers
/
choice-single-context-sanitizer.php
choice-single-context-sanitizer.php
66 lines
| 1 | <?php |
| 2 | |
| 3 | |
| 4 | namespace JFB_Modules\Advanced_Choices\Block_Sanitizers; |
| 5 | |
| 6 | use Jet_Form_Builder\Blocks\Module; |
| 7 | use JFB_Modules\Advanced_Choices\Block_Types\Choices_Field; |
| 8 | use JFB_Modules\Block_Sanitizer\Interfaces\Block_Context_Sanitizer_Interface; |
| 9 | use JFB_Modules\Block_Sanitizer\Interfaces\For_Blocks_Sanitizer_Interface; |
| 10 | use JFB_Modules\Block_Sanitizer\Traits\For_Blocks_Sanitizer_Trait; |
| 11 | use JFB_Modules\Blocks_V2\Repeater_Field\Block_Type_Row; |
| 12 | |
| 13 | // If this file is called directly, abort. |
| 14 | if ( ! defined( 'WPINC' ) ) { |
| 15 | die; |
| 16 | } |
| 17 | |
| 18 | class Choice_Single_Context_Sanitizer implements Block_Context_Sanitizer_Interface, For_Blocks_Sanitizer_Interface { |
| 19 | |
| 20 | use For_Blocks_Sanitizer_Trait; |
| 21 | |
| 22 | public function for_blocks(): array { |
| 23 | return array( |
| 24 | 'choice', |
| 25 | 'choice-control', |
| 26 | ); |
| 27 | } |
| 28 | |
| 29 | public function apply_block_context( array $block_context, array $parsed_block, $parent_block = null ): array { |
| 30 | |
| 31 | /** @var Module $blocks */ |
| 32 | /** @noinspection PhpUnhandledExceptionInspection */ |
| 33 | $blocks = jet_form_builder()->module( 'blocks' ); |
| 34 | $block = $blocks->get_field_by_name( $parsed_block ); |
| 35 | $root = $blocks->get_field_by_name( 'choices-field' ); |
| 36 | $name = $block_context[ Choices_Field::CONTEXT_NAME ] ?? ''; |
| 37 | |
| 38 | if ( ! $block || |
| 39 | ! $name || |
| 40 | ! empty( $block_context[ Choices_Field::CONTEXT_DEFAULT ] ) || |
| 41 | ! isset( $block_context[ Block_Type_Row::CONTEXT_DEFAULT ][ $name ] ) |
| 42 | ) { |
| 43 | return $block_context; |
| 44 | } |
| 45 | |
| 46 | $multiple = $block_context[ Choices_Field::CONTEXT_MULTIPLE ] ?? false; |
| 47 | $preset_ref = &$block_context[ Choices_Field::CONTEXT_DEFAULT ]; |
| 48 | |
| 49 | $preset_ref = $root->get_prepared_default( $block_context[ Block_Type_Row::CONTEXT_DEFAULT ][ $name ] ); |
| 50 | |
| 51 | // if enabled "checkbox-mode" - just skip |
| 52 | if ( $multiple ) { |
| 53 | return $block_context; |
| 54 | } |
| 55 | |
| 56 | // save only first value |
| 57 | foreach ( $preset_ref as $item ) { |
| 58 | $preset_ref = array( $item ); |
| 59 | break; |
| 60 | } |
| 61 | |
| 62 | return $block_context; |
| 63 | } |
| 64 | |
| 65 | } |
| 66 |