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