CartService.php
93 lines
| 1 | <?php |
| 2 | |
| 3 | namespace SureCart\Cart; |
| 4 | |
| 5 | use SureCart\Models\Form; |
| 6 | |
| 7 | /** |
| 8 | * The cart service. |
| 9 | */ |
| 10 | class CartService { |
| 11 | /** |
| 12 | * Bootstrap the cart. |
| 13 | * |
| 14 | * @return void |
| 15 | */ |
| 16 | public function bootstrap() { |
| 17 | // Slide-out is disabled. Do not load scripts. |
| 18 | if ( (bool) get_option( 'sc_slide_out_cart_disabled', false ) ) { |
| 19 | return; |
| 20 | } |
| 21 | |
| 22 | // enqueue scripts needed for slide out cart. |
| 23 | add_action( |
| 24 | 'wp_enqueue_scripts', |
| 25 | function() { |
| 26 | \SureCart::assets()->enqueueComponents(); |
| 27 | } |
| 28 | ); |
| 29 | add_action( 'wp_footer', [ $this, 'renderCartComponent' ] ); |
| 30 | } |
| 31 | |
| 32 | /** |
| 33 | * Get the cart template. |
| 34 | * |
| 35 | * @return string |
| 36 | */ |
| 37 | public function cartTemplate() { |
| 38 | ob_start(); |
| 39 | $form = $this->getForm(); |
| 40 | if ( empty( $form->ID ) ) { |
| 41 | return ''; |
| 42 | } |
| 43 | $cart = \SureCart::cartPost()->get(); |
| 44 | if ( empty( $cart->post_content ) ) { |
| 45 | return ''; |
| 46 | } |
| 47 | ?> |
| 48 | |
| 49 | <sc-cart |
| 50 | id="sc-cart" |
| 51 | header="<?php esc_attr_e( 'Cart', 'surecart' ); ?>" |
| 52 | form-id="<?php echo esc_attr( $form->ID ); ?>" |
| 53 | mode="<?php echo esc_attr( Form::getMode( $form->ID ) ); ?>" |
| 54 | checkout-link="<?php echo esc_attr( \SureCart::pages()->url( 'checkout' ) ); ?>" |
| 55 | style="font-size: 16px"> |
| 56 | |
| 57 | <?php echo wp_kses_post( do_blocks( $cart->post_content ) ); ?> |
| 58 | |
| 59 | </sc-cart> |
| 60 | <?php |
| 61 | return trim( preg_replace( '/\s+/', ' ', ob_get_clean() ) ); |
| 62 | } |
| 63 | |
| 64 | /** |
| 65 | * Render the cart components. |
| 66 | * |
| 67 | * @return void |
| 68 | */ |
| 69 | public function renderCartComponent() { |
| 70 | $form = $this->getForm(); |
| 71 | if ( empty( $form->ID ) ) { |
| 72 | return; |
| 73 | } |
| 74 | $template = $this->cartTemplate(); |
| 75 | ?> |
| 76 | <sc-cart-loader |
| 77 | form-id="<?php echo esc_attr( $form->ID ); ?>" |
| 78 | mode="<?php echo esc_attr( Form::getMode( $form->ID ) ); ?>" |
| 79 | template='<?php echo esc_attr( $template ); ?>'> |
| 80 | </sc-cart-loader> |
| 81 | <?php |
| 82 | } |
| 83 | |
| 84 | /** |
| 85 | * Get the form |
| 86 | * |
| 87 | * @return \WP_Post The default form post. |
| 88 | */ |
| 89 | public function getForm() { |
| 90 | return \SureCart::forms()->getDefault(); |
| 91 | } |
| 92 | } |
| 93 |