feat: Use yaMetrika number in settings

This commit is contained in:
2025-12-01 19:44:14 +03:00
parent c670e38392
commit cedc49f0d5
5 changed files with 54 additions and 46 deletions

View File

@@ -95,37 +95,22 @@ class ControllerExtensionTgshopHandle extends Controller
->bootAndHandleRequest();
}
function extractPureJs($input)
{
// Убираем <noscript>...</noscript>
$input = preg_replace('#<noscript>.*?</noscript>#is', '', $input);
// Убираем <!-- комментарии -->
$input = preg_replace('#<!--.*?-->#s', '', $input);
// Извлекаем содержимое <script>...</script>
if (preg_match('#<script[^>]*>(.*?)</script>#is', $input, $matches)) {
return trim($matches[1]);
}
return '';
}
private function safeJsonDecode(?string $input = null, $default = null)
{
try {
return json_decode($input, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
return $default;
}
}
/** @noinspection PhpUnused */
public function ya_metrika(): void
{
$json = $this->model_setting_setting->getSetting('module_telecart');
if (isset($json['module_telecart_settings'])) {
$raw = Arr::get($json, 'module_telecart_settings.metrics.yandex_metrika_counter');
$raw = $this->extractPureJs($raw);
$yaCounterId = Arr::get($json, 'module_telecart_settings.metrics.yandex_metrika_counter');
$raw = <<<JS
(function(m,e,t,r,i,k,a){
m[i]=m[i]||function(){(m[i].a=m[i].a||[]).push(arguments)};
m[i].l=1*new Date();
for (var j = 0; j < document.scripts.length; j++) {if (document.scripts[j].src === r) { return; }}
k=e.createElement(t),a=e.getElementsByTagName(t)[0],k.async=1,k.src=r,a.parentNode.insertBefore(k,a)
})(window, document,'script','https://mc.yandex.ru/metrika/tag.js?id={$yaCounterId}', 'ym');
ym({$yaCounterId}, 'init', {ssr: true, defer: true, ecommerce:"dataLayer", accurateTrackBounce:true, trackLinks:true});
JS;
http_response_code(200);
header('Content-Type: application/javascript');