$input what the write sends * @param array $current the stored settings this write replaces */ public static function clearedByMove(#[\SensitiveParameter] array $input, #[\SensitiveParameter] array $current): bool { return Schema::providerKeyClearedByMove($input, $current) && self::resolve($current['provider.api_key'] ?? '') !== ''; } /** Stores `$key`, autoload off; '' deletes the option, so a site with no key has no row. */ public static function put(#[\SensitiveParameter] string $key): void { if ($key === '') { delete_option(self::OPTION); return; } update_option(self::OPTION, $key, false); } /** * The lift (the class docblock). `$value` is what is about to be written and `$old` what is * stored, as core hands them to the filter; a `$value` that is not an array is handed back as * it came. A row that leaves the key out says there is none, since a read merges the '' * default over it. "Keep" with nothing held keeps a plaintext key `$old` still carries: a raw * write of the mask over a row migrate() has not reached. The option is written only when * the key changes. */ public function beforeSave(#[\SensitiveParameter] mixed $value, #[\SensitiveParameter] mixed $old): mixed { if (!is_array($value)) { return $value; } $held = self::held(); $posted = array_key_exists('provider.api_key', $value) ? $value['provider.api_key'] : ''; $key = match (true) { $posted === Schema::MASK, !is_string($posted) => $held !== '' ? $held : (self::pending($old) ? (string) $old['provider.api_key'] : ''), default => $posted, }; if ($key !== $held) { self::put($key); } $value['provider.api_key'] = $key === '' ? '' : Schema::MASK; return $value; } /** * Whether a settings row still carries its key in plaintext: its `provider.api_key` is a * string other than '' and MASK. The row is autoloaded, so asking costs no query. * * @phpstan-assert-if-true array{'provider.api_key': non-empty-string} $row */ public static function pending(#[\SensitiveParameter] mixed $row): bool { $key = is_array($row) ? ($row['provider.api_key'] ?? '') : ''; return is_string($key) && $key !== '' && $key !== Schema::MASK; } /** * The one-time move from a row written before 0.6.1: the plaintext key into the option, then * the row rewritten with MASK. Plugin::register() runs it on `init`; a row that is not pending * is left alone, so a second run writes nothing. The row is rewritten only once the option * holds the key, so a failed write of either leaves the plaintext in the row, which resolve() * still reads and the next request moves again. */ public static function migrate(): void { $row = get_option(Plugin::OPTION); if (!self::pending($row)) { return; } self::put($row['provider.api_key']); if (self::held() !== $row['provider.api_key']) { return; } $row['provider.api_key'] = Schema::MASK; update_option(Plugin::OPTION, $row); } }