Skip to content

Commit

Permalink
Merge pull request #40 from nox7/2.0.8
Browse files Browse the repository at this point in the history
2.0.8
  • Loading branch information
nox7 authored Sep 27, 2022
2 parents 32b410a + 0b5efff commit 0c875a9
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/Http/Request.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,16 @@ public static function setRequestPayload(RequestPayload $requestPayload): void{
self::$lastProcessedRequestPayload = $requestPayload;
}

public static function getFirstHeaderValue(string $headerName): ?string{
foreach(getallheaders() as $name => $value){
if (strtolower($name) === strtolower($headerName)){
return $value;
}
}

return null;
}

/**
* Fetches the raw body of a request
*/
Expand Down
21 changes: 21 additions & 0 deletions src/Router/Router.php
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
<?php
namespace Nox\Router;

use DateTime;
use Exception;
use Nox\Http\Attributes\ChosenRouteAttribute;
use Nox\Http\Interfaces\ArrayLike;
use Nox\Http\Redirect;
use Nox\Http\Request;
use Nox\Http\Rewrite;
use Nox\Nox;
use Nox\Router\Attributes\Controller;
Expand Down Expand Up @@ -68,7 +70,26 @@ public function processRequestAsStaticFile(): void{
*/
$cacheTime = $this->noxInstance->staticFileHandler->getCacheTimeForMime($mimeType);
if ($cacheTime !== null) {

header(sprintf("cache-control: max-age=%d", $cacheTime));

$lastModifiedTime = filemtime($staticFilePath);
if ($lastModifiedTime !== false){
$lastModifiedDateTime = new DateTime('UTC');
$lastModifiedDateTimestamp = $lastModifiedDateTime->format('D, d M Y H:i:s \G\M\T');
header(sprintf("last-modified: %s", $lastModifiedDateTimestamp));
header(sprintf("etag: %d", $lastModifiedTime));

// Check if the client sent an "If-None-Match" header with the same etag used above
// If so, simply respond with 304 Not Modified and exit.
// Else, don't exit
$ifNoneMatch = Request::getFirstHeaderValue("If-None-Match");
if ((string) $lastModifiedTime === $ifNoneMatch){
// Etags match, no need to send file. It's not stale
http_response_code(304);
exit();
}
}
}

$fileContents = file_get_contents(realpath($staticFilePath));
Expand Down

0 comments on commit 0c875a9

Please sign in to comment.