Skip to content

Instantly share code, notes, and snippets.

@Soulwest
Created February 5, 2023 18:18
Show Gist options
  • Save Soulwest/d8b6c2546d88a615a7dc0eb0ced57b50 to your computer and use it in GitHub Desktop.
Save Soulwest/d8b6c2546d88a615a7dc0eb0ced57b50 to your computer and use it in GitHub Desktop.
Code example
<?php
abstract class HTTP extends Kohana_HTTP {
/**
* The standard Kohana_HTTP::redirect raises Out of memory fatal error sometimes
*
* We don't need redirects in HMVC, so we can use the straight-forward approach instead of throwing exception
*/
public static function redirect($uri = '', int $code = 302) : void
{
if ( ! str_contains($uri, '://'))
{
// Make the URI into a URL
$uri = URL::site($uri, TRUE, ! empty(Kohana::$index_file));
}
header('HTTP/1.1 '.$code.' '.Response::$messages[$code]);
header('Location: '.$uri);
exit();
}
/**
* Checks the browser cache to see the response needs to be returned,
* execution will halt and a 304 Not Modified will be sent if the
* browser cache is up-to-date.
*
* @throws Request_Exception
*/
public static function check_cache(Request $request, Response $response, string $etag = NULL) : Response
{
// Generate an etag if necessary
if ($etag === NULL)
{
$etag = $response->generate_etag();
}
// Set the ETag header
$response->headers('ETag', $etag);
// Add the Cache-Control header if it is not already set
// This allows etags to be used with max-age, etc
if ($response->headers('cache-control'))
{
$response->headers('cache-control', $response->headers('cache-control').', must-revalidate');
}
else
{
$response->headers('cache-control', 'must-revalidate');
}
// Check if we have a matching etag
if (
$request->headers('if-none-match')
AND (
(string) $request->headers('if-none-match') === $etag
OR preg_replace('/^W\//', '', $request->headers('if-none-match')) === $etag
)
)
{
// No need to send data again
throw HTTP_Exception::factory(304)->headers('ETag', $etag);
}
return $response;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment