From a9f97363ce6c986e68b3da714a988d04ede872f2 Mon Sep 17 00:00:00 2001 From: Oliver Vogel Date: Sat, 17 May 2014 11:45:16 +0200 Subject: [PATCH] added imagecache route to serviceprovider --- .../Image/ImageServiceProvider.php | 69 +++++++++++++++++-- 1 file changed, 65 insertions(+), 4 deletions(-) diff --git a/src/Intervention/Image/ImageServiceProvider.php b/src/Intervention/Image/ImageServiceProvider.php index 26e4999e..7f0fae12 100644 --- a/src/Intervention/Image/ImageServiceProvider.php +++ b/src/Intervention/Image/ImageServiceProvider.php @@ -1,6 +1,7 @@ app; - $app['image'] = $app->share( - function ($app) { - return new ImageManager($app['config']); + + $app['image'] = $app->share(function ($app) { + return new ImageManager($app['config']); + }); + + // try to create imagecache route only if imagecache is present + if (class_exists('Intervention\Image\ImageCache')) { + + // load imagecache config + $app['config']->package('intervention/imagecache', __DIR__.'/../../../../imagecache/src/config', 'imagecache'); + $config = $app['config']; + + // create dynamic manipulation route + if (is_string($config->get('imagecache::route'))) { + + // add original to route templates + $config->set('imagecache::templates.original', null); + + // setup image manipulator route + $app['router']->get($config->get('imagecache::route').'/{template}/{filename}', array('as' => 'imagecache', function ($template, $filename) use ($app, $config) { + + // find file + foreach ($config->get('imagecache::paths') as $path) { + $image_path = $path.'/'.$filename; + if (file_exists($image_path) && is_file($image_path)) { + break; + } else { + $image_path = false; + } + } + + // abort if file not found + if ($image_path === false) { + $app->abort(404); + } + + // define template callback + $callback = $config->get("imagecache::templates.{$template}"); + + if (is_callable($callback)) { + + // image manipulation based on callback + $content = $app['image']->cache(function ($image) use ($image_path, $callback) { + return $callback($image->make($image_path)); + }, $config->get('imagecache::lifetime')); + + } else { + + // get original image file contents + $content = file_get_contents($image_path); + } + + // define mime type + $mime = finfo_buffer(finfo_open(FILEINFO_MIME_TYPE), $content); + + // return http response + return new Response($content, 200, array( + 'Content-Type' => $mime, + 'Cache-Control' => 'max-age='.($config->get('imagecache::lifetime')*60).', public', + 'Etag' => md5($content) + )); + + }))->where(array('template' => join('|', array_keys($config->get('imagecache::templates'))), 'filename' => '^[\/\w.-]+$')); } - ); + } } /**