| 1 |
<?php |
| 2 |
|
| 3 |
namespace Templately\Modules\Settings; |
| 4 |
|
| 5 |
/** |
| 6 |
* Per-user UI preferences. |
| 7 |
* |
| 8 |
* Deliberately NOT stored through Utils\Options: that abstraction carries |
| 9 |
* global-login fallback semantics (a linked user's derived writes can land on |
| 10 |
* the global administrator's record), which is correct for account data and |
| 11 |
* wrong for personal UI taste. These are plain per-user, per-site options via |
| 12 |
* update_user_option()/get_user_option() — the same multisite-safe scoping, |
| 13 |
* no account indirection. |
| 14 |
*/ |
| 15 |
class Preferences { |
| 16 |
|
| 17 |
/** |
| 18 |
* Where the template modal lands when it opens. |
| 19 |
* 'auto' = context rules (empty editor → pages, content → blocks, admin → packs), |
| 20 |
* 'last' = last visited tab, or a fixed tab. |
| 21 |
*/ |
| 22 |
const EDITOR_DEFAULT_TAB_KEY = 'templately_editor_default_tab'; |
| 23 |
|
| 24 |
const ALLOWED_TABS = [ 'auto', 'last', 'packs', 'pages', 'blocks' ]; |
| 25 |
|
| 26 |
public static function get_editor_default_tab( $user_id = 0 ): string { |
| 27 |
$user_id = $user_id ? $user_id : get_current_user_id(); |
| 28 |
$value = get_user_option( self::EDITOR_DEFAULT_TAB_KEY, $user_id ); |
| 29 |
|
| 30 |
return in_array( $value, self::ALLOWED_TABS, true ) ? $value : 'auto'; |
| 31 |
} |
| 32 |
|
| 33 |
public static function set_editor_default_tab( $value, $user_id = 0 ) { |
| 34 |
if ( ! in_array( $value, self::ALLOWED_TABS, true ) ) { |
| 35 |
return false; |
| 36 |
} |
| 37 |
|
| 38 |
$user_id = $user_id ? $user_id : get_current_user_id(); |
| 39 |
if ( ! $user_id ) { |
| 40 |
return false; |
| 41 |
} |
| 42 |
|
| 43 |
update_user_option( $user_id, self::EDITOR_DEFAULT_TAB_KEY, $value ); |
| 44 |
|
| 45 |
return true; |
| 46 |
} |
| 47 |
|
| 48 |
/** |
| 49 |
* Apply an allow-listed preferences bag. Unknown keys and invalid values are |
| 50 |
* skipped, not errors — the response reports what was actually applied. |
| 51 |
* |
| 52 |
* @param array $preferences e.g. [ 'editor_default_tab' => 'blocks' ] |
| 53 |
* @return array Applied key => value pairs. |
| 54 |
*/ |
| 55 |
public static function update( array $preferences ): array { |
| 56 |
$applied = []; |
| 57 |
|
| 58 |
if ( isset( $preferences['editor_default_tab'] ) |
| 59 |
&& self::set_editor_default_tab( sanitize_key( $preferences['editor_default_tab'] ) ) ) { |
| 60 |
$applied['editor_default_tab'] = sanitize_key( $preferences['editor_default_tab'] ); |
| 61 |
} |
| 62 |
|
| 63 |
return $applied; |
| 64 |
} |
| 65 |
} |
| 66 |
|