67 lines
1.6 KiB
PHP
67 lines
1.6 KiB
PHP
<?php
|
|
|
|
namespace lib\Http;
|
|
|
|
class Url extends Http
|
|
{
|
|
protected string $baseUrl;
|
|
protected string $uri;
|
|
|
|
public function __construct()
|
|
{
|
|
parent::__construct();
|
|
$this->baseUrl = $this->detectBaseUrl();
|
|
$this->uri = $this->detectUri();
|
|
}
|
|
|
|
// 현재 전체 URL 반환
|
|
public function current(): string
|
|
{
|
|
return $this->baseUrl . '/' . ltrim($this->uri, '/');
|
|
}
|
|
|
|
// base URL만 반환
|
|
public function baseURL(): string
|
|
{
|
|
return $this->baseUrl;
|
|
}
|
|
|
|
// 세그먼트 배열 반환
|
|
public function segments(): array
|
|
{
|
|
return explode('/', trim($this->uri, '/'));
|
|
}
|
|
|
|
// N번째 세그먼트 반환 (1부터 시작)
|
|
public function segment(int $n): ?string
|
|
{
|
|
$segments = $this->segments();
|
|
return $segments[$n - 1] ?? null;
|
|
}
|
|
|
|
// 특정 경로에 대한 URL 생성
|
|
public function to(string $path): string
|
|
{
|
|
return rtrim($this->baseUrl, '/') . '/' . ltrim($path, '/');
|
|
}
|
|
|
|
// URI 추출 (도메인 제외)
|
|
protected function detectUri(): string
|
|
{
|
|
$uri = $_SERVER['REQUEST_URI'] ?? '/';
|
|
$scriptName = dirname($_SERVER['SCRIPT_NAME'] ?? '');
|
|
$uri = str_replace($scriptName, '', $uri);
|
|
$uri = strtok($uri, '?'); // 쿼리 스트링 제거
|
|
return $uri;
|
|
}
|
|
|
|
// base URL 추출
|
|
protected function detectBaseUrl(): string
|
|
{
|
|
$scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
|
|
$host = $_SERVER['HTTP_HOST'] ?? 'localhost';
|
|
$scriptDir = rtrim(dirname($_SERVER['SCRIPT_NAME'] ?? ''), '/');
|
|
return $scheme . '://' . $host . $scriptDir;
|
|
}
|
|
}
|