|null */ private ?array $cache = null; /** * Get default settings. * * @return array */ public static function defaults(): array { return [ 'crawlers' => CrawlerPolicy::defaults(), 'override' => '', ]; } /** * Get a setting value. * * @param string $key Setting key. * @param mixed $fallback Fallback if not set. * @return mixed The result. */ public function get( string $key, mixed $fallback = null ): mixed { $all = $this->all(); if ( array_key_exists( $key, $all ) ) { return $all[ $key ]; } return $fallback; } /** * Get all merged settings. * * @return array */ public function all(): array { if ( null !== $this->cache ) { return $this->cache; } $stored = get_option( self::OPTION, [] ); if ( ! is_array( $stored ) ) { $stored = []; } $merged = array_merge( self::defaults(), $stored ); $merged['crawlers'] = CrawlerPolicy::sanitizeMap( $merged['crawlers'] ?? [] ); $this->cache = $merged; return $this->cache; } /** * Update settings with a partial array (whitelisted keys only). * * @param array $partial Partial settings to merge. * @return bool Whether anything was saved. */ public function set( array $partial ): bool { $allowed = array_keys( self::defaults() ); $sanitized = []; foreach ( $partial as $key => $value ) { if ( ! is_string( $key ) || ! in_array( $key, $allowed, true ) ) { continue; } $sanitized[ $key ] = $this->sanitize( $key, $value ); } if ( [] === $sanitized ) { return false; } $current = $this->all(); $merged = array_merge( $current, $sanitized ); // update_option() returns false both when the value is unchanged and // when the write fails, so the write is skipped when nothing changed. // An unchanged save still counts as a success; a changed write that // returns false reports the failure instead of updating the cache. if ( $merged === $current ) { return true; } if ( ! update_option( self::OPTION, $merged, false ) ) { return false; } $this->cache = $merged; return true; } /** * Sanitize a single value by key. * * @param string $key Setting key. * @param mixed $value Raw value. * @return mixed Sanitized value. */ private function sanitize( string $key, mixed $value ): mixed { switch ( $key ) { case 'override': return RobotsDirectives::normalize( is_string( $value ) ? $value : '' ); case 'crawlers': return CrawlerPolicy::sanitizeMap( $value ); } return null; } }