Skip to content
This repository has been archived by the owner on Feb 23, 2024. It is now read-only.

Commit

Permalink
has_valid_pickup_location helper
Browse files Browse the repository at this point in the history
  • Loading branch information
mikejolley committed Jun 28, 2023
1 parent e0fa15b commit b4bfc94
Showing 1 changed file with 43 additions and 2 deletions.
45 changes: 43 additions & 2 deletions src/Shipping/PickupLocation.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,48 @@ public function init() {
add_filter( 'woocommerce_attribute_label', array( $this, 'translate_meta_data' ), 10, 3 );
}

/**
* Checks if a given address is complete.
*
* @param array $address Address.
* @return bool
*/
protected function has_valid_pickup_location( $address ) {
// Normalize address.
$address_fields = wp_parse_args(
(array) $address,
array(
'city' => '',
'postcode' => '',
'state' => '',
'country' => '',
)
);

// Country is always required.
if ( empty( $address_fields['country'] ) ) {
return false;
}

// If all fields are provided, we can skip further checks.
if ( ! empty( $address_fields['city'] ) && ! empty( $address_fields['postcode'] ) && ! empty( $address_fields['state'] ) ) {
return true;
}

// Check validity based on requirements for the country.
$country_address_fields = wc()->countries->get_address_fields( $address_fields['country'], 'shipping_' );

foreach ( $country_address_fields as $field_name => $field ) {
$key = str_replace( 'shipping_', '', $field_name );

if ( true === $field['required'] && empty( $address_fields[ $key ] ) ) {
return false;
}
}

return true;
}

/**
* Calculate shipping.
*
Expand All @@ -56,7 +98,6 @@ public function calculate_shipping( $package = array() ) {
if ( ! $location['enabled'] ) {
continue;
}
$has_pickup_address = ! empty( $location['address'] ) && ! empty( $location['address']['city'] ) && ! empty( $location['address']['state'] ) && ! empty( $location['address']['country'] );
$this->add_rate(
array(
'id' => $this->id . ':' . $index,
Expand All @@ -66,7 +107,7 @@ public function calculate_shipping( $package = array() ) {
'cost' => $this->cost,
'meta_data' => array(
'pickup_location' => wp_kses_post( $location['name'] ),
'pickup_address' => $has_pickup_address ? wc()->countries->get_formatted_address( $location['address'], ', ' ) : '',
'pickup_address' => $this->has_valid_pickup_location( $location['address'] ) ? wc()->countries->get_formatted_address( $location['address'], ', ' ) : '',
'pickup_details' => wp_kses_post( $location['details'] ),
),
)
Expand Down

0 comments on commit b4bfc94

Please sign in to comment.