Files
preland/bin/ensure-cons-config.php
2026-10-24 04:35:44 +03:00

37 lines
2.3 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
/** preland#17: миграция только utm.chb → utm.cons; остальные значения владельца сохраняются. */
declare(strict_types=1);
if ($argc !== 2) {
fwrite(STDERR, "Использование: php bin/ensure-cons-config.php /path/to/config.json\n");
exit(2);
}
try {
$path = $argv[1];
$raw = @file_get_contents($path);
if ($raw === false) throw new RuntimeException('Не удалось прочитать config.json.');
// Object decode сохраняет типы соседних {} и объектов с числовыми ключами.
$config = json_decode($raw, false, 512, JSON_THROW_ON_ERROR);
if (!$config instanceof stdClass || !($config->utm ?? null) instanceof stdClass) throw new RuntimeException('В config.json отсутствует объект utm.');
$hasCons = property_exists($config->utm, 'cons');
$cons = $hasCons ? $config->utm->cons : (object) ['weights' => (object) ['1' => 100, '2' => 0], 'default' => '2'];
if (!$cons instanceof stdClass || !(is_array($cons->weights ?? null) || ($cons->weights ?? null) instanceof stdClass)
|| !(is_string($cons->default ?? null) || is_int($cons->default ?? null))
|| !preg_match('/^[1-9][0-9]*$/D', (string) $cons->default)
|| (float) $cons->default > 2147483647) {
throw new RuntimeException('Существующий utm.cons некорректен; автоматическая перезапись запрещена.');
}
if (!property_exists($config->utm, 'chb') && $hasCons) {
fwrite(STDOUT, "cons уже настроен: config не изменён.\n");
exit(0);
}
unset($config->utm->chb);
$config->utm->cons = $cons;
$encoded = json_encode($config, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR) . "\n";
if (file_put_contents($path, $encoded, LOCK_EX) === false) throw new RuntimeException('Не удалось записать config.json.');
fwrite(STDOUT, "Мигрированы только utm.chb/cons; остальные поля и существующие настройки cons сохранены.\n");
exit(10);
} catch (Throwable $error) {
fwrite(STDERR, $error->getMessage() . "\n");
exit(2);
}