shipping_method = $shipping_method; $this->nonce_name = $nonce_name; } /** * Fires hooks. * */ public function hooks() { add_action( 'wp_ajax_dhl_search_machines_via_ajax', array( $this, 'wp_ajax_dhl_search_parcels_via_ajax') ); add_action( 'wp_ajax_nopriv_dhl_search_machines_via_ajax', array( $this, 'wp_ajax_dhl_search_parcels_via_ajax') ); } /** * Execute AJAX request * * @return void */ public function wp_ajax_dhl_search_parcels_via_ajax() { check_ajax_referer( 'woocommerce-dhl', 'security' ); $all_parcels = array(); $this->requests = new WPDesk_WooCommerce_DHL_Ajax_Request( $this->nonce_name, $_POST ); $this->parcels = $this->get_list_of_parcels(); $sap = $this->requests->getCode(); $all_parcels['items'] = $this->get_parcel_by_city(); if ( ! empty( $sap ) && isset( $this->parcels[ $sap ] ) ) { wp_send_json( array( 'id' => $sap, 'text' => $this->parcels[ $sap ] ) ); } wp_send_json( $all_parcels ); } /** * Append parcels. * * @param array $parcels Parcels. * @param array $parcels_to_append Parcels to append. * * @return array */ private function append_parcels( array $parcels, array $parcels_to_append ) { foreach ( $parcels_to_append as $key => $value ) { $parcels[ $key ] = $value; } return $parcels; } /** * Return a list of parcels * * @return array */ public function get_list_of_parcels() { $list_of_parcels = $this->shipping_method->getListOfParcels(); return $this->append_parcels( $this->append_parcels( array(), isset( $list_of_parcels['dhl_parcelshop_nearest'] ) ? $list_of_parcels['dhl_parcelshop_nearest'] : array() ), isset( $list_of_parcels['dhl_parcelshop_other'] ) ? $list_of_parcels['dhl_parcelshop_other'] : array() ); } /** * Return a list of parcels for city request * * @return array */ public function get_parcel_by_city() { if ( strlen( $this->requests->getCity() ) >= self::MIN_LENGTH ) { $items = array(); $phrase = explode( ' ', $this->requests->getCity() ); $phrase = str_replace(',', '', $phrase ); $pattern = '/^.+(' . implode( ').+(', $phrase ) . ').+/iu'; $results = preg_grep( $pattern, $this->parcels ); foreach ( $results as $key => $item ) { $items[] = array( 'id' => $key, 'text' => $item, ); } return $items; } return array(); } }