PluginProbe
FluentCart A New Era of eCommerce – Faster, Lighter, and Simpler / 1.3.25
FluentCart A New Era of eCommerce – Faster, Lighter, and Simpler v1.3.25
1.6.6 1.6.5 1.6.4 1.6.3 1.6.2 1.6.1 1.6.0 1.5.4 1.5.5 1.5.3 1.5.2 1.5.1 1.5.0 1.4.2 1.4.1 1.4.0 1.3.28 1.3.27 1.3.26 1.3.25 1.3.23 1.3.22 1.3.21 1.3.20 1.3.19 All 49 releases
fluent-cart / app / Services / Renderer / ProductCardRender.php

ProductCardRender.php in FluentCart A New Era of eCommerce – Faster, Lighter, and Simpler 1.3.25, at app/Services/Renderer/ProductCardRender.php

584 lines 23.6 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace FluentCart\App\Services\Renderer;
4
5 use FluentCart\Api\ModuleSettings;
6 use FluentCart\App\Helpers\Helper;
7 use FluentCart\App\Models\Product;
8 use FluentCart\App\Models\ProductVariation;
9 use FluentCart\App\Modules\Templating\AssetLoader;
10 use FluentCart\App\Vite;
11 use FluentCart\Framework\Support\Arr;
12
13 class ProductCardRender
14 {
15 protected $product;
16
17 protected $viewUrl = '';
18
19 protected $config = [];
20
21 public function __construct(Product $product, $config = [])
22 {
23 $this->product = $product;
24 $this->viewUrl = $product->view_url;
25 $this->config = $config;
26 }
27
28 public function renderWrapperStart()
29 {
30
31 }
32
33 public function renderWrapperEnd()
34 {
35
36 }
37
38 public function render()
39 {
40 AssetLoader::loadSingleProductAssets();
41 $cursor = '';
42 if (!empty($this->config['cursor'])) {
43 $cursor = 'data-fluent-cart-cursor="' . esc_attr($this->config['cursor']) . '"';
44 }
45
46 $cardWidth = '';
47 $cardWidthValue = Arr::get($this->config, 'card_width', '');
48 if ($cardWidthValue) {
49 $widthValue = $cardWidthValue === '100%' ? '100%' : intval($cardWidthValue) . 'px';
50 $cardWidth = 'style="width: ' . esc_attr($widthValue) . ';"';
51 }
52
53
54 ?>
55 <article data-fluent-cart-shop-app-single-product data-fct-product-card=""
56 class="fct-product-card"
57 <?php echo $cursor; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Already escaped ?>
58 <?php echo $cardWidth; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Already escaped ?>
59 aria-label="<?php echo esc_attr(sprintf(
60 /* translators: %s: product title */
61 __('%s product card', 'fluent-cart'), $this->product->post_title));
62 ?>">
63 <?php $this->renderProductImage(); ?>
64 <?php $this->renderTitle(); ?>
65 <?php $this->renderExcerpt(); ?>
66 <?php $this->renderPrices(); ?>
67 <?php $this->showBuyButton(); ?>
68 </article>
69 <?php
70 }
71
72 /**
73 * Build package info string from snapshotted other_info fields.
74 *
75 * @param array $otherInfo Order item's other_info array
76 * @return string e.g. "Gift (Box) · 30 × 20 × 15 cm · Wt: 2 kg · Shipping: 2.5 kg"
77 */
78 public static function buildPackageInfoFromOtherInfo($otherInfo)
79 {
80 $storeWeightUnit = Helper::shopConfig('weight_unit') ?: 'kg';
81 $parts = [];
82
83 // Package name
84 $name = Arr::get($otherInfo, 'package_name', '');
85 if ($name) {
86 $parts[] = $name;
87 }
88
89 // Dimensions
90 $length = Arr::get($otherInfo, 'package_length', '');
91 $width = Arr::get($otherInfo, 'package_width', '');
92 $height = Arr::get($otherInfo, 'package_height', '');
93 $dimensionUnit = Arr::get($otherInfo, 'package_dimension_unit', 'cm');
94 $dimParts = array_filter([$length, $width, $height], function ($val) {
95 return $val !== '' && $val !== null && $val != 0;
96 });
97 if ($dimParts) {
98 $parts[] = implode(' × ', $dimParts) . ' ' . $dimensionUnit;
99 }
100
101 // Product weight
102 $productWeight = floatval(Arr::get($otherInfo, 'weight', 0));
103 $productWeightUnit = Arr::get($otherInfo, 'weight_unit', $storeWeightUnit);
104 $convertedProductWeight = Helper::convertWeight($productWeight, $productWeightUnit, $storeWeightUnit);
105 if ($convertedProductWeight) {
106 $formatted = rtrim(rtrim(number_format($convertedProductWeight, 2), '0'), '.');
107 $parts[] = __('Wt:', 'fluent-cart') . ' ' . $formatted . ' ' . $storeWeightUnit;
108 }
109
110 // Shipping weight (product + package)
111 $packageWeight = floatval(Arr::get($otherInfo, 'package_weight', 0));
112 $packageWeightUnit = Arr::get($otherInfo, 'package_weight_unit', $storeWeightUnit);
113 $convertedPackageWeight = Helper::convertWeight($packageWeight, $packageWeightUnit, $storeWeightUnit);
114 $totalWeight = $convertedProductWeight + $convertedPackageWeight;
115 if ($totalWeight && $convertedPackageWeight) {
116 $formatted = rtrim(rtrim(number_format($totalWeight, 2), '0'), '.');
117 $parts[] = __('Shipping wt:', 'fluent-cart') . ' ' . $formatted . ' ' . $storeWeightUnit;
118 }
119
120 $info = implode(' · ', $parts);
121
122 return $info ? __('Package:', 'fluent-cart') . ' ' . $info : '';
123 }
124
125 public function renderPackageDescription(
126 $wrapper_attributes = '',
127 $showName = true,
128 $showDimensions = true,
129 $showProductWeight = true,
130 $showTotalWeight = true,
131 $variant = null
132 ) {
133 $variant = $variant ?: $this->product->variants->first();
134
135 if (!$variant) {
136 return;
137 }
138
139 if (!$wrapper_attributes) {
140 $wrapper_attributes = 'class="fct-package-description" data-fluent-cart-package-description';
141 }
142
143 $this->renderPackageDescriptionForVariant($variant, $wrapper_attributes, $showName, $showDimensions, $showProductWeight, $showTotalWeight);
144 }
145
146 private function renderPackageDescriptionForVariant(
147 ProductVariation $variant,
148 $wrapper_attributes,
149 $showName,
150 $showDimensions,
151 $showProductWeight,
152 $showTotalWeight
153 ) {
154 $packageSlug = Arr::get($variant->other_info, 'package_slug', '');
155 $package = Helper::getPackageBySlug($packageSlug);
156
157 if (!$package) {
158 return;
159 }
160
161 $name = Arr::get($package, 'name', '');
162 $length = Arr::get($package, 'length', '');
163 $width = Arr::get($package, 'width', '');
164 $height = Arr::get($package, 'height', '');
165 $dimensionUnit = Arr::get($package, 'dimension_unit', 'cm');
166 $packageWeight = floatval(Arr::get($package, 'weight', 0));
167 $packageWeightUnit = Arr::get($package, 'weight_unit', 'kg');
168
169 $storeWeightUnit = Helper::shopConfig('weight_unit') ?: 'kg';
170 $otherInfo = $variant->other_info ?: [];
171 $productWeight = floatval(Arr::get($otherInfo, 'weight', 0));
172 $productWeightUnit = Arr::get($otherInfo, 'weight_unit', $storeWeightUnit);
173
174 $convertedProductWeight = Helper::convertWeight($productWeight, $productWeightUnit, $storeWeightUnit);
175 $convertedPackageWeight = Helper::convertWeight($packageWeight, $packageWeightUnit, $storeWeightUnit);
176 $totalWeight = $convertedProductWeight + $convertedPackageWeight;
177
178 $hasVisibleContent = ($showName && $name)
179 || ($showDimensions && ($length || $width || $height))
180 || ($showProductWeight && $convertedProductWeight)
181 || ($showTotalWeight && $totalWeight);
182
183 if (!$hasVisibleContent) {
184 return;
185 }
186
187 echo sprintf('<div %s>', $wrapper_attributes); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
188 echo '<table class="fct-package-description__table" role="presentation"><tbody>';
189
190 if ($showName && $name) {
191 echo sprintf(
192 '<tr><th>%s</th><td>%s</td></tr>',
193 esc_html__('Package', 'fluent-cart'),
194 esc_html($name)
195 );
196 }
197
198 if ($showDimensions && ($length || $width || $height)) {
199 $dimensionParts = array_filter([$length, $width, $height], function ($val) {
200 return $val !== '' && $val !== null;
201 });
202 if ($dimensionParts) {
203 $formattedDimensions = implode(' × ', $dimensionParts) . ' ' . $dimensionUnit;
204 echo sprintf(
205 '<tr><th>%s</th><td>%s</td></tr>',
206 esc_html__('Dimensions', 'fluent-cart'),
207 esc_html($formattedDimensions)
208 );
209 }
210 }
211
212 if ($showProductWeight && $convertedProductWeight) {
213 $formattedProductWeight = rtrim(rtrim(number_format($convertedProductWeight, 2), '0'), '.');
214 echo sprintf(
215 '<tr><th>%s</th><td>%s</td></tr>',
216 esc_html__('Weight', 'fluent-cart'),
217 esc_html($formattedProductWeight . ' ' . $storeWeightUnit)
218 );
219 }
220
221 if ($showTotalWeight && $totalWeight && $convertedPackageWeight) {
222 $formattedTotalWeight = rtrim(rtrim(number_format($totalWeight, 2), '0'), '.');
223 echo sprintf(
224 '<tr><th>%s</th><td>%s</td></tr>',
225 esc_html__('Shipping Weight', 'fluent-cart'),
226 esc_html($formattedTotalWeight . ' ' . $storeWeightUnit)
227 );
228 }
229
230 echo '</tbody></table>';
231 echo '</div>';
232 }
233
234 public function renderExcerpt($atts = '')
235 {
236 if (empty($this->product->post_excerpt)) {
237 return;
238 }
239
240 echo sprintf(
241 '<p %1$s class="fct-product-card-excerpt">
242 %2$s
243 </p>',
244 $atts, // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
245 wp_kses_post($this->product->post_excerpt),
246 );
247 }
248
249 public function renderTitle($atts = '', $config = [])
250 {
251 $link = Arr::get($config, 'isLink', true);
252 $target = Arr::get($config, 'target', '_self');
253
254 $titleText = esc_html($this->product->post_title);
255
256 if ($link) {
257 // Render as link
258 $targetAttr = $target === '_blank' ? 'target="_blank" rel="noopener noreferrer"' : '';
259 echo sprintf(
260 '<h3 class="fct-product-card-title">
261 <a %1$s data-fluent-cart-product-link
262 data-product-id="%2$s"
263 href="%3$s"
264 aria-label="%4$s"
265 %5$s>%6$s</a>
266 </h3>',
267 $atts, // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
268 esc_attr($this->product->ID),
269 esc_url($this->product->view_url),
270 esc_attr($this->product->post_title),
271 $targetAttr, // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
272 esc_html($titleText)
273 );
274 } else {
275 // Render as plain text (no link)
276 echo sprintf(
277 '<h3 class="fct-product-card-title" %1$s>%2$s</h3>',
278 $atts, // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
279 esc_html($titleText)
280 );
281 }
282 }
283
284 public function renderProductImage()
285 {
286 $image = $this->product->thumbnail;
287 $isPlaceholder = false;
288
289 if (!$image) {
290 $image = Vite::getAssetUrl('images/placeholder.svg');
291 $isPlaceholder = true;
292 }
293
294 $altText = $isPlaceholder
295 ? sprintf(
296 /* translators: %s: product title */
297 __('Placeholder image for %s', 'fluent-cart'), $this->product->post_title)
298 : $this->product->post_title;
299
300 do_action('fluent_cart/product/group/before_image_block', [
301 'product' => $this->product,
302 'scope' => 'product_card'
303 ]);
304 ?>
305 <a class="fct-product-card-image-wrap"
306 href="<?php echo esc_url($this->viewUrl); ?>"
307 style="display: block;"
308 aria-label="<?php echo esc_attr(sprintf(
309 /* translators: %s: product title */
310 __('View %s product image', 'fluent-cart'), $this->product->post_title)); ?>">
311 <img class="fct-product-card-image"
312 data-fluent-cart-shop-app-single-product-image
313 src="<?php echo esc_url($image); ?>"
314 alt="<?php echo esc_attr($altText); ?>"
315 loading="lazy"
316 width="300"
317 height="300"/>
318 </a>
319 <?php
320
321 do_action('fluent_cart/product/group/after_image_block', [
322 'product' => $this->product,
323 'scope' => 'product_card'
324 ]);
325 }
326
327 public function renderPrices($wrapper_attributes = '')
328 {
329 $priceFormat = Arr::get($this->config, 'price_format', 'starts_from');
330 $isSimple = $this->product->detail->variation_type === 'simple';
331 $minPrice = $this->product->detail->min_price;
332 $maxPrice = $this->product->detail->max_price;
333 $comparePrice = 0;
334
335 if ($isSimple) {
336 $firstVariant = $this->product->variants->first();
337 if ($firstVariant) {
338 $minPrice = $firstVariant->item_price;
339 $minPrice = apply_filters('fluent_cart/product/display_price', $minPrice, [
340 'product' => $this->product,
341 'variation' => $firstVariant,
342 ]);
343 $minPrice = (int)$minPrice;
344 if ($firstVariant->compare_price > $minPrice) {
345 $comparePrice = $firstVariant->compare_price;
346 }
347 }
348 }
349
350 $formattedMinPrice = Helper::toDecimal($minPrice);
351 $formattedMaxPrice = Helper::toDecimal($maxPrice);
352 $formattedComparePrice = Helper::toDecimal($comparePrice);
353
354 do_action('fluent_cart/product/group/before_price_block', [
355 'product' => $this->product,
356 'current_price' => $minPrice,
357 'scope' => 'product_card'
358 ]);
359 ?>
360 <div <?php echo $wrapper_attributes; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
361 class="fct-product-card-prices"
362 role="region"
363 aria-label="<?php echo esc_attr__('Product pricing', 'fluent-cart'); ?>">
364 <?php if ($comparePrice): ?>
365 <span class="fct-compare-price" aria-label="<?php echo esc_attr(sprintf(
366 /* translators: %s: product price */
367 __('Original price: %s', 'fluent-cart'), $formattedComparePrice)); ?>">
368 <del aria-hidden="true"><?php echo esc_html($formattedComparePrice); ?></del>
369 </span>
370 <?php endif; ?>
371
372 <?php if (!$comparePrice && $maxPrice && $maxPrice > $minPrice): ?>
373 <!-- Case 2: price range -->
374 <?php if ($priceFormat === 'range'): ?>
375 <span class="fct-item-price" aria-label="<?php echo esc_attr(sprintf(
376 /* translators: %1$s: min price, %2$s: max price */
377 __('Price range from %1$s to %2$s', 'fluent-cart'), $formattedMinPrice, $formattedMaxPrice)); ?>">
378 <span aria-hidden="true"><?php echo esc_html($formattedMinPrice); ?> - <?php echo esc_html($formattedMaxPrice); ?></span>
379 </span>
380 <?php else: ?>
381 <span class="fct-item-price" aria-label="<?php echo esc_attr(sprintf(
382 /* translators: %s: min price */
383 __('Starting from %s', 'fluent-cart'), $formattedMinPrice)); ?>">
384 <span aria-hidden="true"><?php
385 /* translators: %s is the minimum price */
386 printf(esc_html__('From %s', 'fluent-cart'), esc_html($formattedMinPrice));
387 ?></span>
388 </span>
389 <?php endif; ?>
390
391 <?php else: ?>
392 <!-- Case 3: Simple or single price -->
393 <span class="fct-item-price" aria-label="<?php echo esc_attr(sprintf(
394 /* translators: %s: product price */
395 __('Price: %s', 'fluent-cart'), $formattedMinPrice)); ?>">
396 <span aria-hidden="true"><?php echo esc_html($formattedMinPrice); ?></span>
397 </span>
398 <?php endif; ?>
399
400 <?php do_action('fluent_cart/product/after_price', [
401 'product' => $this->product,
402 'current_price' => $minPrice,
403 'scope' => 'product_card'
404 ]); ?>
405 </div>
406 <?php
407 do_action('fluent_cart/product/group/after_price_block', [
408 'product' => $this->product,
409 'current_price' => $minPrice,
410 'scope' => 'product_card'
411 ]);
412 }
413
414 public function showBuyButton($atts = '')
415 {
416 $isOutOfStock = ModuleSettings::isActive('stock_management') && !$this->product->isStock();
417
418 if ($isOutOfStock) {
419 $soldOutText = __('Not Available', 'fluent-cart');
420 ?>
421 <button type="button" class="fct-product-view-button out-of-stock" disabled aria-disabled="true"
422 aria-label="<?php echo esc_attr($soldOutText); ?>">
423 <span class="fct-button-text">
424 <?php echo esc_html($soldOutText); ?>
425 </span>
426 </button>
427 <?php
428 return;
429 }
430
431 $enableModalCheckout = Helper::isModalCheckoutEnabled();
432 $isSimple = $this->product->detail->variation_type === 'simple';
433 $firstVariant = null;
434 $buttonHref = $this->viewUrl;
435
436 if ($isSimple) {
437 $firstVariant = $this->product->variants->first();
438 if ($firstVariant) {
439 // return '';
440 }
441 }
442
443 $isInstantCheckout = false;
444 $hasSubscription = $this->product->has_subscription;
445 $buttonText = __('View Options', 'fluent-cart');
446 $ariaLabel = sprintf(
447 /* translators: %s: product title */
448 __('View options for %s', 'fluent-cart'), $this->product->post_title);
449
450 if ($isSimple) {
451 if ($hasSubscription) {
452 $buttonText = __('Buy Now', 'fluent-cart');
453 $ariaLabel = sprintf(
454 /* translators: %s: product title */
455 __('Buy %s now', 'fluent-cart'), $this->product->post_title);
456 $buttonHref = $firstVariant->getPurchaseUrl();
457 $isInstantCheckout = true;
458 } else {
459 $buttonText = __('Add To Cart', 'fluent-cart');
460 $ariaLabel = sprintf(
461 /* translators: %s: product title */
462 __('Add %s to cart', 'fluent-cart'), $this->product->post_title);
463 }
464 }
465
466 $buttonAttributes = [
467 'class' => 'fct-product-view-button fct-single-product-card-view-button',
468 'data-product-id' => $this->product->ID,
469 'data-fluent-cart-single-product-card-view-button' => '',
470 'aria-label' => $ariaLabel
471 ];
472
473 if ($firstVariant) {
474 $buttonAttributes = [
475 'data-cart-id' => $firstVariant->id,
476 'class' => 'fluent-cart-add-to-cart-button',
477 'data-variation-type' => $this->product->detail->variation_type,
478 'data-fluent-cart-add-to-cart-button' => '',
479 'data-is-custom' => false,
480 'aria-label' => $ariaLabel
481 ];
482 }
483 $customAttributes = $this->parseAttributes($atts);
484 if (!empty($customAttributes)) {
485 if (isset($customAttributes['class']) && isset($buttonAttributes['class'])) {
486 $buttonAttributes['class'] .= ' ' . $customAttributes['class'];
487 unset($customAttributes['class']);
488 }
489 $buttonAttributes = array_merge($buttonAttributes, $customAttributes);
490 }
491
492 $anchorAttributes = [
493 'href' => $buttonHref,
494 'class' => 'fct-product-view-button',
495 'aria-label' => $ariaLabel,
496 ];
497
498 if ($enableModalCheckout) {
499 $anchorAttributes['data-fct-instant-checkout-button'] = '';
500 $anchorAttributes['data-enable-modal-checkout'] = 'yes';
501 }
502
503 if ($isInstantCheckout) {
504 $parsedCustomAttributes = $this->parseAttributes($atts);
505 if (isset($parsedCustomAttributes['class']) && isset($anchorAttributes['class'])) {
506 $anchorAttributes['class'] .= ' ' . $parsedCustomAttributes['class'];
507 unset($parsedCustomAttributes['class']);
508 }
509 $anchorAttributes = array_merge($anchorAttributes, $parsedCustomAttributes);
510 }
511 ?>
512 <?php if ($isInstantCheckout): ?>
513 <a <?php $this->renderAttributes($anchorAttributes); ?>>
514 <span aria-hidden="true">
515 <?php echo esc_html($buttonText); ?>
516 </span>
517 </a>
518 <?php else: ?>
519 <button
520 type="button"
521 data-button-url="<?php echo esc_url($buttonHref); ?>"
522 <?php $this->renderAttributes($buttonAttributes); ?>>
523 <span class="fct-button-text">
524 <?php echo esc_html($buttonText); ?>
525 </span>
526 <span
527 class="fluent-cart-loader"
528 role="status"
529 aria-live="polite"
530 aria-label="<?php echo esc_attr__('Loading', 'fluent-cart'); ?>">
531 <svg aria-hidden="true"
532 viewBox="0 0 100 101"
533 fill="none"
534 xmlns="http://www.w3.org/2000/svg"
535 focusable="false">
536 <path
537 d="M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z"
538 fill="currentColor"></path>
539 <path
540 d="M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z"
541 fill="currentFill"></path>
542 </svg>
543 </span>
544 </button>
545 <?php endif; ?>
546 <?php
547 }
548
549 protected function renderAttributes($atts = [])
550 {
551 foreach ($atts as $attr => $value) {
552 if ($value !== '') {
553 echo esc_attr($attr) . '="' . esc_attr((string)$value) . '" ';
554 } else {
555 echo esc_attr($attr) . ' ';
556 }
557 }
558 }
559
560 private function parseAttributes($atts)
561 {
562 if (empty($atts)) {
563 return [];
564 }
565
566 $attributes = [];
567
568 // Match attribute="value" or attribute='value' or attribute=value
569 preg_match_all('/(\w+(?:-\w+)*)=(["\'])(.*?)\2|\b(\w+(?:-\w+)*)=(\S+)/', $atts, $matches, PREG_SET_ORDER);
570
571 foreach ($matches as $match) {
572 if (!empty($match[1])) {
573 // Quoted value
574 $attributes[$match[1]] = $match[3];
575 } elseif (!empty($match[4])) {
576 // Unquoted value
577 $attributes[$match[4]] = $match[5];
578 }
579 }
580
581 return $attributes;
582 }
583 }
584