1
|
|
|
<?php namespace Onigoetz\Imagecache\Support\Slim; |
2
|
|
|
|
3
|
|
|
use GuzzleHttp\Psr7\LazyOpenStream; |
4
|
|
|
use Onigoetz\Imagecache\Exceptions\InvalidPresetException; |
5
|
|
|
use Onigoetz\Imagecache\Exceptions\NotFoundException; |
6
|
|
|
use Onigoetz\Imagecache\Manager; |
7
|
|
|
use Onigoetz\Imagecache\Transfer; |
8
|
|
|
use Psr\Http\Message\ResponseInterface; |
9
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
10
|
|
|
use RuntimeException; |
11
|
|
|
use Slim\App; |
12
|
|
|
|
13
|
|
|
class ImagecacheRegister |
14
|
|
|
{ |
15
|
18 |
|
public function request() |
16
|
|
|
{ |
17
|
|
|
return function (ServerRequestInterface $req, ResponseInterface $res, $args) { |
18
|
|
|
|
19
|
12 |
|
$preset = $args['preset']; |
20
|
12 |
|
$file = $args['file']; |
21
|
|
|
|
22
|
|
|
try { |
23
|
12 |
|
$final_file = $this->imagecache->handleRequest($preset, $file); |
|
|
|
|
24
|
10 |
|
} catch (InvalidPresetException $e) { |
25
|
3 |
|
$res->getBody()->write($e->getMessage()); |
26
|
3 |
|
return $res->withStatus(404); |
27
|
6 |
|
} catch (NotFoundException $e) { |
28
|
3 |
|
$res->getBody()->write($e->getMessage()); |
29
|
3 |
|
return $res->withStatus(404); |
30
|
3 |
|
} catch (RuntimeException $e) { |
31
|
3 |
|
$res->getBody()->write($e->getMessage()); |
32
|
3 |
|
return $res->withStatus(500); |
33
|
|
|
} |
34
|
|
|
|
35
|
3 |
|
$transfer = new Transfer($final_file); |
36
|
3 |
|
foreach ($transfer->getHeaders() as $key => $value) { |
37
|
3 |
|
$res = $res->withHeader($key, $value); |
38
|
1 |
|
} |
39
|
|
|
|
40
|
3 |
|
return $res->withStatus($transfer->getStatus())->withBody(new LazyOpenStream($final_file, 'r')); |
41
|
18 |
|
}; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
public static function register(App $app, $config) |
45
|
|
|
{ |
46
|
15 |
|
$app->getContainer()['imagecache'] = function () use ($config) { |
47
|
15 |
|
return new Manager($config); |
48
|
|
|
}; |
49
|
|
|
|
50
|
18 |
|
$app->get( |
51
|
18 |
|
"/{$config['path_web']}/{$config['path_cache']}/{preset}/{file:.*}", |
52
|
18 |
|
(new ImagecacheRegister)->request() |
53
|
6 |
|
) |
54
|
18 |
|
->setName('onigoetz.imagecache'); |
55
|
18 |
|
} |
56
|
|
|
} |
57
|
|
|
|
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: