Repeater.php
83 lines
| 1 | <?php |
| 2 | /** |
| 3 | * Repeater Customizer Setting. |
| 4 | * |
| 5 | * @package kirki-framework/control-repeater |
| 6 | * @copyright Copyright (c) 2023, Themeum |
| 7 | * @license https://opensource.org/licenses/MIT |
| 8 | * @since 1.0 |
| 9 | */ |
| 10 | |
| 11 | namespace Kirki\Settings; |
| 12 | |
| 13 | if ( ! defined( 'ABSPATH' ) ) { |
| 14 | exit; |
| 15 | } |
| 16 | |
| 17 | /** |
| 18 | * Repeater Settings. |
| 19 | */ |
| 20 | class Repeater extends \WP_Customize_Setting { |
| 21 | |
| 22 | /** |
| 23 | * Constructor. |
| 24 | * |
| 25 | * Any supplied $args override class property defaults. |
| 26 | * |
| 27 | * @access public |
| 28 | * @since 1.0 |
| 29 | * @param WP_Customize_Manager $manager The WordPress WP_Customize_Manager object. |
| 30 | * @param string $id A specific ID of the setting. Can be a theme mod or option name. |
| 31 | * @param array $args Setting arguments. |
| 32 | */ |
| 33 | public function __construct( $manager, $id, $args = [] ) { |
| 34 | parent::__construct( $manager, $id, $args ); |
| 35 | |
| 36 | // Will convert the setting from JSON to array. Must be triggered very soon. |
| 37 | add_filter( "customize_sanitize_{$this->id}", [ $this, 'sanitize_repeater_setting' ], 10, 1 ); |
| 38 | } |
| 39 | |
| 40 | /** |
| 41 | * Fetch the value of the setting. |
| 42 | * |
| 43 | * @access public |
| 44 | * @since 1.0 |
| 45 | * @return mixed The value. |
| 46 | */ |
| 47 | public function value() { |
| 48 | return (array) parent::value(); |
| 49 | } |
| 50 | |
| 51 | /** |
| 52 | * Convert the JSON encoded setting coming from Customizer to an Array. |
| 53 | * |
| 54 | * @access public |
| 55 | * @since 1.0 |
| 56 | * @param string $value URL Encoded JSON Value. |
| 57 | * @return array |
| 58 | */ |
| 59 | public function sanitize_repeater_setting( $value ) { |
| 60 | if ( ! is_array( $value ) ) { |
| 61 | $value = json_decode( urldecode( $value ) ); |
| 62 | } |
| 63 | |
| 64 | if ( empty( $value ) || ! is_array( $value ) ) { |
| 65 | $value = []; |
| 66 | } |
| 67 | |
| 68 | // Make sure that every row is an array, not an object. |
| 69 | foreach ( $value as $key => $val ) { |
| 70 | $value[ $key ] = (array) $val; |
| 71 | if ( empty( $val ) ) { |
| 72 | unset( $value[ $key ] ); |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | // Reindex array. |
| 77 | if ( is_array( $value ) ) { |
| 78 | $value = array_values( $value ); |
| 79 | } |
| 80 | |
| 81 | return $value; |
| 82 | } |
| 83 | } |