1
0
Files
breadcrumb-the-shire/lib/Http/Request.php

96 lines
2.9 KiB
PHP
Raw Normal View History

2026-02-04 23:31:53 +01:00
<?php
namespace MintyPHP\Http;
use MintyPHP\Router;
use MintyPHP\I18n;
class Request
{
public static function stripBasePath(string $path): string
2026-02-04 23:31:53 +01:00
{
$base = trim(parse_url(Router::getBaseUrl(), PHP_URL_PATH) ?: '/', '/');
2026-02-04 23:31:53 +01:00
$path = ltrim($path, '/');
if ($base !== '' && strpos($path, $base . '/') === 0) {
return substr($path, strlen($base) + 1);
}
if ($base !== '' && $path === $base) {
return '';
2026-02-04 23:31:53 +01:00
}
return $path;
}
public static function path(): string
{
$uri = $_SERVER['REQUEST_URI'] ?? '';
$path = parse_url($uri, PHP_URL_PATH) ?: '';
return self::stripBasePath($path);
}
2026-02-04 23:31:53 +01:00
public static function safeReturnTarget(string $returnParam = ''): string
{
if ($returnParam !== '') {
$parts = parse_url($returnParam);
if (($parts['scheme'] ?? '') === '' && ($parts['host'] ?? '') === '') {
$path = self::stripBasePath($parts['path'] ?? '');
2026-02-04 23:31:53 +01:00
$query = isset($parts['query']) ? '?' . $parts['query'] : '';
return $path . $query;
}
}
$referer = $_SERVER['HTTP_REFERER'] ?? '';
if ($referer !== '') {
$parts = parse_url($referer);
$host = $parts['host'] ?? '';
$currentHost = $_SERVER['HTTP_HOST'] ?? '';
if ($host === '' || $host === $currentHost) {
$path = self::stripBasePath($parts['path'] ?? '');
2026-02-04 23:31:53 +01:00
$query = isset($parts['query']) ? '?' . $parts['query'] : '';
return $path . $query;
}
}
return '';
}
public static function pathWithQuery(): string
{
$uri = $_SERVER['REQUEST_URI'] ?? '';
$path = self::path();
$query = parse_url($uri, PHP_URL_QUERY);
return $path . ($query ? '?' . $query : '');
}
public static function stripLocale(string $path, ?array $locales = null): string
{
$locales = $locales ?? (defined('APP_LOCALES') ? APP_LOCALES : [I18n::$defaultLocale]);
$path = ltrim($path, '/');
if ($path === '') {
return '';
}
$parts = explode('/', $path);
while ($parts && $parts[0] !== '' && in_array($parts[0], $locales, true)) {
array_shift($parts);
}
return implode('/', $parts);
}
public static function withLocale(string $path = '', ?string $locale = null): string
{
$locale = $locale ?? (I18n::$locale ?? I18n::$defaultLocale);
$path = ltrim($path, '/');
return ($locale !== '' ? $locale . '/' : '') . $path;
}
public static function wantsJson(): bool
{
$accept = $_SERVER['HTTP_ACCEPT'] ?? '';
$requestedWith = $_SERVER['HTTP_X_REQUESTED_WITH'] ?? '';
return stripos($accept, 'application/json') !== false || $requestedWith !== '';
}
}