|
| 1 | +<?php |
| 2 | + |
| 3 | +/** |
| 4 | + * Copyright (c) dotBlue (http://dotblue.net) |
| 5 | + */ |
| 6 | + |
| 7 | +namespace DotBlue\WebImages\Application; |
| 8 | + |
| 9 | +use Nette\Application\Routers\Route as BaseRoute; |
| 10 | +use Nette\Utils\Image; |
| 11 | +use DotBlue\WebImages\Generator; |
| 12 | + |
| 13 | + |
| 14 | +class Route extends BaseRoute |
| 15 | +{ |
| 16 | + |
| 17 | + /** @var array */ |
| 18 | + protected $defaults = array( |
| 19 | + 'flags' => Image::JPEG |
| 20 | + ); |
| 21 | + |
| 22 | + |
| 23 | + /** |
| 24 | + * @param string |
| 25 | + * @param array |
| 26 | + * @param \DotBlue\WebImages\Generator |
| 27 | + */ |
| 28 | + public function __construct($mask, array $defaults, Generator $generator) |
| 29 | + { |
| 30 | + $this->defaults = array_replace($this->defaults, $defaults); |
| 31 | + $defaults['presenter'] = 'Nette:Micro'; |
| 32 | + $me = $this; |
| 33 | + |
| 34 | + $defaults[NULL][self::FILTER_OUT] = function($params) use ($me, $generator) { |
| 35 | + $width = $me->acquireArgument('width', $params); |
| 36 | + $height = $me->acquireArgument('height', $params); |
| 37 | + $flags = $me->acquireArgument('flags', $params); |
| 38 | + |
| 39 | + if (!$generator->getValidator()->validate($width, $height, $flags)) { |
| 40 | + throw new \Nette\Application\ForbiddenRequestException("Image with params ({$width}x{$height}, {$flags}) is not allowed - check your 'webimages.rules' please."); |
| 41 | + } |
| 42 | + |
| 43 | + return $params; |
| 44 | + }; |
| 45 | + |
| 46 | + $defaults['callback'] = function($presenter) use ($me, $generator) { |
| 47 | + $params = $presenter->getRequest()->getParameters(); |
| 48 | + |
| 49 | + $image = NULL; |
| 50 | + try { |
| 51 | + $id = $me->acquireArgument('id', $params); |
| 52 | + $width = $me->acquireArgument('width', $params); |
| 53 | + $height = $me->acquireArgument('height', $params); |
| 54 | + $flags = $me->acquireArgument('flags', $params); |
| 55 | + |
| 56 | + $image = $generator->generateImage($id, $width, $height, $flags); |
| 57 | + } catch (\Exception $e) {} |
| 58 | + |
| 59 | + return new Response($image); |
| 60 | + }; |
| 61 | + |
| 62 | + parent::__construct($mask, $defaults); |
| 63 | + } |
| 64 | + |
| 65 | + |
| 66 | + /** |
| 67 | + * @param string |
| 68 | + * @param array |
| 69 | + * @return mixed |
| 70 | + * @throws \Nette\InvalidStateException |
| 71 | + */ |
| 72 | + public function acquireArgument($name, array $data) |
| 73 | + { |
| 74 | + if (isset($data[$name])) { |
| 75 | + return $data[$name]; |
| 76 | + } elseif (isset($this->defaults[$name])) { |
| 77 | + return $this->defaults[$name]; |
| 78 | + } else { |
| 79 | + throw new \Nette\InvalidArgumentException("Missing parameter $name."); |
| 80 | + } |
| 81 | + } |
| 82 | + |
| 83 | +} |
0 commit comments