key setting. */ const SERVICES = array( 'google' => 'api_key', 'geoapify' => 'geoapify_key', 'here' => 'here_key', ); /** * Service names, not translated. Here (not in Admin) because add-ons need them outside the admin too. * * @return array */ public static function service_names() { return array( 'google' => 'Google Maps', 'geoapify' => 'Geoapify', 'here' => 'HERE', ); } /** * Cached settings. * * @var array|null */ private static $cache = null; /** * Defaults. * * @return array */ public static function defaults() { return array( 'provider' => 'google', 'api_key' => '', 'geoapify_key' => '', 'here_key' => '', 'style' => 'on', ); } /** * All settings, defaults filled in. * * @return array */ public static function all() { if ( null === self::$cache ) { $stored = get_option( self::OPTION, array() ); self::$cache = self::sanitize( is_array( $stored ) ? $stored : array() ); } return self::$cache; } /** * One setting. * * @param string $key Setting name. * @return mixed */ public static function get( $key ) { $all = self::all(); return isset( $all[ $key ] ) ? $all[ $key ] : null; } /** * Forgets the cache (after saving, on switch_blog). */ public static function reset() { self::$cache = null; } /** * Saves sanitized settings. * * @param array $values New values. */ public static function save( array $values ) { update_option( self::OPTION, self::sanitize( $values ), true ); self::reset(); } /** * Cleans settings: unknown keys dropped, every value to its type. * * @param array $values Raw values. * @return array */ public static function sanitize( array $values ) { $clean = self::defaults(); if ( isset( $values['provider'] ) && is_string( $values['provider'] ) && isset( self::SERVICES[ $values['provider'] ] ) ) { $clean['provider'] = $values['provider']; } foreach ( self::SERVICES as $field ) { if ( isset( $values[ $field ] ) && is_string( $values[ $field ] ) ) { $clean[ $field ] = self::clean_key( $values[ $field ] ); } } if ( isset( $values['style'] ) && in_array( $values['style'], array( 'on', 'off' ), true ) ) { $clean['style'] = $values['style']; } return $clean; } /** * An API key: letters, digits, "-" and "_", at most 100 characters. * * @param string $key Raw key. * @return string */ public static function clean_key( $key ) { $key = preg_replace( '/[^A-Za-z0-9_\-]/', '', trim( $key ) ); return substr( (string) $key, 0, 100 ); } /** * The chosen address service. * * @return string google, geoapify or here. */ public static function service() { return (string) self::get( 'provider' ); } /** * The key of the chosen service. * * @return string */ public static function key() { return (string) self::get( self::SERVICES[ self::service() ] ); } /** * Whether the chosen service has a key. * * @return bool */ public static function has_key() { return '' !== self::key(); } }