Fields.php
95 lines
| 1 | <?php |
| 2 | namespace Give\FormAPI; |
| 3 | |
| 4 | use Give\FormAPI\Form\File; |
| 5 | use InvalidArgumentException; |
| 6 | use Give\FormAPI\Form\Colorpicker; |
| 7 | use Give\FormAPI\Form\Media; |
| 8 | use Give\FormAPI\Form\Radio; |
| 9 | use Give\FormAPI\Form\Text; |
| 10 | use Give\FormAPI\Form\Textarea; |
| 11 | use Give\FormAPI\Form\Wysiwyg; |
| 12 | use Give\FormAPI\Form\Group; |
| 13 | |
| 14 | class Fields { |
| 15 | /** |
| 16 | * Field vs class name mapping array |
| 17 | * |
| 18 | * @since 2.7.0 |
| 19 | * @var array |
| 20 | */ |
| 21 | private $fieldClasses = [ |
| 22 | 'text' => Text::class, |
| 23 | 'textarea' => Textarea::class, |
| 24 | 'file' => File::class, |
| 25 | 'media' => Media::class, |
| 26 | 'radio' => Radio::class, |
| 27 | 'wysiwyg' => Wysiwyg::class, |
| 28 | 'colorpicker' => Colorpicker::class, |
| 29 | 'group' => Group::class, |
| 30 | ]; |
| 31 | |
| 32 | /** |
| 33 | * Get field object. |
| 34 | * |
| 35 | * @since 2.7.0 |
| 36 | * @param array $array |
| 37 | * |
| 38 | * @return Form\Field |
| 39 | */ |
| 40 | public static function fromArray( $array ) { |
| 41 | $field = new static(); |
| 42 | $field->validate( $array ); |
| 43 | |
| 44 | /** |
| 45 | * Filter the field classes |
| 46 | * |
| 47 | * @since 2.7.0 |
| 48 | * @param Form\Field[] |
| 49 | */ |
| 50 | $field->fieldClasses = apply_filters( 'give_form_api_field_classes', $field->fieldClasses ); |
| 51 | |
| 52 | /* @var Form\Field $fieldClass */ |
| 53 | $fieldClass = $field->fieldClasses[ $field->getFieldType( $array['type'] ) ]; |
| 54 | |
| 55 | return $fieldClass::fromArray( $array ); |
| 56 | } |
| 57 | |
| 58 | /** |
| 59 | * Get field class name. |
| 60 | * Note: |
| 61 | * 1. Field name create with {fieldType_modifier} logic. Use underscore in field type only if you want to add a modifier. For example: text_small, radio_inline etc. |
| 62 | * 2. This function exist for backward compatibility and can be remove in future |
| 63 | * |
| 64 | * @param $type |
| 65 | * |
| 66 | * @return string |
| 67 | * @since 2.7.0 |
| 68 | */ |
| 69 | private function getFieldType( $type ) { |
| 70 | if ( false !== strpos( $type, '_' ) ) { |
| 71 | $type = current( explode( '_', $type, 2 ) ); |
| 72 | } |
| 73 | |
| 74 | return $type; |
| 75 | } |
| 76 | |
| 77 | /** |
| 78 | * Validate field arguments |
| 79 | * |
| 80 | * @since 2.7.0 |
| 81 | * |
| 82 | * @param array $array |
| 83 | * |
| 84 | * @throws InvalidArgumentException |
| 85 | */ |
| 86 | private function validate( $array ) { |
| 87 | $required = [ 'id', 'name', 'type' ]; |
| 88 | $array = array_filter( $array ); // Remove empty values. |
| 89 | |
| 90 | if ( array_diff( $required, array_keys( $array ) ) ) { |
| 91 | throw new InvalidArgumentException( __( 'To create a Field object, please provide valid id, name and type.', 'give' ) ); |
| 92 | } |
| 93 | } |
| 94 | } |
| 95 |