| 1 |
<?php |
| 2 |
|
| 3 |
namespace FluentCart\App\Helpers; |
| 4 |
|
| 5 |
use FluentCart\App\App; |
| 6 |
use FluentCart\App\Models\OrderOperation; |
| 7 |
use FluentCart\Framework\Support\Arr; |
| 8 |
|
| 9 |
class UtmHelper |
| 10 |
{ |
| 11 |
|
| 12 |
public static function allowedUtmParameterKey(): array |
| 13 |
{ |
| 14 |
$keys = [ |
| 15 |
'utm_campaign', |
| 16 |
'utm_content', |
| 17 |
'utm_term', |
| 18 |
'utm_source', |
| 19 |
'utm_medium', |
| 20 |
'utm_id', |
| 21 |
'refer_url', |
| 22 |
'fbclid', |
| 23 |
'gclid' |
| 24 |
]; |
| 25 |
|
| 26 |
return apply_filters('fluent_cart/utm/allowed_keys', $keys, []); |
| 27 |
} |
| 28 |
|
| 29 |
public static function addUtmToOrder($orderId, $data = []) |
| 30 |
{ |
| 31 |
$directValueKeys = [ |
| 32 |
'utm_campaign', |
| 33 |
'utm_content', |
| 34 |
'utm_term', |
| 35 |
'utm_source', |
| 36 |
'utm_medium', |
| 37 |
'utm_id', |
| 38 |
'refer_url', |
| 39 |
]; |
| 40 |
|
| 41 |
$directValues = Arr::only($data, $directValueKeys); |
| 42 |
$metaValues = Arr::except($data, $directValueKeys); |
| 43 |
|
| 44 |
foreach ($directValues as $key => $value) { |
| 45 |
if ($key == 'refer_url') { |
| 46 |
$directValues[$key] = sanitize_url($value); |
| 47 |
} else { |
| 48 |
$directValues[$key] = sanitize_text_field($value); |
| 49 |
} |
| 50 |
} |
| 51 |
|
| 52 |
$allowedKeys = self::allowedUtmParameterKey(); |
| 53 |
$allowedMetaValues = []; |
| 54 |
foreach ($metaValues as $key => $value) { |
| 55 |
if (!in_array($key, $allowedKeys)) { |
| 56 |
continue; |
| 57 |
} |
| 58 |
$allowedMetaValues[$key] = sanitize_text_field($value); |
| 59 |
} |
| 60 |
|
| 61 |
$directValues['meta'] = $allowedMetaValues; |
| 62 |
|
| 63 |
$hasValues = array_filter($directValues) || array_filter($allowedMetaValues); |
| 64 |
|
| 65 |
|
| 66 |
$oldOperation = OrderOperation::query()->where('order_id', $orderId)->first(); |
| 67 |
|
| 68 |
if (empty($oldOperation)) { |
| 69 |
OrderOperation::query()->create( |
| 70 |
array_merge($directValues, ['order_id' => $orderId]) |
| 71 |
); |
| 72 |
} else { |
| 73 |
$directValues['meta'] = Arr::mergeMissingValues($directValues['meta'], $oldOperation->meta); |
| 74 |
Arr::mergeMissingValues($directValues, Arr::except($oldOperation->toArray(), 'meta')); |
| 75 |
$directValues = array_merge($directValues); |
| 76 |
$oldOperation->update($directValues); |
| 77 |
} |
| 78 |
} |
| 79 |
|
| 80 |
public static function getUtmDataOfRequest(): array |
| 81 |
{ |
| 82 |
$requestData = App::request()->all(); |
| 83 |
$requestUtmData = Arr::get($requestData, 'utm_data', []); |
| 84 |
$sanitizedUtmData = []; |
| 85 |
// Sanitize UTM data |
| 86 |
foreach ($requestUtmData as $utmKey => $utmValue) { |
| 87 |
$sanitizedKey = sanitize_text_field($utmKey); |
| 88 |
$sanitizedUtmData[$sanitizedKey] = sanitize_text_field($utmValue); |
| 89 |
} |
| 90 |
|
| 91 |
return $sanitizedUtmData; |
| 92 |
} |
| 93 |
|
| 94 |
} |