je-query-object-handlers
2 years ago
get-from-field.php
2 years ago
get-from-je-query.php
2 years ago
get-from-je-query.php
101 lines
| 1 | <?php |
| 2 | |
| 3 | namespace JFB_Compatibility\Jet_Engine\Generators; |
| 4 | |
| 5 | use JFB_Compatibility\Jet_Engine\Generators\Je_Query_Object_Handlers\Base_Object_Handler; |
| 6 | use JFB_Compatibility\Jet_Engine\Generators\Je_Query_Object_Handlers\User_Object_Handler; |
| 7 | use Jet_Form_Builder\Generators\Base; |
| 8 | use Jet_Engine\Query_Builder\Manager as Query_Manager; |
| 9 | |
| 10 | // If this file is called directly, abort. |
| 11 | if ( ! defined( 'WPINC' ) ) { |
| 12 | die; |
| 13 | } |
| 14 | |
| 15 | class Get_From_Je_Query extends Base { |
| 16 | |
| 17 | private $object_handlers; |
| 18 | |
| 19 | public function __construct() { |
| 20 | $this->object_handlers = apply_filters( |
| 21 | 'jet-form-builder/generators/get_from_query/handlers', |
| 22 | array( |
| 23 | new User_Object_Handler(), |
| 24 | new Base_Object_Handler(), |
| 25 | ) |
| 26 | ); |
| 27 | } |
| 28 | |
| 29 | /** |
| 30 | * Returns generator ID |
| 31 | * |
| 32 | * @return string |
| 33 | */ |
| 34 | public function get_id() { |
| 35 | return 'get_from_query'; |
| 36 | } |
| 37 | |
| 38 | /** |
| 39 | * Returns generator name |
| 40 | * |
| 41 | * @return string |
| 42 | */ |
| 43 | public function get_name() { |
| 44 | return __( 'Get values list from JetEngine Query', 'jet-form-builder' ); |
| 45 | } |
| 46 | |
| 47 | /** |
| 48 | * Returns generated options list |
| 49 | * |
| 50 | * @param $args |
| 51 | * |
| 52 | * @return array |
| 53 | */ |
| 54 | public function generate( $args ) { |
| 55 | |
| 56 | $field = $args['generator_field'] ?? $args; |
| 57 | |
| 58 | $args = explode( '|', $field ); |
| 59 | $query = Query_Manager::instance()->get_query_by_id( $args[0] ); |
| 60 | $result = array(); |
| 61 | |
| 62 | if ( ! $query ) { |
| 63 | return $result; |
| 64 | } |
| 65 | |
| 66 | $query->setup_query(); |
| 67 | $objects = $query->_get_items(); |
| 68 | |
| 69 | $handler = $this->get_handler( $objects[0] ?? array() ); |
| 70 | $handler->set_fields( $args ); |
| 71 | |
| 72 | foreach ( $objects as $object ) { |
| 73 | $item = $handler->to_array( $object ); |
| 74 | |
| 75 | if ( ! empty( $item ) ) { |
| 76 | $result[] = $item; |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | return $result; |
| 81 | } |
| 82 | |
| 83 | private function get_handler( $current ): Base_Object_Handler { |
| 84 | /** @var Base_Object_Handler $handler */ |
| 85 | foreach ( $this->object_handlers as $handler ) { |
| 86 | if ( $handler->is_supported( $current ) ) { |
| 87 | return $handler; |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | wp_die( |
| 92 | sprintf( |
| 93 | /* translators: %s - class name */ |
| 94 | esc_html__( '%s::is_supported must return TRUE', 'jet-form-builder' ), |
| 95 | esc_attr( Base_Object_Handler::class ) |
| 96 | ) |
| 97 | ); |
| 98 | } |
| 99 | |
| 100 | } |
| 101 |