FormatList.php
72 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Give\Onboarding\Helpers; |
| 4 | |
| 5 | /** |
| 6 | * Formats an associative array into a JS parsable array of objects. |
| 7 | * |
| 8 | * @since 2.8.0 |
| 9 | */ |
| 10 | class FormatList { |
| 11 | |
| 12 | /** |
| 13 | * Format a JS value/label object where the $key is the `value` and the $value is the `label`. |
| 14 | * |
| 15 | * @param array $data |
| 16 | * |
| 17 | * @return array |
| 18 | * |
| 19 | * @since 2.8.0 |
| 20 | */ |
| 21 | public static function fromKeyValue( $data ) { |
| 22 | return self::format( |
| 23 | $data, |
| 24 | function( $key, $value ) { |
| 25 | return [ |
| 26 | 'value' => $key, |
| 27 | 'label' => $value, |
| 28 | ]; |
| 29 | } |
| 30 | ); |
| 31 | } |
| 32 | |
| 33 | /** |
| 34 | * Format a JS value/label object where the $key is the `label` and the $value is the `value`. |
| 35 | * |
| 36 | * @param array $data |
| 37 | * |
| 38 | * @return array |
| 39 | * |
| 40 | * @since 2.8.0 |
| 41 | */ |
| 42 | public static function fromValueKey( $data ) { |
| 43 | return self::format( |
| 44 | $data, |
| 45 | function( $key, $value ) { |
| 46 | return [ |
| 47 | 'value' => $value, |
| 48 | 'label' => $key, |
| 49 | ]; |
| 50 | } |
| 51 | ); |
| 52 | } |
| 53 | |
| 54 | /** |
| 55 | * A higher-order function to format a JS value/label object. |
| 56 | * |
| 57 | * @param array $data |
| 58 | * @param callable $function |
| 59 | * |
| 60 | * @return array |
| 61 | * |
| 62 | * @since 2.8.0 |
| 63 | */ |
| 64 | protected static function format( $data, $function ) { |
| 65 | return array_map( |
| 66 | $function, |
| 67 | array_keys( $data ), |
| 68 | array_values( $data ) |
| 69 | ); |
| 70 | } |
| 71 | } |
| 72 |