ProductBlock.php
| 1 | <?php |
| 2 | |
| 3 | namespace SureCartBlocks\Blocks\Product; |
| 4 | |
| 5 | use SureCart\Models\Product; |
| 6 | use SureCartBlocks\Blocks\BaseBlock; |
| 7 | |
| 8 | /** |
| 9 | * Product Block |
| 10 | */ |
| 11 | abstract class ProductBlock extends BaseBlock { |
| 12 | /** |
| 13 | * Set initial product state |
| 14 | * |
| 15 | * @param Product $product The current product. |
| 16 | * |
| 17 | * @return void |
| 18 | */ |
| 19 | public function setInitialState( $product ) { |
| 20 | if ( empty( $product->id ) ) { |
| 21 | return; |
| 22 | } |
| 23 | |
| 24 | $state = sc_initial_state(); |
| 25 | |
| 26 | // we already have state for this product. |
| 27 | if ( ! empty( $state['product'][ $product->id ] ) ) { |
| 28 | return; |
| 29 | } |
| 30 | |
| 31 | $product_state[ $product->id ] = $product->getInitialPageState(); |
| 32 | |
| 33 | sc_initial_state( |
| 34 | [ |
| 35 | 'product' => $product_state, |
| 36 | ] |
| 37 | ); |
| 38 | } |
| 39 | |
| 40 | /** |
| 41 | * Get the product |
| 42 | * |
| 43 | * @param string $id The product id. |
| 44 | * |
| 45 | * @return Product|null |
| 46 | */ |
| 47 | public function getProduct( string $id ) { |
| 48 | if ( empty( $id ) ) { |
| 49 | return get_query_var( 'surecart_current_product' ); |
| 50 | } |
| 51 | |
| 52 | $product = Product::with( [ 'image', 'prices', 'product_medias', 'variant_options', 'variants', 'product_media.media', 'product_collections' ] )->find( $id ); |
| 53 | |
| 54 | return ! empty( $product->id ) ? $product : null; |
| 55 | } |
| 56 | |
| 57 | /** |
| 58 | * Get product and call set state. |
| 59 | * |
| 60 | * @param string $id The product id. |
| 61 | * |
| 62 | * @return \SureCart\Models\Product|null |
| 63 | */ |
| 64 | public function getProductAndSetInitialState( $id ) { |
| 65 | $product = $this->getProduct( $id ); |
| 66 | |
| 67 | if ( empty( $product ) ) { |
| 68 | return; |
| 69 | } |
| 70 | |
| 71 | $this->setInitialState( $product ); |
| 72 | |
| 73 | return $product; |
| 74 | } |
| 75 | } |
| 76 |