|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace JustCoded\WP\Framework\ACF; |
| 4 | + |
| 5 | +use StoutLogic\AcfBuilder\Builder; |
| 6 | +use StoutLogic\AcfBuilder\FieldBuilder; |
| 7 | +use StoutLogic\AcfBuilder\FieldsBuilder; |
| 8 | + |
| 9 | +trait Has_ACF_Fields { |
| 10 | + /** |
| 11 | + * @var FieldsBuilder[] |
| 12 | + */ |
| 13 | + protected $fields; |
| 14 | + |
| 15 | + /** |
| 16 | + * Add field definition to internal stack. |
| 17 | + * |
| 18 | + * @param FieldsBuilder ...$fields FieldsBuilder objects to be added. |
| 19 | + */ |
| 20 | + public function has( ...$fields ) { |
| 21 | + /* @var FieldsBuilder[] $args */ |
| 22 | + $args = func_get_args(); |
| 23 | + |
| 24 | + foreach ( $args as $group ) { |
| 25 | + $group = $group->getRootContext(); |
| 26 | + |
| 27 | + $this->set_responsive_width_classes( $group->getFields() ); |
| 28 | + |
| 29 | + $this->fields[ $group->getName() ] = $group; |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + /** |
| 34 | + * Update fields wrapper for responsive. |
| 35 | + * |
| 36 | + * @param FieldBuilder[] $fields Group fields. |
| 37 | + */ |
| 38 | + public function set_responsive_width_classes( $fields ) { |
| 39 | + if ( ! empty( $fields ) ) { |
| 40 | + foreach ( $fields as $field ) { |
| 41 | + $wrapper = $field->getWrapper(); |
| 42 | + $width = isset( $wrapper['width'] ) ? $wrapper['width'] : '100%'; |
| 43 | + if ( false !== strpos( $width, '%' ) ) { |
| 44 | + $width = trim( $width, '%' ); |
| 45 | + // Set attr class. |
| 46 | + $field->setAttr( 'class', 'jc_acf_fields jc_acf_fields_' . $width ); |
| 47 | + // Set block layout for responsive. |
| 48 | + $field->setConfig( 'layout', 'block' ); |
| 49 | + // Clear field width. |
| 50 | + $field->setWidth( '' ); |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + /** |
| 57 | + * Build a fields group configuration object |
| 58 | + * |
| 59 | + * @param string|null $name Group name. |
| 60 | + * @param array $group_config Group config. |
| 61 | + * |
| 62 | + * @return FieldsBuilder |
| 63 | + */ |
| 64 | + public function build( string $name = '', array $group_config = [] ) { |
| 65 | + // take current class short name as field name. |
| 66 | + if ( empty( $name ) ) { |
| 67 | + $class_name_parts = explode( '\\', get_class( $this ) ); |
| 68 | + $class_short_name = strtolower( end( $class_name_parts ) ); |
| 69 | + if ( ! isset( $this->fields[ $class_short_name ] ) ) { |
| 70 | + $name = $class_short_name; |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + return new FieldsBuilder( $name, $group_config ); |
| 75 | + } |
| 76 | +} |
0 commit comments