FormatList.php
80 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 | /** |
| 14 | * Format a JS value/label object where the $key is the `value` and the $value is the `label`. |
| 15 | * |
| 16 | * @since 2.8.0 |
| 17 | * |
| 18 | * @param array $data |
| 19 | * |
| 20 | * @return array |
| 21 | * |
| 22 | */ |
| 23 | public static function fromKeyValue($data) |
| 24 | { |
| 25 | return self::format( |
| 26 | $data, |
| 27 | function ($key, $value) { |
| 28 | return [ |
| 29 | 'value' => $key, |
| 30 | 'label' => $value, |
| 31 | ]; |
| 32 | } |
| 33 | ); |
| 34 | } |
| 35 | |
| 36 | /** |
| 37 | * Format a JS value/label object where the $key is the `label` and the $value is the `value`. |
| 38 | * |
| 39 | * @since 2.8.0 |
| 40 | * |
| 41 | * @param array $data |
| 42 | * |
| 43 | * @return array |
| 44 | * |
| 45 | */ |
| 46 | public static function fromValueKey($data) |
| 47 | { |
| 48 | return self::format( |
| 49 | $data, |
| 50 | function ($key, $value) { |
| 51 | return [ |
| 52 | 'value' => $value, |
| 53 | 'label' => $key, |
| 54 | ]; |
| 55 | } |
| 56 | ); |
| 57 | } |
| 58 | |
| 59 | /** |
| 60 | * A higher-order function to format a JS value/label object. |
| 61 | * |
| 62 | * @since 2.8.0 |
| 63 | * |
| 64 | * @param callable $function |
| 65 | * |
| 66 | * @param array $data |
| 67 | * |
| 68 | * @return array |
| 69 | * |
| 70 | */ |
| 71 | protected static function format($data, $function) |
| 72 | { |
| 73 | return array_map( |
| 74 | $function, |
| 75 | array_keys($data), |
| 76 | array_values($data) |
| 77 | ); |
| 78 | } |
| 79 | } |
| 80 |