Last active
January 2, 2016 07:49
-
-
Save dhardtke/8272328 to your computer and use it in GitHub Desktop.
Controller to send appropriate caching headers to clients. Use it like this in your config.php of AssetPipeline: 'controller_action' => 'CustomAssetPipelineController@file'
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Symfony\Component\HttpFoundation\BinaryFileResponse; | |
use Codesleeve\AssetPipeline\Asset; | |
class CustomAssetPipelineController extends BaseController | |
{ | |
/** | |
* Returns a file in the assets directory | |
* | |
* @return \Illuminate\Support\Facades\Response | |
*/ | |
public function file($path) | |
{ | |
$absolutePath = Asset::isJavascript($path); | |
if ($absolutePath) { | |
return $this->javascript($absolutePath); | |
} | |
$absolutePath = Asset::isStylesheet($path); | |
if ($absolutePath) { | |
return $this->stylesheet($absolutePath); | |
} | |
$absolutePath = Asset::isFile($path); | |
if ($absolutePath) { | |
return new BinaryFileResponse($absolutePath, 200); | |
} | |
App::abort(404); | |
} | |
/* | |
* Returns a javascript file for the given path. | |
* | |
* @return \Illuminate\Support\Facades\Response | |
*/ | |
private function javascript($path) | |
{ | |
$this->prepareClientCache($path); | |
$response = Response::make(Asset::javascript($path), 200); | |
$response->header('Content-Type', 'application/javascript'); | |
return $response; | |
} | |
/** | |
* Returns css for the given path | |
* | |
* @return \Illuminate\Support\Facades\Response | |
*/ | |
private function stylesheet($path) | |
{ | |
$this->prepareClientCache($path); | |
$response = Response::make(Asset::stylesheet($path), 200); | |
$response->header('Content-Type', 'text/css'); | |
return $response; | |
} | |
/** | |
* prepare client cache so the client doesn't have to download the asset again | |
* | |
* @return void | |
*/ | |
private function prepareClientCache($path) { | |
$lastLastModified = filemtime($path); | |
header('Last-Modified: '.gmdate('r', $lastLastModified)); | |
if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= $lastLastModified) { | |
header('HTTP/1.0 304 Not Modified'); | |
exit; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment