name. * * @return array */ public static function products() { $lists = self::load(); return $lists['products']; } /** * Shipment services, as id => name. * * @return array */ public static function services() { $lists = self::load(); return $lists['services']; } /** * Drops the cache, e.g. after the key changes. * * @return void */ public static function flush() { delete_transient( self::TRANSIENT ); } /** * Loads both lists from cache or ABS. Lists that fail to load are empty and not cached. * * @return array{products: array, services: array} */ private static function load() { $cached = get_transient( self::TRANSIENT ); if ( is_array( $cached ) && isset( $cached['products'], $cached['services'] ) ) { return $cached; } $empty = array( 'products' => array(), 'services' => array(), ); $api_key = Credentials::get(); $state = Connection::state_saved(); if ( '' === $api_key || Connection::CONNECTED !== $state['status'] ) { return $empty; } $client = new AbsClient( $api_key ); try { $lists = array( 'products' => self::to_map( $client->get( 'shared/dropdown/products', array( 'lang' => 'en' ) ) ), 'services' => self::to_map( $client->get( 'shared/dropdown/shipment-services', array( 'lang' => 'en' ) ) ), ); } catch ( AbsError $e ) { // Remember the failure briefly so a slow or unavailable ABS doesn't delay every page load. set_transient( self::TRANSIENT, $empty, 5 * MINUTE_IN_SECONDS ); return $empty; } set_transient( self::TRANSIENT, $lists, HOUR_IN_SECONDS ); return $lists; } /** * Converts ABS dropdown rows (`{id, value}` or `{id, name}`) to id => name. * * @param mixed $rows Rows from ABS. * @return array */ private static function to_map( $rows ) { $map = array(); if ( ! is_array( $rows ) ) { return $map; } foreach ( $rows as $row ) { if ( ! is_array( $row ) || ! isset( $row['id'] ) || ! is_numeric( $row['id'] ) ) { continue; } $name = isset( $row['value'] ) ? $row['value'] : ( isset( $row['name'] ) ? $row['name'] : '' ); $map[ (int) $row['id'] ] = sanitize_text_field( (string) $name ); } return $map; } }