/
delphin
/
CatRW
Обзор
Документация
Войти
/
delphin
/
CatRW
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
api/railways.php
321 строка
13 KB
delphin
start project
02 мар 2026, 09:14
Верифицирован
02 мар 2026, 09:14
4b0ee03
Код
Авторство
О чём код?
<?php // /api/railways.php - API для железнодорожных компаний (работа по ID) // Включаем логирование 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__ . '/RailwayCompanyService.php'; // Заголовки header('Content-Type: application/json; charset=utf-8'); // Функция для отправки JSON ответа function sendJson($data, $status = 200) { http_response_code($status); echo json_encode($data, JSON_UNESCAPED_UNICODE); exit; } // Логируем запрос error_log("=== RAILWAYS API REQUEST ==="); error_log("Request Method: " . $_SERVER['REQUEST_METHOD']); error_log("Request URI: " . $_SERVER['REQUEST_URI']); error_log("GET params: " . print_r($_GET, true)); try { $method = $_SERVER['REQUEST_METHOD']; $path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); // Убираем /api если есть в начале $path = preg_replace('|^/api|', '', $path); $parts = array_values(array_filter(explode('/', $path))); error_log("Path parts: " . print_r($parts, true)); // Инициализируем переменные $companyId = 0; $action = ''; // Определяем, что запрашиваем // Форматы: // - /api/railways - список всех компаний // - /api/railways/{id} - одна компания по ID // - /api/railways/{id}/logo - логотип компании // - /api/railways/{id}/models/count - количество моделей // Ищем ID компании в URL if (count($parts) >= 2 && $parts[0] === 'railways') { $firstPart = $parts[1]; // Если второй часть является числом - это ID if (is_numeric($firstPart)) { $companyId = (int)$firstPart; // Проверяем дополнительные действия if (count($parts) >= 3) { if ($parts[2] === 'logo') { $action = 'logo'; } elseif ($parts[2] === 'models' && count($parts) >= 4 && $parts[3] === 'count') { $action = 'models_count'; } } } } error_log("Company ID: '$companyId', Action: '$action'"); // ===== ОСОБЫЕ ENDPOINTS ===== // 1. Управление логотипом по ID if ($action === 'logo' && $companyId > 0) { switch ($method) { case 'DELETE': // Удаление логотипа try { $deleted = RailwayCompanyService::deleteLogo($companyId); if ($deleted) { sendJson(['success' => true, 'message' => 'Логотип удален']); } else { sendJson(['success' => false, 'error' => 'Логотип не найден'], 404); } } catch (Exception $e) { sendJson(['success' => false, 'error' => $e->getMessage()], 400); } exit; case 'POST': // Загрузка логотипа if (empty($_FILES['logo'])) { sendJson(['success' => false, 'error' => 'Файл не загружен'], 400); } try { $logoUrl = RailwayCompanyService::uploadLogo($companyId, $_FILES['logo']); sendJson(['success' => true, 'logo_url' => $logoUrl]); } catch (Exception $e) { sendJson(['success' => false, 'error' => $e->getMessage()], 400); } exit; case 'GET': // Получение логотипа $logoUrl = RailwayCompanyService::getLogoUrl($companyId); if ($logoUrl) { sendJson(['success' => true, 'logo_url' => $logoUrl]); } else { sendJson(['success' => false, 'error' => 'Логотип не найден'], 404); } exit; } } // 2. Получение количества моделей по ID if ($action === 'models_count' && $companyId > 0 && $method === 'GET') { try { $count = RailwayCompanyService::getModelsCount($companyId); header('Content-Type: text/plain'); echo $count; exit; } catch (Exception $e) { error_log("models_count error for railway id '$companyId': " . $e->getMessage()); header('Content-Type: text/plain'); echo "-1"; exit; } } // ===== ОБРАБОТКА ОСНОВНЫХ МЕТОДОВ ===== switch ($method) { case 'GET': error_log("Processing GET request"); // 1. Получение количества моделей через параметр GET if (isset($_GET['action']) && $_GET['action'] === 'models_count') { $railwayId = (int)($_GET['railway_id'] ?? 0); if ($railwayId <= 0) { sendJson(['success' => false, 'error' => 'Railway ID required'], 400); } try { $count = RailwayCompanyService::getModelsCount($railwayId); sendJson(['success' => true, 'count' => $count]); } catch (Exception $e) { error_log("models_count error for railway ID '$railwayId': " . $e->getMessage()); sendJson(['success' => false, 'error' => 'Internal server error'], 500); } exit; } // 2. Получение статистики if (isset($_GET['action']) && $_GET['action'] === 'stats') { $stats = RailwayCompanyService::getStats(); sendJson(['success' => true, 'data' => $stats]); exit; } // 3. Получение одной компании по ID if ($companyId > 0) { error_log("Getting company with ID: " . $companyId); $company = RailwayCompanyService::getById($companyId); if ($company) { // Добавляем URL логотипа $company['logo_url'] = RailwayCompanyService::getLogoUrl($companyId); sendJson(['success' => true, 'data' => $company]); } else { sendJson(['success' => false, 'error' => 'Компания не найдена'], 404); } exit; } if (isset($_GET['action']) && $_GET['action'] === 'stats') { $stats = RailwayCompanyService::getStats(); sendJson(['success' => true, 'data' => $stats]); exit; } // 4. Получение всех компаний (с фильтрами) $filters = []; if (!empty($_GET['search'])) { $filters['search'] = $_GET['search']; error_log("Search filter: " . $_GET['search']); } if (!empty($_GET['country_code'])) { $filters['country_code'] = $_GET['country_code']; error_log("Country filter: " . $_GET['country_code']); } $companies = RailwayCompanyService::getAll($filters); // Добавляем URL логотипа для каждой компании foreach ($companies as &$company) { $company['logo_url'] = RailwayCompanyService::getLogoUrl($company['id']); } $stats = RailwayCompanyService::getStats(); sendJson([ 'success' => true, 'data' => $companies, 'meta' => [ 'total' => count($companies), 'stats' => $stats ] ]); break; case 'POST': error_log("Processing POST request"); // Проверяем, это загрузка логотипа или добавление компании if (!empty($_FILES['logo'])) { // Загрузка логотипа должна быть обработана выше sendJson(['success' => false, 'error' => 'Неверный запрос'], 400); } else { // Добавление компании $input = json_decode(file_get_contents('php://input'), true); if (!$input && !empty($_POST)) { $input = $_POST; } error_log("Input data: " . print_r($input, true)); if (empty($input['code'])) { sendJson(['success' => false, 'error' => 'Код обязателен'], 400); } if (empty($input['name'])) { sendJson(['success' => false, 'error' => 'Название обязательно'], 400); } try { $id = RailwayCompanyService::add($input); sendJson([ 'success' => true, 'message' => 'Железнодорожная компания добавлена', 'id' => $id ]); } catch (Exception $e) { error_log("Add company error: " . $e->getMessage()); sendJson(['success' => false, 'error' => $e->getMessage()], 400); } } break; case 'PUT': error_log("Processing PUT request for ID: " . $companyId); // Обновить компанию по ID if ($companyId <= 0) { sendJson(['success' => false, 'error' => 'ID обязателен'], 400); } $input = json_decode(file_get_contents('php://input'), true); if (!$input) { sendJson(['success' => false, 'error' => 'Нет данных для обновления'], 400); } error_log("Update data: " . print_r($input, true)); try { $result = RailwayCompanyService::updateById($companyId, $input); sendJson(['success' => true, 'message' => 'Компания обновлена', 'affected_rows' => $result]); } catch (Exception $e) { error_log("Update company error: " . $e->getMessage()); sendJson(['success' => false, 'error' => $e->getMessage()], 400); } break; case 'DELETE': error_log("Processing DELETE request for ID: " . $companyId); // Удалить компанию по ID if ($companyId <= 0) { sendJson(['success' => false, 'error' => 'ID обязателен'], 400); } // Проверяем, это удаление логотипа или компании $deleteLogo = isset($_GET['logo']) && $_GET['logo'] == '1'; if ($deleteLogo) { // Удаление логотипа должно быть обработано выше sendJson(['success' => false, 'error' => 'Неверный запрос'], 400); } else { // Удаление компании try { $result = RailwayCompanyService::deleteById($companyId); sendJson(['success' => true, 'message' => $result['message']]); } catch (Exception $e) { error_log("Delete company error: " . $e->getMessage()); sendJson(['success' => false, 'error' => $e->getMessage()], 400); } } break; default: sendJson(['success' => false, 'error' => 'Метод не поддерживается'], 405); } } catch (Exception $e) { error_log("=== RAILWAYS API ERROR ==="); error_log("Error: " . $e->getMessage()); error_log("File: " . $e->getFile()); error_log("Line: " . $e->getLine()); error_log("Trace: " . $e->getTraceAsString()); sendJson(['success' => false, 'error' => 'Внутренняя ошибка сервера'], 500); } error_log("=== RAILWAYS API COMPLETE ==="); ?>