| 1 |
<?php |
| 2 |
|
| 3 |
/** |
| 4 |
* Cache data. |
| 5 |
*/ |
| 6 |
|
| 7 |
namespace Extendify\Shared\DataProvider; |
| 8 |
|
| 9 |
defined('ABSPATH') || die('No direct access.'); |
| 10 |
|
| 11 |
use Extendify\Constants; |
| 12 |
use Extendify\PartnerData; |
| 13 |
use Extendify\Shared\Services\Sanitizer; |
| 14 |
|
| 15 |
/** |
| 16 |
* The product data class. |
| 17 |
*/ |
| 18 |
|
| 19 |
class ProductsData |
| 20 |
{ |
| 21 |
/** |
| 22 |
* Gets the recommended products based on partner and current language. |
| 23 |
* |
| 24 |
* @return array |
| 25 |
*/ |
| 26 |
public static function get() |
| 27 |
{ |
| 28 |
// Check cache before fetching. |
| 29 |
$products = get_transient('extendify_recommendations_products'); |
| 30 |
|
| 31 |
// Return products from cache if not empty. |
| 32 |
if ($products !== false) { |
| 33 |
return $products; |
| 34 |
} |
| 35 |
|
| 36 |
// Otherwise fetch products. |
| 37 |
$response = \wp_remote_get( |
| 38 |
\add_query_arg( |
| 39 |
[ |
| 40 |
'disabled_products' => PartnerData::setting('productRecommendations')['disabledProducts'], |
| 41 |
'custom_products' => PartnerData::setting('productRecommendations')['customProducts'], |
| 42 |
'wp_language' => \get_locale(), |
| 43 |
], |
| 44 |
Constants::DASHBOARD_HOST . '/api/recommendations/products' |
| 45 |
), |
| 46 |
[ |
| 47 |
'headers' => ['Accept' => 'application/json'], |
| 48 |
] |
| 49 |
); |
| 50 |
|
| 51 |
if (\is_wp_error($response)) { |
| 52 |
return []; |
| 53 |
} |
| 54 |
|
| 55 |
$result = json_decode(\wp_remote_retrieve_body($response), true); |
| 56 |
|
| 57 |
if (!isset($result['success']) || !$result['success']) { |
| 58 |
return []; |
| 59 |
} |
| 60 |
|
| 61 |
$products = $result['data']; |
| 62 |
$sanitizedProducts = []; |
| 63 |
|
| 64 |
foreach ($products as $product) { |
| 65 |
// We are escaping the original price tag separately because we are using HTML tags |
| 66 |
// inside it and they are removed when going through the `sanitizeArray` function. |
| 67 |
$originalPriceTag = $product['priceTag'] ?? ''; |
| 68 |
$sanitizedPriceTag = Sanitizer::sanitizeTextWithFormattingTags($originalPriceTag); |
| 69 |
$sanitizedProduct = Sanitizer::sanitizeArray($product); |
| 70 |
$sanitizedProduct['priceTag'] = $sanitizedPriceTag; |
| 71 |
$sanitizedProducts[] = $sanitizedProduct; |
| 72 |
} |
| 73 |
|
| 74 |
// Cache products. |
| 75 |
set_transient('extendify_recommendations_products', $sanitizedProducts, DAY_IN_SECONDS); |
| 76 |
|
| 77 |
return $sanitizedProducts; |
| 78 |
} |
| 79 |
} |
| 80 |
|