HasOptions.php
| 1 | <?php |
| 2 | |
| 3 | namespace Give\Framework\FieldsAPI\Concerns; |
| 4 | |
| 5 | use Give\Framework\FieldsAPI\Option; |
| 6 | |
| 7 | trait HasOptions { |
| 8 | |
| 9 | /** @var Option[] */ |
| 10 | protected $options = []; |
| 11 | |
| 12 | /** |
| 13 | * Set the options |
| 14 | * |
| 15 | * Note that the keys of associative arrays are not supported for setting values or labels. |
| 16 | * For setting labels either use `new FieldOption($value, $label)` or `[$value, $label]`. |
| 17 | * In either case, the label is optional. |
| 18 | * |
| 19 | * @param Option|array|mixed ...$options |
| 20 | * |
| 21 | * @return $this |
| 22 | */ |
| 23 | public function options( ...$options ) { |
| 24 | // Reset options, since they are meant to be set immutably |
| 25 | $this->options = []; |
| 26 | |
| 27 | // Loop through the options and transform them to the proper format. |
| 28 | foreach ( $options as $value ) { |
| 29 | if ( $value instanceof Option ) { |
| 30 | // In this case, what is provided matches the proper format, so we can just append it. |
| 31 | $this->options[] = $value; |
| 32 | } elseif ( is_array( $value ) ) { |
| 33 | // In this case, what has been provided in the value is an array with a value then a label. |
| 34 | // This matches the constructor of `FieldOption`, so we can unpack it as arguments for a new instance. |
| 35 | $this->options[] = new Option( ...$value ); |
| 36 | } else { |
| 37 | // In this case, we just have a value which is the bare minimum required for a `FieldOption`. |
| 38 | $this->options[] = new Option( $value ); |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | return $this; |
| 43 | } |
| 44 | |
| 45 | /** |
| 46 | * Access the options |
| 47 | * |
| 48 | * @return Option[] |
| 49 | */ |
| 50 | public function getOptions() { |
| 51 | return $this->options; |
| 52 | } |
| 53 | |
| 54 | /** |
| 55 | * Check whether options exist |
| 56 | * |
| 57 | * @since 2.15.0 |
| 58 | * |
| 59 | * @return bool |
| 60 | */ |
| 61 | public function hasOptions() { |
| 62 | return (bool) count( $this->options ); |
| 63 | } |
| 64 | |
| 65 | /** |
| 66 | * Walk through the options |
| 67 | * |
| 68 | * @since 2.12.0 |
| 69 | * |
| 70 | * @param callable $callback |
| 71 | * |
| 72 | * @return void |
| 73 | */ |
| 74 | public function walkOptions( callable $callback ) { |
| 75 | foreach ( $this->options as $option ) { |
| 76 | // Call the callback for each option. |
| 77 | if ( $callback( $option ) === false ) { |
| 78 | // Returning false breaks the loop. |
| 79 | break; |
| 80 | } |
| 81 | } |
| 82 | } |
| 83 | } |
| 84 |