Skip to content

Commit

Permalink
Normalizing header key consistency
Browse files Browse the repository at this point in the history
  • Loading branch information
Vahram1995 committed Oct 30, 2024
1 parent dba82fe commit 0834574
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 6 deletions.
2 changes: 1 addition & 1 deletion src/Helpers/server.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ function getallheaders(): array

foreach ($data as $key => $value) {
if (substr($key, 0, 5) == 'HTTP_') {
$headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($key, 5)))))] = $value;
$headers[str_replace(' ', '-', strtolower(str_replace('_', ' ', substr($key, 5))))] = $value;
}
}

Expand Down
29 changes: 24 additions & 5 deletions src/Http/Request/Header.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,12 @@ trait Header
* @param string $key
* @return bool
*/
public static function hasHeader(string $key): bool
{
return isset(self::$__headers[strtolower($key)]);
}
public static function hasHeader(string $key): bool
{
list($keyWithHyphens, $keyWithUnderscores) = self::normalizeHeaderKey($key);

return isset(self::$__headers[$keyWithHyphens]) || isset(self::$__headers[$keyWithUnderscores]);
}

/**
* Gets the request header by given key
Expand All @@ -44,7 +46,14 @@ public static function hasHeader(string $key): bool
*/
public static function getHeader(string $key): ?string
{
return self::hasHeader($key) ? self::$__headers[strtolower($key)] : null;
list($keyWithHyphens, $keyWithUnderscores) = self::normalizeHeaderKey($key);

if (array_key_exists($keyWithHyphens, self::$__headers)) {
return self::$__headers[$keyWithHyphens];
} elseif (array_key_exists($keyWithUnderscores, self::$__headers)) {
return self::$__headers[$keyWithUnderscores];
}
return null;
}

/**
Expand Down Expand Up @@ -77,4 +86,14 @@ public static function deleteHeader(string $key)
}
}

/**
* @param string $key
* @return array
*/
private static function normalizeHeaderKey(string $key): array
{
$keyWithHyphens = str_replace('_', '-', strtolower($key));
$keyWithUnderscores = str_replace('-', '_', $key);
return [$keyWithHyphens, $keyWithUnderscores];
}
}

0 comments on commit 0834574

Please sign in to comment.