index.php

2.51 KB
04/08/2025 05:50
PHP
<?php
/**
 * API Entry Point
 * Main entry point for all API requests
 */

// Set error reporting based on environment
if (isset($_ENV['APP_ENV']) && $_ENV['APP_ENV'] === 'production') {
    error_reporting(0);
    ini_set('display_errors', 0);
} else {
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
}

// Set timezone
date_default_timezone_set($_ENV['TIMEZONE'] ?? 'Asia/Bangkok');

// Load environment variables if .env file exists
$envFile = __DIR__.'/../.env';
if (file_exists($envFile)) {
    $lines = file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    foreach ($lines as $line) {
        if (strpos($line, '=') !== false && strpos($line, '#') !== 0) {
            list($key, $value) = explode('=', $line, 2);
            $_ENV[trim($key)] = trim($value, '"\'');
        }
    }
}

// Include autoloader
require_once __DIR__.'/../src/Core/Autoloader.php';

// Register autoloader
$autoloader = new \App\Core\Autoloader();
$autoloader->addNamespace('App', __DIR__.'/../src');
$autoloader->register();

// Load configuration
$storeConfigFile = __DIR__.'/../config/app-store.php';
$defaultConfigFile = __DIR__.'/../config/app.php';

if (file_exists($storeConfigFile)) {
    $config = require $storeConfigFile;
} elseif (file_exists($defaultConfigFile)) {
    $config = require $defaultConfigFile;
} else {
    die('Configuration file not found');
}

// Set up error handling
// Note: Logger and ErrorHandler classes not implemented yet
// Using basic PHP error handling for now

// Initialize router
$router = new \App\Core\Router($config['api_base_path']);

// Add global middleware
$router->addGlobalMiddleware(\App\Middleware\SecurityMiddleware::class);
$router->addGlobalMiddleware(\App\Middleware\CorsMiddleware::class);

// Load routes
$routeLoader = require __DIR__.'/../config/routes.php';
$routeLoader($router);

// Handle the request
try {
    $router->dispatch();
} catch (\Exception $e) {
    // Fallback error handling
    http_response_code(500);
    header('Content-Type: application/json');

    if ($config['debug']) {
        echo json_encode([
            'error' => 'Internal Server Error',
            'message' => $e->getMessage(),
            'file' => $e->getFile(),
            'line' => $e->getLine()
        ], JSON_PRETTY_PRINT);
    } else {
        echo json_encode([
            'error' => 'Internal Server Error',
            'message' => 'An unexpected error occurred'
        ]);
    }

    // Log the error
    error_log("Fatal Error: ".$e->getMessage()." in ".$e->getFile().":".$e->getLine());
}