| 1 |
<?php |
| 2 |
|
| 3 |
namespace Code_Snippets\REST_API\Preferences; |
| 4 |
|
| 5 |
/** |
| 6 |
* Controller for reading and updating the user's preference whether snippet lists |
| 7 |
* display as a table or a grid of cards. |
| 8 |
* |
| 9 |
* @package Code_Snippets |
| 10 |
*/ |
| 11 |
final class Snippet_View_REST_Controller extends Preference_REST_Controller { |
| 12 |
|
| 13 |
/** |
| 14 |
* Current API version. |
| 15 |
*/ |
| 16 |
public const VERSION = 1; |
| 17 |
|
| 18 |
/** |
| 19 |
* The base suffix of this controller's route. |
| 20 |
*/ |
| 21 |
public const BASE_ROUTE = 'snippet-view'; |
| 22 |
|
| 23 |
/** |
| 24 |
* The key used to identify this preference in the REST API. |
| 25 |
*/ |
| 26 |
protected const PREFERENCE_KEY = 'view'; |
| 27 |
|
| 28 |
/** |
| 29 |
* The name of the option used to store the snippet view preference. |
| 30 |
*/ |
| 31 |
public const OPTION_NAME = 'code_snippets_snippet_view'; |
| 32 |
|
| 33 |
/** |
| 34 |
* Valid snippet view values. |
| 35 |
*/ |
| 36 |
public const VALID_VIEWS = [ 'card', 'table' ]; |
| 37 |
|
| 38 |
/** |
| 39 |
* The snippet view shown when no preference has been saved. |
| 40 |
*/ |
| 41 |
protected const DEFAULT_VIEW = 'table'; |
| 42 |
|
| 43 |
/** |
| 44 |
* Retrieve the current snippet view preference, falling back to the |
| 45 |
* default when the stored value is missing or invalid. |
| 46 |
* |
| 47 |
* @return string Either 'card' or 'table'. |
| 48 |
*/ |
| 49 |
public static function get_snippet_view(): string { |
| 50 |
$view = get_option( self::OPTION_NAME, self::DEFAULT_VIEW ); |
| 51 |
|
| 52 |
return in_array( $view, self::VALID_VIEWS, true ) |
| 53 |
? $view |
| 54 |
: self::DEFAULT_VIEW; |
| 55 |
} |
| 56 |
|
| 57 |
/** |
| 58 |
* Retrieve the stored preference value, falling back to the default when the stored value is missing or invalid. |
| 59 |
* |
| 60 |
* @return string |
| 61 |
*/ |
| 62 |
protected function get_option_value(): string { |
| 63 |
return self::get_snippet_view(); |
| 64 |
} |
| 65 |
|
| 66 |
/** |
| 67 |
* Get the schema for the update request argument. |
| 68 |
* |
| 69 |
* @return array The schema for the update request argument. |
| 70 |
*/ |
| 71 |
protected function get_update_request_schema(): array { |
| 72 |
return [ |
| 73 |
'description' => esc_html__( 'Whether snippet lists display as a grid of cards or a table.', 'code-snippets' ), |
| 74 |
'type' => 'string', |
| 75 |
'enum' => self::VALID_VIEWS, |
| 76 |
'required' => true, |
| 77 |
]; |
| 78 |
} |
| 79 |
} |
| 80 |
|