Block.php
85 lines
| 1 | <?php |
| 2 | |
| 3 | namespace SureCartBlocks\Blocks\VariantPriceSelector; |
| 4 | |
| 5 | use SureCart\Models\Component; |
| 6 | use SureCart\Models\Product; |
| 7 | use SureCartBlocks\Blocks\BaseBlock; |
| 8 | |
| 9 | /** |
| 10 | * Product Variant Selector Block. |
| 11 | */ |
| 12 | class Block extends BaseBlock { |
| 13 | /** |
| 14 | * Keep track of number of instances. |
| 15 | * |
| 16 | * @var integer |
| 17 | */ |
| 18 | public static $instance = 0; |
| 19 | |
| 20 | /** |
| 21 | * Render the block |
| 22 | * |
| 23 | * @param array $attributes Block attributes. |
| 24 | * @param string $content Post content. |
| 25 | * |
| 26 | * @return string |
| 27 | */ |
| 28 | public function render( $attributes, $content = '' ) { |
| 29 | $product = Product::with( |
| 30 | [ |
| 31 | 'prices', |
| 32 | 'variants', |
| 33 | 'variant_options', |
| 34 | ] |
| 35 | )->find( $attributes['product_id'] ); |
| 36 | |
| 37 | if ( empty( $product ) || is_wp_error( $product ) ) { |
| 38 | return ''; |
| 39 | } |
| 40 | |
| 41 | // only active prices. |
| 42 | $product = $product->withActivePrices()->withSortedPrices(); |
| 43 | |
| 44 | // active prices. |
| 45 | $first_variant_with_stock = $product->first_variant_with_stock; |
| 46 | |
| 47 | // must have at least one active price. |
| 48 | if ( empty( $product->prices->data[0] ) ) { |
| 49 | return ''; |
| 50 | } |
| 51 | |
| 52 | if ( ! empty( $product->prices->data[0]->id ) ) { |
| 53 | $line_item = array_merge( |
| 54 | [ |
| 55 | 'price_id' => $product->prices->data[0]->id, |
| 56 | 'quantity' => 1, |
| 57 | ], |
| 58 | ! empty( $first_variant_with_stock->id ) ? [ 'variant_id' => $first_variant_with_stock->id ] : [] |
| 59 | ); |
| 60 | |
| 61 | sc_initial_state( |
| 62 | [ |
| 63 | 'checkout' => [ |
| 64 | 'initialLineItems' => sc_initial_line_items( [ $line_item ] ), |
| 65 | ], |
| 66 | ] |
| 67 | ); |
| 68 | } |
| 69 | |
| 70 | self::$instance++; |
| 71 | |
| 72 | return wp_kses_post( |
| 73 | Component::tag( 'sc-checkout-product-price-variant-selector' ) |
| 74 | ->id( 'sc-checkout-product-price-variant-selector-' . (int) self::$instance ) |
| 75 | ->with( |
| 76 | [ |
| 77 | 'product' => $product, |
| 78 | 'label' => ! empty( $attributes['label'] ) ? $attributes['label'] : '', |
| 79 | 'selectorTitle' => ! empty( $attributes['selectorTitle'] ) ? $attributes['selectorTitle'] : '', |
| 80 | ] |
| 81 | )->render( '' ) |
| 82 | ); |
| 83 | } |
| 84 | } |
| 85 |