/
delphin
/
CatRW
Обзор
Документация
Войти
/
delphin
/
CatRW
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
api/model_subtypes.php
158 строк
6 KB
delphin
start project
02 мар 2026, 09:14
Верифицирован
02 мар 2026, 09:14
4b0ee03
Код
Авторство
О чём код?
<?php // /api/model_subtypes.php - API ДЛЯ ПОДТИПОВ МОДЕЛЕЙ // Включаем логирование ini_set('display_errors', 0); ini_set('log_errors', 1); error_reporting(E_ALL); // Подключаем файлы require_once __DIR__ . '/../config.php'; require_once __DIR__ . '/Database.php'; require_once __DIR__ . '/ModelSubtypeService.php'; // Заголовки header('Content-Type: application/json; charset=utf-8'); // Логируем запрос error_log("=== MODEL SUBTYPES API CALL ==="); error_log("Request Method: " . $_SERVER['REQUEST_METHOD']); error_log("Request URI: " . $_SERVER['REQUEST_URI']); // Функция ответа function sendJson($data, $status = 200) { http_response_code($status); echo json_encode($data, JSON_UNESCAPED_UNICODE); exit; } // Основной обработчик try { $method = $_SERVER['REQUEST_METHOD']; // Получаем путь и code $path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); $parts = explode('/', trim($path, '/')); // Находим code в URL (например: /api/model_subtypes/steam) $code = ''; foreach ($parts as $index => $part) { if (isset($parts[$index-1]) && $parts[$index-1] === 'model_subtypes') { $code = $part; break; } } // Если code в GET параметрах if (!$code && isset($_GET['code'])) { $code = $_GET['code']; } // Получаем параметр типа $typeCode = $_GET['type_code'] ?? ''; error_log("Parsed Code: " . $code); error_log("Type Code: " . $typeCode); // Обработка методов switch ($method) { case 'GET': error_log("Processing GET request"); if ($code) { // Получить один подтип error_log("Getting model subtype code: " . $code); $subtype = ModelSubtypeService::get($code); if ($subtype) { // Получаем статистику $stats = ModelSubtypeService::getStats($code); $subtype['stats'] = $stats; sendJson(['success' => true, 'data' => $subtype]); } else { sendJson(['success' => false, 'error' => 'Подтип модели не найден'], 404); } } elseif (isset($_GET['q'])) { // Поиск $query = $_GET['q'] ?? ''; error_log("Search query: " . $query); $subtypes = ModelSubtypeService::search($query, $typeCode); sendJson(['success' => true, 'data' => $subtypes, 'total' => count($subtypes)]); } elseif ($typeCode) { // Получить все подтипы для типа $subtypes = ModelSubtypeService::getAll($typeCode); sendJson(['success' => true, 'data' => $subtypes, 'total' => count($subtypes)]); } else { // Список всех $subtypes = ModelSubtypeService::getAll(); sendJson(['success' => true, 'data' => $subtypes, 'total' => count($subtypes)]); } break; case 'POST': error_log("Processing POST request"); // Добавление подтипа $input = json_decode(file_get_contents('php://input'), true); if (!$input && !empty($_POST)) { $input = $_POST; } if (empty($input['code'])) { sendJson(['success' => false, 'error' => 'Код обязателен'], 400); } if (empty($input['type_code'])) { sendJson(['success' => false, 'error' => 'Код типа обязателен'], 400); } $newId = ModelSubtypeService::add($input); sendJson(['success' => true, 'id' => $newId, 'message' => 'Подтип модели добавлен']); break; case 'PUT': error_log("Processing PUT request for code: " . $code); if (!$code) { sendJson(['success' => false, 'error' => 'Код обязателен'], 400); } $input = json_decode(file_get_contents('php://input'), true); if (!$input) { sendJson(['success' => false, 'error' => 'Нет данных'], 400); } ModelSubtypeService::update($code, $input); sendJson(['success' => true, 'message' => 'Подтип модели обновлён']); break; case 'DELETE': error_log("Processing DELETE request for code: " . $code); if (!$code) { sendJson(['success' => false, 'error' => 'Код обязателен'], 400); } $result = ModelSubtypeService::delete($code); sendJson(['success' => true, 'message' => $result['message']]); break; default: sendJson(['success' => false, 'error' => 'Метод не поддерживается'], 405); } } catch (Exception $e) { // Логируем полную ошибку error_log("=== MODEL SUBTYPES API ERROR ==="); error_log("Error message: " . $e->getMessage()); error_log("File: " . $e->getFile()); error_log("Line: " . $e->getLine()); error_log("Trace: " . $e->getTraceAsString()); // Отправляем общую ошибку клиенту sendJson(['success' => false, 'error' => $e->getMessage()], 500); } error_log("=== MODEL SUBTYPES API COMPLETE ===");