1 | <?php |
||
13 | class ImageStrategy implements ListenerAggregateInterface |
||
14 | { |
||
15 | /** |
||
16 | * @var \Zend\Stdlib\CallbackHandler[] |
||
17 | */ |
||
18 | protected $listeners = []; |
||
19 | |||
20 | /** |
||
21 | * @var ImagineInterface |
||
22 | */ |
||
23 | protected $imagine; |
||
24 | |||
25 | /** |
||
26 | * Constructor |
||
27 | * |
||
28 | * @param ImagineInterface $imagine |
||
29 | */ |
||
30 | 3 | public function __construct(ImagineInterface $imagine) |
|
34 | |||
35 | /** |
||
36 | * {@inheritDoc} |
||
37 | */ |
||
38 | public function attach(EventManagerInterface $events, $priority = 1) |
||
43 | |||
44 | /** |
||
45 | * {@inheritDoc} |
||
46 | */ |
||
47 | public function detach(EventManagerInterface $events) |
||
48 | { |
||
49 | foreach ($this->listeners as $index => $listener) { |
||
50 | if ($events->detach($listener)) { |
||
51 | unset($this->listeners[$index]); |
||
52 | } |
||
53 | } |
||
54 | } |
||
55 | |||
56 | /** |
||
57 | * Sets ImageRenderer as Renderer when ImageModel is used |
||
58 | * |
||
59 | * @param ViewEvent $e |
||
60 | * @return ImageRenderer|null |
||
61 | * @throws Exception\RuntimeException |
||
62 | */ |
||
63 | 2 | public function selectRenderer(ViewEvent $e) |
|
64 | { |
||
65 | 2 | $model = $e->getModel(); |
|
66 | 2 | if ($model instanceof ImageModel) { |
|
67 | 1 | if (!$model->getImage() instanceof ImageInterface) { |
|
68 | 1 | if (!$model->getImagePath()) { |
|
69 | 1 | throw new Exception\RuntimeException( |
|
70 | 'You must provide Imagine\Image\ImageInterface or path of image' |
||
71 | 1 | ); |
|
72 | } |
||
73 | $model->setImage($this->imagine->open($model->getImagePath())); |
||
74 | } |
||
75 | |||
76 | return new ImageRenderer(); |
||
77 | } |
||
78 | 1 | } |
|
79 | |||
80 | /** |
||
81 | * Sets the response based on image returned by the renderer |
||
82 | * |
||
83 | * @param ViewEvent $e |
||
84 | * @return void |
||
85 | */ |
||
86 | public function injectResponse(ViewEvent $e) |
||
87 | { |
||
88 | $model = $e->getModel(); |
||
89 | if ($model instanceof ImageModel) { |
||
90 | $result = $e->getResult(); |
||
91 | |||
92 | $response = $e->getResponse(); |
||
93 | $response->setContent($result); |
||
94 | |||
95 | $response->getHeaders()->addHeaderLine('Content-type', $this->getMimeType($model->getFormat())); |
||
96 | } |
||
97 | } |
||
98 | |||
99 | /** |
||
100 | * Internal |
||
101 | * |
||
102 | * Get the mime type based on format. |
||
103 | * |
||
104 | * @param string $format |
||
105 | * |
||
106 | * @return string mime-type |
||
107 | * |
||
108 | * @throws RuntimeException |
||
109 | */ |
||
110 | protected function getMimeType($format) |
||
124 | } |
||
125 |