int, 'en' => string, 'ar' => string], sorted by English name. * * @return array * @throws AbsError When ABS cannot be reached and nothing is cached. */ public static function all() { $cached = get_transient( self::TRANSIENT ); if ( is_array( $cached ) && ! empty( $cached ) ) { return $cached; } if ( '' === Credentials::get() ) { throw new AbsError( AbsError::CONFIG, __( 'The store is not connected to ABS Courier.', 'abs-courier' ) ); } if ( get_transient( self::FAILED ) ) { throw new AbsError( AbsError::RETRYABLE, __( 'The district list could not be loaded from ABS Courier. Try again shortly.', 'abs-courier' ) ); } $client = new AbsClient( Credentials::get() ); try { $en = self::fetch( $client, 'en' ); $ar = self::fetch( $client, 'ar' ); } catch ( AbsError $e ) { // Remember the failure so order screens do not each wait on ABS for the next few minutes. set_transient( self::FAILED, 1, 5 * MINUTE_IN_SECONDS ); throw $e; } $districts = array(); foreach ( $en as $id => $name ) { $districts[] = array( 'id' => $id, 'en' => $name, 'ar' => isset( $ar[ $id ] ) ? $ar[ $id ] : '', ); } usort( $districts, static function ( $a, $b ) { return strcasecmp( $a['en'], $b['en'] ); } ); if ( ! empty( $districts ) ) { set_transient( self::TRANSIENT, $districts, DAY_IN_SECONDS ); } return $districts; } /** * Matcher over the current list. * * @return DistrictMatcher * @throws AbsError When the list cannot be loaded. */ public static function matcher() { return new DistrictMatcher( self::all() ); } /** * English name of a district, or '' when unknown. * * @param int $id District ID. * @return string */ public static function name( $id ) { if ( DistrictMatcher::UNRESOLVED_DISTRICT_ID === (int) $id ) { return __( 'Not Clear', 'abs-courier' ); } try { foreach ( self::all() as $district ) { if ( (int) $id === $district['id'] ) { return $district['en']; } } } catch ( AbsError $e ) { return ''; } return ''; } /** * All pages of the district dropdown in one language, as id => name. * * @param AbsClient $client Client. * @param string $lang 'en' or 'ar'. * @return array * @throws AbsError On failure. */ private static function fetch( AbsClient $client, $lang ) { $names = array(); $page = 1; do { $data = $client->get( 'shared/dropdown/districts', array( 'lang' => $lang, 'countryId' => self::EGYPT_COUNTRY_ID, 'page' => $page, 'limit' => self::PAGE_SIZE, ) ); $rows = isset( $data['content'] ) && is_array( $data['content'] ) ? $data['content'] : array(); $pages = isset( $data['page']['total_pages'] ) ? (int) $data['page']['total_pages'] : 1; foreach ( $rows as $row ) { if ( isset( $row['id'], $row['value'] ) && is_numeric( $row['id'] ) ) { $names[ (int) $row['id'] ] = sanitize_text_field( (string) $row['value'] ); } } ++$page; } while ( $page <= $pages && $page <= self::MAX_PAGES ); return $names; } }