> */ private array $items; /** * @var string */ private string $total; /** * @var string */ private string $created_at; /** * Constructor. * * @param string $phone Customer phone. * @param array $items Cart items. * @param string $total Cart total. * @param string $created_at Created timestamp. */ public function __construct( string $phone, array $items = array(), string $total = '0', string $created_at = '' ) { $this->phone = $phone; $this->items = $items; $this->total = $total; $this->created_at = $created_at ?: current_time( 'mysql' ); } /** * Create from WooCommerce cart. * * @param string $phone Customer phone. * @return self */ public static function fromCart( string $phone ): self { $items = array(); $total = '0'; if ( function_exists( 'WC' ) && WC()->cart ) { $cart = WC()->cart; foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) { $product = $cart_item['data'] ?? null; if ( $product instanceof \WC_Product ) { $items[] = array( 'product_id' => $product->get_id(), 'name' => $product->get_name(), 'quantity' => $cart_item['quantity'] ?? 1, 'price' => $product->get_price(), ); } } $total = (string) $cart->get_cart_total(); } return new self( $phone, $items, $total ); } /** * Convert to array for JSON storage. * * @return array */ public function toArray(): array { return array( 'phone' => $this->phone, 'items' => $this->items, 'total' => $this->total, 'created_at' => $this->created_at, ); } /** * Create from stored array. * * @param array $data Stored data. * @return self */ public static function fromArray( array $data ): self { return new self( (string) ( $data['phone'] ?? '' ), (array) ( $data['items'] ?? array() ), (string) ( $data['total'] ?? '0' ), (string) ( $data['created_at'] ?? '' ) ); } /** * Get phone. * * @return string */ public function getPhone(): string { return $this->phone; } /** * Get items. * * @return array> */ public function getItems(): array { return $this->items; } /** * Get total. * * @return string */ public function getTotal(): string { return $this->total; } /** * Get cart data for Variables/template context. * * @return array */ public function getCartDataForContext(): array { return array( 'items' => $this->items, 'total' => $this->total, ); } }