|
| 1 | +<?php |
| 2 | +namespace Carbon_Fields\Datastore\Datastore; |
| 3 | +use Carbon_Fields\Field\Field; |
| 4 | +use Carbon_Fields\Datastore\Datastore; |
| 5 | + |
| 6 | +/** |
| 7 | + * Stores serialized values in the database |
| 8 | + */ |
| 9 | +class Serialized_Theme_Options_Datastore extends Datastore { |
| 10 | + |
| 11 | + /** |
| 12 | + * Initialization tasks for concrete datastores. |
| 13 | + **/ |
| 14 | + public function init() { |
| 15 | + |
| 16 | + } |
| 17 | + |
| 18 | + protected function get_key_for_field( Field $field ) { |
| 19 | + $key = '_' . $field->get_base_name(); |
| 20 | + return $key; |
| 21 | + } |
| 22 | + |
| 23 | + /** |
| 24 | + * Save a single key-value pair to the database with autoload |
| 25 | + * |
| 26 | + * @param string $key |
| 27 | + * @param string $value |
| 28 | + * @param bool $autoload |
| 29 | + */ |
| 30 | + protected function save_key_value_pair_with_autoload( $key, $value, $autoload ) { |
| 31 | + $notoptions = wp_cache_get( 'notoptions', 'options' ); |
| 32 | + $notoptions[ $key ] = ''; |
| 33 | + wp_cache_set( 'notoptions', $notoptions, 'options' ); |
| 34 | + $autoload = $autoload ? 'yes' : 'no'; |
| 35 | + |
| 36 | + if ( ! add_option( $key, $value, null, $autoload ) ) { |
| 37 | + update_option( $key, $value, $autoload ); |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + /** |
| 42 | + * Load the field value(s) |
| 43 | + * |
| 44 | + * @param Field $field The field to load value(s) in. |
| 45 | + * @return array |
| 46 | + */ |
| 47 | + public function load( Field $field ) { |
| 48 | + $key = $this->get_key_for_field( $field ); |
| 49 | + $value = get_option( $key, null ); |
| 50 | + return $value; |
| 51 | + } |
| 52 | + |
| 53 | + /** |
| 54 | + * Save the field value(s) |
| 55 | + * |
| 56 | + * @param Field $field The field to save. |
| 57 | + */ |
| 58 | + public function save( Field $field ) { |
| 59 | + if ( ! empty( $field->get_hierarchy() ) ) { |
| 60 | + return; // only applicable to root fields |
| 61 | + } |
| 62 | + $key = $this->get_key_for_field( $field ); |
| 63 | + $value = $field->get_full_value(); |
| 64 | + if ( is_a( $field, '\\Carbon_Fields\\Field\\Complex_Field' ) ) { |
| 65 | + $value = $field->get_value_tree(); |
| 66 | + } |
| 67 | + $this->save_key_value_pair_with_autoload( $key, $value, $field->get_autoload() ); |
| 68 | + } |
| 69 | + |
| 70 | + /** |
| 71 | + * Delete the field value(s) |
| 72 | + * |
| 73 | + * @param Field $field The field to delete. |
| 74 | + */ |
| 75 | + public function delete( Field $field ) { |
| 76 | + if ( ! empty( $field->get_hierarchy() ) ) { |
| 77 | + return; // only applicable to root fields |
| 78 | + } |
| 79 | + $key = $this->get_key_for_field( $field ); |
| 80 | + delete_option( $key ); |
| 81 | + } |
| 82 | +} |
0 commit comments