From 43fc808fc2f9be53cd66ed26b84c0a006e82356c Mon Sep 17 00:00:00 2001 From: Henner R Setyono Date: Mon, 17 Jan 2022 12:03:22 +0700 Subject: [PATCH] 2.0.2 - Added support for Localhost - Changed some coding style to remove empty space between parentheses. --- CHANGELOG.md | 80 -------------- README.md | 4 +- helper/rajaongkir.php | 194 +++++++++++++++++++++++++++++++++ module-admin/init-main.php | 54 ++++----- module-admin/init-zones.php | 68 ++++++------ module-admin/wcis-checkout.php | 40 ++++--- module-api/_index.php | 16 +-- module-api/json-update.php | 10 +- module-api/json/couriers.json | 65 ++++++----- module-api/rajaongkir.php | 85 --------------- module-api/static.php | 188 +++++++++++++++++--------------- module-checkout/fields.php | 14 +-- module-checkout/wcis-ajax.php | 24 ++-- woocommerce-indo-shipping.php | 65 ++++++----- 14 files changed, 473 insertions(+), 434 deletions(-) delete mode 100644 CHANGELOG.md create mode 100644 helper/rajaongkir.php delete mode 100644 module-api/rajaongkir.php diff --git a/CHANGELOG.md b/CHANGELOG.md deleted file mode 100644 index 856375d..0000000 --- a/CHANGELOG.md +++ /dev/null @@ -1,80 +0,0 @@ -## 1.1.4 - -- Fixed Sumatera Selatan (Province) not having correct ID. - -### 1.1.3 - -- Fixed City dropdown filter only searching title - -### 1.1.2 - -- Fixed compatibility with WooCommerce Edje plugin -- [Weight] Fixed weight not being calculated - -### 1.1.1 - -- Fixed City Field not updated after selecting the dropdown - -### 1.1.0 - -- Combine City and District into one SELECT, separated with optgroup - -### 1.0.0-beta5 - -- Removed the function that reorders checkout field. -- Fixed an error when choosing City Origin. -- Removed City Origin cache since it's no longer do API call to get the list. - -### 1.0.0-beta2 - -- Fixed a bug where Shipping cost doesn't initially load when customer has existing address. - -### 1.0.0-beta - -- City and District no longer uses API. All data stored internally in JSON. -- Added RPX, J&T, and PCP couriers. - -### 0.3.6 - -- Added City and District data as part of the plugin. No need to do API call just to get them. - -### 0.3.5b - -- Fixed Shipping Zone can't be removed - -### 0.3.5 - -- Fixed City origin not saving due to Enhanced Select bug. -- Add comment and add more PHPdoc - -### 0.3.4 - -- Add prefix to city with same name. Example: "Bandung (Kota)" and "Bandung (Kabupaten)" - -### 0.3.3 - -- Fix for initial installation - -### 0.3.2 - -- Directory structure changes -- Namespace the landing code with class - -### 0.3.1 - -- Fixed plugin not working on new website. -- Added Global settings, you still need to set individual shipping zones for it to work. - -### 0.3.0 - -- Added support to Shipping Zone for WooCommerce 2.6 -- Remove select2 on City and District field - -### 0.2.1 - -- Refactor open function name into Class. -- Fix bug when using WooCommerce 2.6 - -### 0.2.0 - -- Fully functional diff --git a/README.md b/README.md index 2fa9768..0b696a0 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,9 @@ Ultimate *Ongkos Kirim* Plugin for major Indonesian Shipping courier. -Add JNE, TIKI, POS, PCP, RPX, and J&T Express to your WooCommerce. Requires PRO License purchase from RajaOngkir.com. We are not affiliated with RajaOngkir in any way. +Add JNE, TIKI, POS, PCP, RPX, and J&T Express to your WooCommerce. + +**Important:** Requires PRO License purchase from RajaOngkir.com. We are not affiliated with RajaOngkir in any way. This plugin is free and provided as is. If you found a bug, please submit it [here](https://github.com/hrsetyono/wc-indo-shipping/issues). diff --git a/helper/rajaongkir.php b/helper/rajaongkir.php new file mode 100644 index 0000000..e72e9ba --- /dev/null +++ b/helper/rajaongkir.php @@ -0,0 +1,194 @@ +api_key = $key; + } + else { + $cached_license = get_transient('wcis_license'); + $this->api_key = $cached_license['key']; + } + } + + + /** + * Test if API key is working + * + * @return bool + */ + function is_valid() { + $result = $this->get('/province', [], false); + $status = wp_remote_retrieve_response_code($result); + return $status === 200; + } + + + /** + * Get shipping costs + * + * @param array $args - Formatted argument ready for API call + * @return array - JSON response + */ + function get_costs($args) { + $result = $this->post('/cost', $args); + + if($result) { + $costs = $result['rajaongkir']['results'] ?? null; + return $costs; + } else { + return $result; + } + } + + ///// + + + /** + * GET request + * + * @param string $endpoint + * @param array $args - The URL params + * @param boolean $return_only_body + * + * @since 2.1.0 + */ + function get($endpoint, $args = [], $return_only_body = true) { + $url = $this->get_endpoint_url($endpoint); + + if(!empty($args)) { + $url = sprintf('%s?%s', $url, http_build_query($args)); + } + + $result = wp_remote_get($url, [ + 'headers' => [ 'key' => $this->api_key ], + 'sslverify' => WP_DEBUG === true ? false : true, + ]); + + if(is_wp_error($result)) { + return $result->get_error_message(); + } + + if($return_only_body) { + return json_decode($result['body'], true); + } + + return $result; + } + + /** + * POST request + * + * @param string $endpoint + * @param array $args - The URL params + * @param boolean $return_only_body + * + * @since 2.1.0 + */ + function post($endpoint, $args = [], $return_only_body = true) { + $url = $this->get_endpoint_url($endpoint); + + $result = wp_remote_post($url, [ + 'headers' => [ 'key' => $this->api_key ], + 'body' => $args, + 'sslverify' => WP_DEBUG === true ? false : true, + ]); + + if(is_wp_error($result)) { + return $result->get_error_message(); + } + + if($return_only_body) { + return json_decode($result['body'], true); + } + + return $result; + } + + /** + * if URL doesn't start with "http", prepend base URL + * + * @since 2.1.0 + */ + private function get_endpoint_url($endpoint) { + $is_full_url = preg_match('/^http/', $endpoint, $matches); + $url = $is_full_url ? $endpoint : sprintf('%s%s', $this->base_url, $endpoint); + + return $url; + } + + + + /** + * GET request using Curl + * + * @deprecated 2.1.0 - Use wp_remote_get() instead + * + * @param string $endpoint + * @param array $args - The URL params + */ + function get_curl($endpoint, $args = []) { + $url = $this->get_endpoint_url($endpoint); + + if(!empty($args)) { + $url = sprintf('%s?%s', $url, http_build_query($args)); + } + + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $url); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1) ; + curl_setopt($ch, CURLOPT_HTTPHEADER, [ + 'key:' . $this->api_key, + ]); + + if (WP_DEBUG) { + curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); + } + + $result = curl_exec($ch); + curl_close($ch); + + return json_decode($result, true); + } + + /** + * POST request using Curl + * + * @deprecated 2.1.0 - Use wp_remote_post() instead + * + * @param string $endpoint + * @param array $body + */ + function post_curl($endpoint, $body = []) { + $url = $this->get_endpoint_url($endpoint); + $payload = json_encode($body); + + // Prepare new cURL resource + $ch = curl_init($url); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLINFO_HEADER_OUT, true); + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); + + // Set HTTP Header for POST request + curl_setopt($ch, CURLOPT_HTTPHEADER, [ + 'key:' . $this->api_key, + 'Content-Type: application/json', + 'Content-Length: ' . strlen($payload) + ]); + + // Submit the POST request + $response = curl_exec($ch); + curl_close($ch); + + return $response; + } +} diff --git a/module-admin/init-main.php b/module-admin/init-main.php index d816428..9040594 100644 --- a/module-admin/init-main.php +++ b/module-admin/init-main.php @@ -1,7 +1,9 @@ init_form_fields(); // allow save setting - add_action('woocommerce_update_options_shipping_' . $this->id, array($this, 'process_admin_options') ); - add_action('woocommerce_update_options_shipping_' . $this->id, array($this, 'process_admin_transients') ); + add_action('woocommerce_update_options_shipping_' . $this->id, [$this, 'process_admin_options']); + add_action('woocommerce_update_options_shipping_' . $this->id, [$this, 'process_admin_transients']); } - /* - Initiate global setting page for WCIS - */ + /** + * Initiate global setting page for WCIS + */ function init_form_fields() { $enabled_field = array( 'title' => __('Enable/Disable'), @@ -76,24 +78,24 @@ function init_form_fields() { * Add API Key to Transient so it's cached */ function process_admin_transients() { - $t_license = get_transient( 'wcis_license' ); + $t_license = get_transient('wcis_license'); $post_data = $this->get_post_data(); $key = $post_data['woocommerce_wcis_key']; // check license - $license_valid = isset( $t_license['valid'] ) && $t_license['valid'] === true; - $license_different = isset( $t_license['key'] ) && $t_license['key'] === $key; + $license_valid = isset($t_license['valid']) && $t_license['valid']; + $license_different = isset($t_license['key']) && $t_license['key'] === $key; // if not valid OR different from before, update transient - if( !$license_valid || $license_different ) { - $rj = new RajaOngkir( $key ); + if(!$license_valid || $license_different) { + $rj = new RajaOngkir($key); $t_license = [ 'key' => $key, 'valid' => $rj->is_valid() ]; - set_transient( 'wcis_license', $t_license, 60*60*24*30 ); + set_transient('wcis_license', $t_license, 60*60*24*30); } return $t_license; @@ -103,19 +105,18 @@ function process_admin_transients() { ///// - /* - Validate API Key by doing a sample AJAX call - - @return bool - */ + /** + * Validate API Key by doing a sample AJAX call + * @return bool + */ private function check_key_valid() { - $license = get_transient( 'wcis_license' ); + $license = get_transient('wcis_license'); // if key doesn't exist, abort - if( !isset( $license['key'] ) ) { return false; } + if(!isset($license['key'])) { return false; } // if valid, return success - if( isset( $license['valid'] ) && $license['valid'] === true ) { + if(isset($license['valid']) && $license['valid']) { $msg = __('API Connected!'); $this->form_fields['key']['description'] = '' . $msg . ''; } @@ -127,11 +128,10 @@ private function check_key_valid() { return $license['valid']; } - /* - Get cities list from cache. Cached when the setting is saved. - - @return array - List of cities in base province - */ + /** + * Get cities list from cache. Cached when the setting is saved. + * @return array - List of cities in base province + */ private function get_cities_origin() { $country = wc_get_base_location(); $prov_id = wcis_get_province_id( $country['state'] ); diff --git a/module-admin/init-zones.php b/module-admin/init-zones.php index 7f8b199..6756179 100644 --- a/module-admin/init-zones.php +++ b/module-admin/init-zones.php @@ -6,9 +6,9 @@ class WCIS_Zones_Method extends WC_Shipping_Method { private $api; private $main_settings; - public function __construct( $instance_id = 0 ) { + public function __construct($instance_id = 0) { $this->id = 'wcis_zone'; - $this->instance_id = absint( $instance_id ); + $this->instance_id = absint($instance_id); $this->title = __('Indo Shipping'); $this->method_title = __('Indo Shipping'); @@ -16,11 +16,11 @@ public function __construct( $instance_id = 0 ) { $this->supports = array('shipping-zones', 'instance-settings',); // global - $this->main_settings = get_option( 'woocommerce_wcis_settings' ); - $this->api = new RajaOngkir( $this->main_settings['key'] ); + $this->main_settings = get_option('woocommerce_wcis_settings'); + $this->api = new RajaOngkir($this->main_settings['key']); // allow save setting - add_action('woocommerce_update_options_shipping_' . $this->id, array( $this, 'process_admin_options' ) ); + add_action('woocommerce_update_options_shipping_' . $this->id, [$this, 'process_admin_options']); } /** @@ -28,15 +28,15 @@ public function __construct( $instance_id = 0 ) { * * @param mixed $package */ - function calculate_shipping( $package = [] ) { + function calculate_shipping($package = []) { // if district not exists or empty - $id_exists = array_key_exists( 'destination_id', $package['destination'] ); - if( !$id_exists || empty( $package['destination']['destination_id'] ) ) { + $id_exists = array_key_exists('destination_id', $package['destination']); + if(!$id_exists || empty($package['destination']['destination_id'])) { return false; } - $costs = $this->_get_costs( $package ); - $this->_set_rate( $costs ); + $costs = $this->_get_costs($package); + $this->_set_rate($costs); } ///// @@ -48,8 +48,8 @@ function calculate_shipping( $package = [] ) { * @param array $package - The shipping detail * @return array - List of cost grouped by each courier */ - private function _get_costs( $package ) { - $weight = $this->_calculate_weight( $package ); + private function _get_costs($package) { + $weight = $this->_calculate_weight($package); $selected_couriers = $this->_get_selected_couriers(); $args = [ @@ -62,7 +62,7 @@ private function _get_costs( $package ) { ]; // get the cost - $costs = $this->api->get_costs( $args ); + $costs = $this->api->get_costs($args); return $costs; } @@ -71,37 +71,37 @@ private function _get_costs( $package ) { * * @param array $costs - Cost list from API */ - private function _set_rate( $costs ) { - if( !$costs ) { return; } + private function _set_rate($costs) { + if(!$costs) { return; } // format the costs from API to WooCommerce - foreach( $costs as $courier ): - if( empty( $courier ) ) { break; } + foreach($costs as $courier): + if(empty($courier)) { break; } // get full list of services $code = $courier['code']; - $all_services = wcis_get_services( $code ); + $all_services = wcis_get_services($code); // get allowed service from this courier $setting_id = $code . '_services'; $allowed_services = isset($this->main_settings[$setting_id]) ? $this->main_settings[$setting_id] : array(); - foreach( $courier['costs'] as $service ): + foreach($courier['costs'] as $service): // check if this service is allowed $is_allowed = false; - foreach( $allowed_services as $as ) { + foreach($allowed_services as $as) { // if has variation - if( isset( $all_services[$as]['vars'] ) ) { - $is_allowed = in_array( $service['service'], $all_services[$as]['vars'] ); + if(isset($all_services[$as]['vars'])) { + $is_allowed = in_array($service['service'], $all_services[$as]['vars']); } else { $is_allowed = $service['service'] === $as; } - if( $is_allowed ) { break; } + if($is_allowed) { break; } } - if( $is_allowed ) { + if($is_allowed) { $rate = array( 'id' => $code . '_' . strtolower($service['service']) . $this->instance_id, 'label' => strtoupper($code) . ' ' . $service['service'], @@ -109,7 +109,7 @@ private function _set_rate( $costs ) { 'calc_tax' => 'per_order' ); - $this->add_rate( $rate ); + $this->add_rate($rate); } endforeach; endforeach; @@ -121,19 +121,18 @@ private function _set_rate( $costs ) { * @param array $package - POST parameter * @return int - THe weight in the unit specified in admin. */ - private function _calculate_weight( $package ) { + private function _calculate_weight($package) { global $woocommerce; + $weight = wc_get_weight($woocommerce->cart->cart_contents_weight, 'g'); - $weight = wc_get_weight( $woocommerce->cart->cart_contents_weight, 'g' ); - - if( $weight > 0 ) { + if($weight > 0) { return $weight; } // if no weight data, return default weight or 1kg else { - $weight = (int) ceil( apply_filters( 'wcis_default_weight', $package ) ); + $weight = (int) ceil(apply_filters('wcis_default_weight', $package)); - return (is_int($weight) && $weight > 0 ) ? $weight : 1; + return (is_int($weight) && $weight > 0) ? $weight : 1; } } @@ -146,13 +145,12 @@ private function _get_selected_couriers() { $couriers = wcis_get_couriers(); $selected_couriers = []; - foreach( $couriers as $id => $name ) { - if( !empty( $this->main_settings[$id . '_services'] ) ) { + foreach($couriers as $id => $name) { + if(!empty($this->main_settings[$id . '_services'])) { $selected_couriers[] = $id; } } - return join( ':', $selected_couriers ); + return join(':', $selected_couriers); } - } diff --git a/module-admin/wcis-checkout.php b/module-admin/wcis-checkout.php index 679fbb9..6983144 100644 --- a/module-admin/wcis-checkout.php +++ b/module-admin/wcis-checkout.php @@ -1,15 +1,14 @@ _clean_city_field( $posted['billing_city'] ); - update_post_meta( $order_id, '_billing_city', $city ); + function update_order_meta($order_id, $posted) { + $city = $this->_clean_city_field($posted['billing_city']); + update_post_meta($order_id, '_billing_city', $city); // if shipping city is passed on - if(isset( $posted['shipping_city'] ) ) { - $city = $this->_clean_city_field( $posted['shipping_city'] ); + if(isset($posted['shipping_city'])) { + $city = $this->_clean_city_field($posted['shipping_city']); } - update_post_meta( $order_id, '_shipping_city', $city ); + update_post_meta($order_id, '_shipping_city', $city); } @@ -56,10 +55,10 @@ function update_order_meta( $order_id, $posted ) { * @param mixed $packages - Cart parameters * @return mixed */ - function parse_shipping_package( $packages ) { + function parse_shipping_package($packages) { // look for district ID in city field - preg_match( '/\[(\d+)\]/', $packages[0]['destination']['city'], $matches ); - if( count( $matches ) ) { + preg_match('/\[(\d+)\]/', $packages[0]['destination']['city'], $matches); + if(count($matches)) { $packages[0]['destination']['destination_id'] = $matches[1]; } @@ -74,10 +73,9 @@ function parse_shipping_package( $packages ) { * @param string $city_raw * @return string - City name without ID */ - private function _clean_city_field( $city_raw ) { - preg_match( '/[\w\s,]+/', $city_raw, $city ); + private function _clean_city_field($city_raw) { + preg_match('/[\w\s,]+/', $city_raw, $city); - return trim( $city[0] ); + return trim($city[0]); } - } diff --git a/module-api/_index.php b/module-api/_index.php index 35fa0b4..60eca08 100644 --- a/module-api/_index.php +++ b/module-api/_index.php @@ -1,30 +1,30 @@ \w+)/', [ + register_rest_route(WCIS_NAMESPACE, '/cities/(?P\w+)/', [ 'methods' => 'GET', 'callback' => 'wcis_get_cities_api', 'permission_callback' => '__return_true' - ] ); + ]); - register_rest_route( WCIS_NAMESPACE, '/districts/(?P\w+)/(?P\d+)/', [ + register_rest_route(WCIS_NAMESPACE, '/districts/(?P\w+)/(?P\d+)/', [ 'methods' => 'GET', 'callback' => 'wcis_get_districts_api', 'permission_callback' => '__return_true' - ] ); + ]); - register_rest_route( WCIS_NAMESPACE, '/fields/(?P\w+)/(?P\w+)/(?P\d+)', [ + register_rest_route(WCIS_NAMESPACE, '/fields/(?P\w+)/(?P\w+)/(?P\d+)', [ 'methods' => 'GET', 'callback' => 'wcis_get_fields_api', 'permission_callback' => '__return_true' - ] ); + ]); } \ No newline at end of file diff --git a/module-api/json-update.php b/module-api/json-update.php index ee43ff4..53e9350 100644 --- a/module-api/json-update.php +++ b/module-api/json-update.php @@ -5,7 +5,7 @@ if(!defined('ABSPATH') ) { exit; } // exit if accessed directly -add_action( 'admin_init', 'wcis_refresh_json_data' ); +add_action('admin_init', 'wcis_refresh_json_data'); /** @@ -14,13 +14,13 @@ function wcis_refresh_json_data() { $prov = wcis_get_provinces(); - foreach( $prov as $code => $id ) { - $result = wp_remote_get( WCIS_API . "/all-cities/$id" ); + foreach($prov as $code => $id) { + $result = wp_remote_get(WCIS_API . "/all-cities/$id"); // if not error - if( !is_wp_error( $result ) ) { + if(!is_wp_error($result)) { $data = $result['body']; - file_put_contents( __DIR__ . "/json/city-$id.json", $data ); + file_put_contents(__DIR__ . "/json/city-$id.json", $data); break; } } diff --git a/module-api/json/couriers.json b/module-api/json/couriers.json index 4cf873c..79177e4 100644 --- a/module-api/json/couriers.json +++ b/module-api/json/couriers.json @@ -63,52 +63,49 @@ } } }, -"pcp": { - "name": "PCP", + +"jnt": { + "code": "J&T", + "name": "J&T Express", + "services": { + "EZ": { + "title": "EZ - Regular Service" + } + } +}, + +"sicepat": { + "code": "sicepat", + "name": "SiCepat Express", "services": { - "ECO": { - "title": "ECO - Economic Service" - }, "REG": { - "title": "REG - Regular Service" + "title": "Layanan Reguler" }, - "ONS": { - "title": "ONS - Overnight Service" + "SIUNT": { + "title": "SiUntung" }, - "ONP": { - "title": "ONP - Overnight Service Premium" - }, - "NFS": { - "title": "NFS - Next Flight Service" + "GOKIL": { + "title": "Cargo (Min 10kg)" } } }, -"rpx": { - "name": "RPX", + +"ninja": { + "code": "ninja", + "name": "Ninja Xpress", "services": { - "REP": { - "title": "REP - Retail Package" - }, - "RGP": { - "title": "RGP - Regular Package" - }, - "NDP": { - "title": "NDP - Next Day Package" - }, - "MDP": { - "title": "MDP - MidDay Package" - }, - "SDP": { - "title": "SDP - SameDay Package" + "STANDARD": { + "title": "Standard Service" } } }, -"jnt": { - "code": "J&T", - "name": "J&T Express", + +"anteraja": { + "code": "anteraja", + "name": "AnterAja", "services": { - "EZ": { - "title": "EZ - Regular Service" + "REG": { + "title": "Regular" } } } diff --git a/module-api/rajaongkir.php b/module-api/rajaongkir.php deleted file mode 100644 index 6e0f74e..0000000 --- a/module-api/rajaongkir.php +++ /dev/null @@ -1,85 +0,0 @@ -api_key = $key; - } - else { - $cached_license = get_transient( 'wcis_license' ); - $this->api_key = $cached_license['key']; - } - } - - - /** - * Test if API key is working - * - * @return bool - */ - function is_valid() { - $result = $this->call_rajaongkir( '/province', 'GET' ); - - $status = wp_remote_retrieve_response_code( $result ); - return $status === 200; - } - - - /** - * Get shipping costs - * - * @param array $args - Formatted argument ready for API call - * @return array - JSON response - */ - function get_costs( $args ) { - $result = $this->call_rajaongkir( '/cost', 'POST', $args ); - - if( $result ) { - $costs = $result['rajaongkir']['results'] ?? null; - return $costs; - } else { - return $result; - } - } - - ///// - - /** - * Call API - * - * @param string $endpoint - * @param array $args - *Optional*. Additional arguments - * @return array - JSON response - */ - private function call_rajaongkir( $endpoint, $method = 'GET', $args = [] ) { - $result = null; - - // do the call - if( $method == 'GET' ) { - $result = wp_remote_get( RAJAONGKIR_API . $endpoint, [ - 'headers' => [ 'key' => $this->api_key ] - ] ); - } - elseif( $method == 'POST' ) { - $result = wp_remote_post( RAJAONGKIR_API . $endpoint, [ - 'headers' => [ 'key' => $this->api_key ], - 'body' => $args - ] ); - } - - // check for error - if( is_wp_error( $result ) ) { - return $result->get_error_message(); - } - else { - return json_decode( $result['body'], true ); - } - } - -} diff --git a/module-api/static.php b/module-api/static.php index 5abb3a5..61921c8 100644 --- a/module-api/static.php +++ b/module-api/static.php @@ -6,16 +6,16 @@ * @get /fields/:type/:prov_code/:district_id * @return array */ -function wcis_get_fields_api( $params ) { +function wcis_get_fields_api($params) { // Convert District ID to City ID - if( $params['district_id'] != '0' ) { - $prov_id = wcis_get_province_id( $params['prov_code'] ); - $cities = _wcis_read_json( $prov_id . '.json' ); + if($params['district_id'] != '0') { + $prov_id = wcis_get_province_id($params['prov_code']); + $cities = _wcis_read_json("$prov_id.json"); - foreach( $cities as $city_id => $c ) { - foreach( $c['districts'] as $district_id => $name ) { + foreach($cities as $city_id => $c) { + foreach($c['districts'] as $district_id => $name) { // find district that has the same ID as the one passed on - if( $params['district_id'] == $district_id ) { + if($params['district_id'] == $district_id) { $params['city_id'] = $city_id; break; } @@ -25,16 +25,24 @@ function wcis_get_fields_api( $params ) { $params['city_id'] = '0'; } - $cities_field = wcis_get_cities_field( $params['type'], $params['prov_code'] ); - $districts_field = wcis_get_districts_field( $params['type'], $params['prov_code'], $params['city_id'] ); + $cities_field = wcis_get_cities_field($params['type'], $params['prov_code']); + $districts_field = wcis_get_districts_field($params['type'], $params['prov_code'], $params['city_id']); // add selected attribute - if( isset( $params['city_id'] ) ) { - $cities_field = preg_replace( '/(_city_field[\s\S]+)(\"' . $params['city_id'] . '\"\s)(\>)([\s\S]+\/p>)/Ui', '$1$2selected$3$4', $cities_field ); + if(isset($params['city_id'])) { + $cities_field = preg_replace( + '/(_city_field[\s\S]+)(\"' . $params['city_id'] . '\"\s)(\>)([\s\S]+\/p>)/Ui', + '$1$2selected$3$4', + $cities_field + ); } - if( $params['district_id'] != '0' ) { - $districts_field = preg_replace( '/(_district_field[\s\S]+)(' . $params['district_id'] . '\]\"\s)(\>)([\s\S]+\/p>)/Ui', '$1$2selected$3$4', $districts_field ); + if($params['district_id'] != '0') { + $districts_field = preg_replace( + '/(_district_field[\s\S]+)(' . $params['district_id'] . '\]\"\s)(\>)([\s\S]+\/p>)/Ui', + '$1$2selected$3$4', + $districts_field + ); } return $cities_field . $districts_field; @@ -46,24 +54,25 @@ function wcis_get_fields_api( $params ) { * * @return array - All cities within that province. */ -function wcis_get_cities_api( $params ) { - if( $params['prov_code'] ) { - $prov_id = wcis_get_province_id( $params['prov_code'] ); - $cities = wcis_get_cities( $prov_id ); +function wcis_get_cities_api($params) { + if($params['prov_code']) { + $prov_id = wcis_get_province_id($params['prov_code']); + $cities = wcis_get_cities($prov_id); // map to `id:name` $cities_mapped = []; - foreach( $cities as $id => $item ) { - $cities_mapped[ $id ] = $item['city_name']; + foreach($cities as $id => $item) { + $cities_mapped[$id] = $item['city_name']; } - $cities_mapped = [ 0 => __( 'Pilih Kota...' ) ] + $cities_mapped; - + $cities_mapped = [0 => __( 'Pilih Kota...' )] + $cities_mapped; return $cities_mapped; } // If province code not given, show error message else { - return [ 0 => __( 'Pilih Provinsi terlebih dahulu...' ) ]; + return [ + 0 => __('Pilih Provinsi terlebih dahulu...') + ]; } } @@ -73,18 +82,18 @@ function wcis_get_cities_api( $params ) { * * @return array - All districts within that city. */ -function wcis_get_districts_api( $params ) { - $prov_id = wcis_get_province_id( $params['prov_code'] ); - $cities = _wcis_read_json( $prov_id . '.json' ); - $city = $cities[ $params['city_id'] ] ?? null; +function wcis_get_districts_api($params) { + $prov_id = wcis_get_province_id($params['prov_code']); + $cities = _wcis_read_json($prov_id . '.json'); + $city = $cities[$params['city_id']] ?? null; // abort if city not found - if( !$city ) { return; } + if(!$city) { return; } // Format the district value so the City name is included $districts = [ '0' => __('Pilih Kecamatan...') ]; - foreach( $city['districts'] as $id => $name ) { - $districts[ $city['city_name'] . ", $name [$id]" ] = $name; + foreach($city['districts'] as $id => $name) { + $districts[$city['city_name'] . ", $name [$id]"] = $name; } return $districts; @@ -96,26 +105,26 @@ function wcis_get_districts_api( $params ) { * * @return array - Currently only has one item: 'field' which contains the HTML form field. */ -function wcis_get_cities_field( $type, $prov_code = '0' ) { +function wcis_get_cities_field($type, $prov_code = '0') { $field = ''; // if code is 0, show empty placeholder dropdown - if( $prov_code == '0' ) { + if($prov_code == '0') { $field = woocommerce_form_field( "_{$type}_city", [ 'type' => 'select', - 'label' => __( 'City', 'woocommerce' ), - 'options' => [ 0 => __( 'Pilih Provinsi terlebih dahulu...' ) ], + 'label' => __('City', 'woocommerce'), + 'options' => [0 => __('Pilih Provinsi terlebih dahulu...')], 'return' => true, 'required' => true, ] ); } // else else { - $cities = wcis_get_cities_api( [ 'prov_code' => $prov_code ] ); + $cities = wcis_get_cities_api(['prov_code' => $prov_code]); - $field = woocommerce_form_field( "_{$type}_city", [ + $field = woocommerce_form_field("_{$type}_city", [ 'type' => 'select', - 'label' => __( 'City', 'woocommerce' ), + 'label' => __('City', 'woocommerce'), 'options' => $cities, 'return' => true, 'required' => true, @@ -130,29 +139,33 @@ function wcis_get_cities_field( $type, $prov_code = '0' ) { * * @return array - City ID and the HTML form field. City ID is used to pre-select the dropdown */ -function wcis_get_districts_field( $type, $prov_code, $city_id = '0' ) { +function wcis_get_districts_field($type, $prov_code, $city_id = '0') { $field = ''; // If city ID is empty, show placeholder - if( $city_id == '0' ) { - $field = woocommerce_form_field( "_{$type}_district", [ + if($city_id == '0') { + $field = woocommerce_form_field("_{$type}_district", [ 'type' => 'select', - 'label' => __( 'Kecamatan' ), - 'options' => [ 0 => __( 'Pilih Kota terlebih dahulu...' ) ], + 'label' => __('Kecamatan'), + 'options' => [ 0 => __('Pilih Kota terlebih dahulu...') ], 'return' => true, 'required' => true ] ); } // Else, show the district selection else { - $districts = wcis_get_districts_api( [ 'prov_code' => $prov_code, 'city_id' => $city_id ] ); - $field = woocommerce_form_field( "_{$type}_district", [ + $districts = wcis_get_districts_api([ + 'prov_code' => $prov_code, + 'city_id' => $city_id + ]); + + $field = woocommerce_form_field("_{$type}_district", [ 'type' => 'select', - 'label' => __( 'Kecamatan' ), + 'label' => __('Kecamatan'), 'options' => $districts, 'return' => true, 'required' => true - ] ); + ]); } return $field; @@ -163,12 +176,12 @@ function wcis_get_districts_field( $type, $prov_code, $city_id = '0' ) { /** * Get all cities in a province */ -function wcis_get_cities( $prov_id ) { - $data = _wcis_read_json( $prov_id . '.json' ); +function wcis_get_cities($prov_id) { + $data = _wcis_read_json($prov_id . '.json'); // if exists, scan for duplicate city name - if( $data ) { - $data = _wcis_prefix_dupe_city_name( $prov_id, $data ); + if($data) { + $data = _wcis_prefix_dupe_city_name($prov_id, $data); return $data; } else { return $data; @@ -181,9 +194,9 @@ function wcis_get_cities( $prov_id ) { * @param str $state - State / Province code from WooCommerce * @return int - the province's ID */ -function wcis_get_province_id( $prov_code ) { +function wcis_get_province_id($prov_code) { $provinces = _wcis_read_json('provinces.json'); - $id = array_key_exists( $prov_code, $provinces ) ? $provinces[$prov_code] : 0; + $id = array_key_exists($prov_code, $provinces) ? $provinces[$prov_code] : 0; return $id; } @@ -191,20 +204,23 @@ function wcis_get_province_id( $prov_code ) { * Get all provinces in Code:ID format. Code is the abbreviation from WooCommerce, ID is the number from RajaOngkir */ function wcis_get_provinces() { - $provinces = _wcis_read_json( 'provinces.json' ); + $provinces = _wcis_read_json('provinces.json'); return $provinces; } /** * Get all couriers. + * + * Available: pos,tiki,jne,pcp,esl,rpx,pandu,wahana,jnt,pahala,cahaya, sap,jet,indah,dse,slis,first,ncs,star + * * @return array - List of couriers in (slug => name) format. */ function wcis_get_couriers() { - $couriers_raw = _wcis_read_json( 'couriers.json' ); + $couriers_raw = _wcis_read_json('couriers.json'); // remap $couriers = []; - foreach( $couriers_raw as $key => $value ) { + foreach($couriers_raw as $key => $value) { $couriers[$key] = $value['name']; } @@ -219,20 +235,20 @@ function wcis_get_couriers() { * @param bool $simple_format - *Optional*. If true, return a simplified `id => name` format. Default is false. * @return array - The services this courier provided */ -function wcis_get_services( $name, $simple_format = false ) { +function wcis_get_services($name, $simple_format = false) { if($name === 'J&T') { $name = 'jnt'; } // for weird reason, the response code for 'jnt' is 'J&T' - $couriers = _wcis_read_json( 'couriers.json' ); - $courier = isset( $couriers[$name] ) ? $couriers[$name] : null; + $couriers = _wcis_read_json('couriers.json'); + $courier = isset($couriers[$name]) ? $couriers[$name] : null; // if courier found - if( $courier ) { + if($courier) { $services = $courier['services']; // simplify the data - if( $simple_format ) { - $parsed = array(); - foreach( $courier['services'] as $key => $val ) { + if($simple_format) { + $parsed = []; + foreach($courier['services'] as $key => $val) { $parsed[$key] = $val['title']; } @@ -252,17 +268,17 @@ function wcis_get_services( $name, $simple_format = false ) { * @param string $filename * @return array */ -function _wcis_read_json( $filename ) { - $fileurl = WCIS_DIR . "/module-api/json/$filename"; - $args = array( - 'ssl' => array( +function _wcis_read_json($filename) { + $fileurl = WCIS_PATH . "/module-api/json/$filename"; + $args = [ + 'ssl' => [ 'verify_peer' => false, 'verify_peer_name' => false, - ), - ); + ], + ]; - $fileraw = file_get_contents( $fileurl, false, stream_context_create($args) ); - return json_decode( $fileraw, true ); + $fileraw = file_get_contents($fileurl, false, stream_context_create($args)); + return json_decode($fileraw, true); } /** @@ -272,32 +288,32 @@ function _wcis_read_json( $filename ) { * @param array $dupe_ids - ID of cities that share the same name * @return array - Prefixed list */ -function _wcis_prefix_dupe_city_name( $prov_id, $data ) { +function _wcis_prefix_dupe_city_name($prov_id, $data) { // Province that has same city and district name - $city_dupe_name = array( - 3 => array(402, 403, 455, 456), // Serang, Tangerang - 9 => array(22, 23, 54, 55, 78, 79, 108, 109, 430, 431, 468, 469), // Bandung, Bekasi, Bogor, Cirebon, Sukabumi, Tasikmalaya - 10 => array(249, 250, 348, 349, 472, 473, 398, 399), // Magelang, Pekalongan, Tegal, Semarang - 11 => array(74, 75, 178, 179, 255, 256, 247, 248, 289, 290, 342, 343, 369, 370), // Blitar, Kediri, Malang, Madiun, Mojokerto, Pasuruan, Probolinggo, + $city_dupe_name = [ + 3 => [402, 403, 455, 456], // Serang, Tangerang + 9 => [22, 23, 54, 55, 78, 79, 108, 109, 430, 431, 468, 469], // Bandung, Bekasi, Bogor, Cirebon, Sukabumi, Tasikmalaya + 10 => [249, 250, 348, 349, 472, 473, 398, 399], // Magelang, Pekalongan, Tegal, Semarang + 11 => [74, 75, 178, 179, 255, 256, 247, 248, 289, 290, 342, 343, 369, 370], // Blitar, Kediri, Malang, Madiun, Mojokerto, Pasuruan, Probolinggo, - 32 => array(420, 421), // Solok + 32 => [420, 421], // Solok - 22 => array(68, 69), // Bima - 23 => array(212, 213), // Kupang + 22 => [68, 69], // Bima + 23 => [212, 213], // Kupang - 12 => array(364, 365), // Pontianak - 7 => array(129, 130), // Gorontalo + 12 => [364, 365], // Pontianak + 7 => [129, 130], // Gorontalo - 24 => array(157, 158), // Jayapura - 25 => array(424, 425), // Sorong - ); + 24 => [157, 158], // Jayapura + 25 => [424, 425], // Sorong + ]; // if province has duplicate city name, add - if( array_key_exists( $prov_id, $city_dupe_name ) ): + if(array_key_exists($prov_id, $city_dupe_name)): $dupe_ids = $city_dupe_name[$prov_id]; - foreach( $data as $id => &$value ) { - if( in_array($id, $dupe_ids) ) { + foreach($data as $id => &$value) { + if(in_array($id, $dupe_ids)) { $value['city_name'] = $value['city_name'] . ' (' . $value['type'] . ')'; } } diff --git a/module-checkout/fields.php b/module-checkout/fields.php index 5789589..269dd4d 100644 --- a/module-checkout/fields.php +++ b/module-checkout/fields.php @@ -1,7 +1,7 @@ settings = get_option( 'woocommerce_wcis_settings' ); - $this->enabled = isset( $this->settings['enabled'] ) ? $this->settings['enabled'] : 'no'; + $this->settings = get_option('woocommerce_wcis_settings'); + $this->enabled = isset($this->settings['enabled']) ? $this->settings['enabled'] : 'no'; - if( $this->enabled === 'yes' ) { + if($this->enabled === 'yes') { $this->admin_init(); - add_action( 'template_redirect', [$this, 'public_init'] ); + add_action('template_redirect', [$this, 'public_init']); } // run this code even if disabled - add_action( 'woocommerce_shipping_init', [$this, 'shipping_init'] ); - add_filter( 'woocommerce_shipping_methods', [$this, 'shipping_method'] ); + add_action('woocommerce_shipping_init', [$this, 'shipping_init']); + add_filter('woocommerce_shipping_methods', [$this, 'shipping_method']); } - /* - Inititate the needed classes - */ + /** + * Inititate the needed classes + */ function admin_init() { new WCIS_Ajax(); new WCIS_Checkout(); } function public_init() { - if( is_checkout() || is_cart() ) { - add_action( 'wp_enqueue_scripts', [$this, 'enqueue_assets'], 1000000 ); + if(is_checkout() || is_cart()) { + add_action('wp_enqueue_scripts', [$this, 'enqueue_assets'], 1000000); } // change default // TODO: due to template_redirect action, Postcode might show up after refresh - add_filter( 'woocommerce_shipping_calculator_enable_city', '__return_true' ); - add_filter( 'woocommerce_shipping_calculator_enable_postcode', '__return_false' ); + add_filter('woocommerce_shipping_calculator_enable_city', '__return_true'); + add_filter('woocommerce_shipping_calculator_enable_postcode', '__return_false'); } @@ -73,15 +73,15 @@ function public_init() { * @filter woocommerce_shipping_init */ function shipping_init() { - require_once( 'module-admin/init-main.php' ); - require_once( 'module-admin/init-zones.php' ); + require_once('module-admin/init-main.php'); + require_once('module-admin/init-zones.php'); } /** * Add our custom Shipping method * @filter woocommerce_shipping_methods */ - function shipping_method( $methods ) { + function shipping_method($methods) { $methods['wcis'] = 'WCIS_Method'; $methods['wcis_zone'] = 'WCIS_Zones_Method'; return $methods; @@ -91,15 +91,14 @@ function shipping_method( $methods ) { * @action wp_enqueue_scripts */ function enqueue_assets() { - $dist = WCIS_DIR . '/assets/dist'; - wp_enqueue_style( 'wcis_style', $dist . '/wcis-public.css', [], WCIS_VERSION ); - wp_enqueue_script( 'wcis_script', $dist . '/wcis-public.js', ['jquery'], WCIS_VERSION, true ); + $dist = WCIS_PATH . '/assets/dist'; + wp_enqueue_style('wcis_style', $dist . '/wcis-public.css', [], WCIS_VERSION); + wp_enqueue_script( 'wcis_script', $dist . '/wcis-public.js', ['jquery'], WCIS_VERSION, true); - wp_localize_script( 'wcis_script', 'wcisLocalize', [ + wp_localize_script('wcis_script', 'wcisLocalize', [ 'WCIS_API' => WCIS_API, - ] ); + ]); } } - new WCIS_Init();