Cart.php
8 months ago
CartItem.php
8 months ago
PluginData.php
7 months ago
ReachContact.php
7 months ago
Totals.php
8 months ago
CartItem.php
92 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Hostinger\Reach\Dto; |
| 4 | |
| 5 | use WC_Product; |
| 6 | |
| 7 | class CartItem { |
| 8 | |
| 9 | private WC_Product $product; |
| 10 | private int $quantity; |
| 11 | |
| 12 | public function __construct( int $product_id, int $quantity ) { |
| 13 | $this->product = wc_get_product( $product_id ); |
| 14 | $this->quantity = $quantity; |
| 15 | } |
| 16 | |
| 17 | public function to_array(): array { |
| 18 | return array( |
| 19 | 'quantity' => $this->quantity, |
| 20 | 'product_id' => $this->product->get_id(), |
| 21 | 'sku' => $this->product->get_sku(), |
| 22 | 'link' => $this->product->get_permalink(), |
| 23 | 'name' => $this->product->get_name(), |
| 24 | 'price' => $this->product->get_price(), |
| 25 | 'description' => $this->product->get_description(), |
| 26 | 'thumbnail' => $this->get_product_thumbnail( $this->product ), |
| 27 | 'tags' => $this->get_product_tags( $this->product ), |
| 28 | 'categories' => $this->get_categories( $this->product ), |
| 29 | ); |
| 30 | } |
| 31 | |
| 32 | public function get_categories( object $product ): array { |
| 33 | $categories = array(); |
| 34 | $category_ids = $product->get_category_ids(); |
| 35 | |
| 36 | if ( empty( $category_ids ) ) { |
| 37 | return $categories; |
| 38 | } |
| 39 | |
| 40 | foreach ( $category_ids as $category_id ) { |
| 41 | $term = get_term( $category_id, 'product_cat' ); |
| 42 | |
| 43 | if ( ! $term || is_wp_error( $term ) ) { |
| 44 | continue; |
| 45 | } |
| 46 | |
| 47 | $categories[] = array( |
| 48 | 'id' => $term->term_id, |
| 49 | 'name' => $term->name, |
| 50 | 'slug' => $term->slug, |
| 51 | 'link' => get_term_link( $term ), |
| 52 | ); |
| 53 | } |
| 54 | |
| 55 | return $categories; |
| 56 | } |
| 57 | |
| 58 | public function get_product_thumbnail( object $product ): string { |
| 59 | $image_data = $product->get_image_id() ? wp_get_attachment_image_src( $product->get_image_id(), 'full' ) : array(); |
| 60 | if ( ! empty( $image_data ) ) { |
| 61 | return $image_data[0]; |
| 62 | } |
| 63 | |
| 64 | return ''; |
| 65 | } |
| 66 | |
| 67 | public function get_product_tags( object $product ): array { |
| 68 | $tags = array(); |
| 69 | $tag_ids = $product->get_tag_ids(); |
| 70 | |
| 71 | if ( empty( $tag_ids ) ) { |
| 72 | return $tags; |
| 73 | } |
| 74 | |
| 75 | foreach ( $tag_ids as $tag_id ) { |
| 76 | $term = get_term( $tag_id, 'product_tag' ); |
| 77 | |
| 78 | if ( ! $term || is_wp_error( $term ) ) { |
| 79 | continue; |
| 80 | } |
| 81 | |
| 82 | $tags[] = array( |
| 83 | 'id' => $term->term_id, |
| 84 | 'name' => $term->name, |
| 85 | 'slug' => $term->slug, |
| 86 | ); |
| 87 | } |
| 88 | |
| 89 | return $tags; |
| 90 | } |
| 91 | } |
| 92 |