AgenticCheckoutUtils.php
4 months ago
ArrayUtils.php
2 years ago
CartController.php
1 month ago
CartTokenUtils.php
1 year ago
CheckoutTrait.php
1 month ago
DraftOrderTrait.php
1 year ago
JsonWebToken.php
11 months ago
LocalPickupUtils.php
5 months ago
NoticeHandler.php
1 year ago
OrderAuthorizationTrait.php
6 months ago
OrderController.php
1 month ago
Pagination.php
2 years ago
PaymentUtils.php
1 year ago
ProductItemTrait.php
1 month ago
ProductLinksTrait.php
3 months ago
ProductQuery.php
2 months ago
ProductQueryFilters.php
11 months ago
QuantityLimits.php
11 months ago
RateLimits.php
1 year ago
SanitizationUtils.php
2 years ago
ValidationUtils.php
2 years ago
ValidationUtils.php
62 lines
| 1 | <?php |
| 2 | namespace Automattic\WooCommerce\StoreApi\Utilities; |
| 3 | |
| 4 | /** |
| 5 | * ValidationUtils class. |
| 6 | * Helper class which validates and update customer info. |
| 7 | */ |
| 8 | class ValidationUtils { |
| 9 | /** |
| 10 | * Get list of states for a country. |
| 11 | * |
| 12 | * @param string $country Country code. |
| 13 | * @return array Array of state names indexed by state keys. |
| 14 | */ |
| 15 | public function get_states_for_country( $country ) { |
| 16 | return $country ? array_filter( (array) \wc()->countries->get_states( $country ) ) : []; |
| 17 | } |
| 18 | |
| 19 | /** |
| 20 | * Validate provided state against a countries list of defined states. |
| 21 | * |
| 22 | * If there are no defined states for a country, any given state is valid. |
| 23 | * |
| 24 | * @param string $state State name or code (sanitized). |
| 25 | * @param string $country Country code. |
| 26 | * @return boolean Valid or not valid. |
| 27 | */ |
| 28 | public function validate_state( $state, $country ) { |
| 29 | $states = $this->get_states_for_country( $country ); |
| 30 | |
| 31 | if ( count( $states ) && ! in_array( \wc_strtoupper( $state ), array_map( '\wc_strtoupper', array_keys( $states ) ), true ) ) { |
| 32 | return false; |
| 33 | } |
| 34 | |
| 35 | return true; |
| 36 | } |
| 37 | |
| 38 | |
| 39 | /** |
| 40 | * Format a state based on the country. If country has defined states, will return a valid upper case state code. |
| 41 | * |
| 42 | * @param string $state State name or code (sanitized). |
| 43 | * @param string $country Country code. |
| 44 | * @return string |
| 45 | */ |
| 46 | public function format_state( $state, $country ) { |
| 47 | $states = $this->get_states_for_country( $country ); |
| 48 | |
| 49 | if ( count( $states ) ) { |
| 50 | $state = \wc_strtoupper( $state ); |
| 51 | $state_values = array_map( '\wc_strtoupper', array_flip( array_map( '\wc_strtoupper', $states ) ) ); |
| 52 | |
| 53 | if ( isset( $state_values[ $state ] ) ) { |
| 54 | // Convert to state code if a state name was provided. |
| 55 | return $state_values[ $state ]; |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | return $state; |
| 60 | } |
| 61 | } |
| 62 |