Admin
2 years ago
Assets
2 years ago
Pages
3 years ago
PostTypes
2 years ago
Shortcodes
2 years ago
Sitemap
2 years ago
Templates
2 years ago
Users
3 years ago
ActionsService.php
3 years ago
CompatibilityService.php
2 years ago
HealthService.php
2 years ago
LineItemStateService.php
2 years ago
PluginService.php
3 years ago
PluginServiceProvider.php
2 years ago
RecaptchaValidationService.php
2 years ago
StateService.php
2 years ago
ThemeService.php
2 years ago
ThemeServiceProvider.php
3 years ago
TranslationsServiceProvider.php
3 years ago
StateService.php
84 lines
| 1 | <?php |
| 2 | |
| 3 | namespace SureCart\WordPress; |
| 4 | |
| 5 | /** |
| 6 | * InitialState class |
| 7 | * |
| 8 | * Manages the initial state of the store in the server and |
| 9 | * its serialization so it can be restored in the browser upon hydration. |
| 10 | */ |
| 11 | class StateService { |
| 12 | /** |
| 13 | * Store data. |
| 14 | * |
| 15 | * @var array |
| 16 | */ |
| 17 | private $store = array(); |
| 18 | |
| 19 | /** |
| 20 | * Set the store. |
| 21 | * |
| 22 | * @param array $store The store data. |
| 23 | */ |
| 24 | public function __construct( $store ) { |
| 25 | $this->store = $store; |
| 26 | } |
| 27 | |
| 28 | /** |
| 29 | * Render the store in the footer. |
| 30 | * |
| 31 | * @return void |
| 32 | */ |
| 33 | public function bootstrap() { |
| 34 | add_action( 'wp_footer', [ $this, 'render' ], 8 ); |
| 35 | } |
| 36 | |
| 37 | /** |
| 38 | * Get store data. |
| 39 | * |
| 40 | * @return array |
| 41 | */ |
| 42 | public function getData() { |
| 43 | return $this->store; |
| 44 | } |
| 45 | |
| 46 | /** |
| 47 | * Get the line items service. |
| 48 | * |
| 49 | * @return LineItemStateService |
| 50 | */ |
| 51 | public function lineItems() { |
| 52 | return new LineItemStateService(); |
| 53 | } |
| 54 | |
| 55 | /** |
| 56 | * Merge data. |
| 57 | * |
| 58 | * @param array $data The data that will be merged with the existing store. |
| 59 | */ |
| 60 | public function mergeData( $data ) { |
| 61 | $this->store = array_replace_recursive( $this->store, $data ); |
| 62 | } |
| 63 | |
| 64 | /** |
| 65 | * Reset the store data. |
| 66 | */ |
| 67 | public function reset() { |
| 68 | $this->store = array(); |
| 69 | } |
| 70 | |
| 71 | /** |
| 72 | * Render the store data. |
| 73 | */ |
| 74 | public function render() { |
| 75 | if ( empty( $this->store ) ) { |
| 76 | return; |
| 77 | } |
| 78 | echo sprintf( |
| 79 | '<script id="sc-store-data" type="application/json">%s</script>', |
| 80 | wp_json_encode( $this->store, JSON_HEX_TAG | JSON_HEX_AMP ) |
| 81 | ); |
| 82 | } |
| 83 | } |
| 84 |