| 1 |
<?php |
| 2 |
|
| 3 |
namespace ReviewX\Shortcodes\Products; |
| 4 |
|
| 5 |
use ReviewX\Utilities\Auth\Client; |
| 6 |
use ReviewX\Utilities\Helper; |
| 7 |
use ReviewX\WPDrill\Contracts\ShortcodeContract; |
| 8 |
use ReviewX\WPDrill\Facades\View; |
| 9 |
class ReviewStatshortcode implements ShortcodeContract |
| 10 |
{ |
| 11 |
public function render(array $attrs, ?string $content = null) : string |
| 12 |
{ |
| 13 |
// Set default attributes to include both product_id and post_id. |
| 14 |
$attrs = shortcode_atts(['title' => null, 'product_id' => null, 'post_id' => null], $attrs); |
| 15 |
// Check if both product_id and post_id are provided. |
| 16 |
if (!Client::getSync()) { |
| 17 |
return '<div class="warning">Error: Please complete the synchronization process of ReviewX.</div>'; |
| 18 |
} |
| 19 |
// If both product_id and post_id are provided, return an error. |
| 20 |
if (!empty($attrs['product_id']) && !empty($attrs['post_id'])) { |
| 21 |
return '<div class="warning">Error: Please use only one of "product_id" or "post_id" in the shortcode.</div>'; |
| 22 |
} |
| 23 |
// Determine whether this is for a product or a post. |
| 24 |
$isProduct = !empty($attrs['product_id']); |
| 25 |
$id = $isProduct ? (int) $attrs['product_id'] : (int) $attrs['post_id']; |
| 26 |
if (!$id && is_singular()) { |
| 27 |
$id = (int) get_the_ID(); |
| 28 |
$isProduct = 'product' === \get_post_type($id); |
| 29 |
} |
| 30 |
// Retrieve data related to review stats. |
| 31 |
$data = $this->getReviewStatsData($id, $isProduct); |
| 32 |
// Title handling |
| 33 |
if ($attrs['title'] === 'false') { |
| 34 |
$title = 'false'; |
| 35 |
} elseif ($attrs['title'] === 'true' || empty($attrs['title'])) { |
| 36 |
$title = $data['postTitle']; |
| 37 |
} else { |
| 38 |
$title = \esc_html($attrs['title']); |
| 39 |
} |
| 40 |
// If no title is provided, use the post title from the data. |
| 41 |
return View::render('storefront/shortcode/reviewStats', ['title' => $title, 'postType' => !empty($data['postType']) ? $data['postType'] : '', 'data' => \json_encode($data)]); |
| 42 |
} |
| 43 |
/** |
| 44 |
* Retrieve review stats data based on an ID and its type (product or post). |
| 45 |
* |
| 46 |
* @param int $id |
| 47 |
* @param bool $isProduct |
| 48 |
* |
| 49 |
* @return array |
| 50 |
*/ |
| 51 |
public function getReviewStatsData(int $id, bool $isProduct) : array |
| 52 |
{ |
| 53 |
// Retrieve the post object. |
| 54 |
$post = \get_post($id); |
| 55 |
$defaultData = ['product' => ['id' => $id], 'postTitle' => $post ? $post->post_title : \false, 'postType' => $post ? $post->post_type : '', 'domain' => ['baseDomain' => Helper::domainSupport(), 'baseRestUrl' => Helper::getRestAPIurl()]]; |
| 56 |
return $defaultData; |
| 57 |
} |
| 58 |
} |
| 59 |
|