IndexController::uploadFiles()   B
last analyzed

Complexity

Conditions 5
Paths 5

Size

Total Lines 22
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 7
Bugs 5 Features 1
Metric Value
c 7
b 5
f 1
dl 0
loc 22
rs 8.6737
cc 5
eloc 11
nc 5
nop 1
1
<?php
2
3
/**
4
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
5
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
6
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
7
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
8
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
10
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
11
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
12
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
13
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
14
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
15
 *
16
 * This software consists of voluntary contributions made by many individuals
17
 * and is licensed under the MIT license.
18
 */
19
namespace LearnZF2AjaxImageGallery\Controller;
20
21
use LearnZF2AjaxImageGallery\Form\AjaxImageUploadForm;
22
use Zend\File\Transfer\Adapter\Http;
23
use Zend\Mvc\Controller\AbstractActionController;
24
use Zend\Mvc\MvcEvent;
25
use Zend\Validator\File\Extension;
26
use Zend\Validator\File\IsImage;
27
use Zend\Validator\File\Size;
28
use Zend\View\Model\JsonModel;
29
use Zend\View\Model\ViewModel;
30
31
/**
32
 * @author  Stanimir Dimitrov <[email protected]>
33
 */
34
class IndexController extends AbstractActionController
35
{
36
    /**
37
     * @var array
38
     */
39
    protected $acceptCriteria = [
40
        'Zend\View\Model\JsonModel' => ['application/json'],
41
        'Zend\View\Model\ViewModel' => ['text/html'],
42
    ];
43
44
    /**
45
     * @var AjaxImageUploadForm
46
     */
47
    private $ajaxForm = null;
48
49
    /**
50
     * @var ViewModel
51
     */
52
    private $view;
53
54
    /**
55
     * @param AjaxImageUploadForm $form
56
     */
57
    public function __construct(AjaxImageUploadForm $form)
58
    {
59
        $this->view = new ViewModel();
60
        $this->ajaxForm = $form;
61
    }
62
63
    /**
64
     * @param MvcEvent $e
65
     */
66
    public function onDispatch(MvcEvent $e)
67
    {
68
        parent::onDispatch($e);
69
    }
70
71
    /**
72
     * @return ViewModel
73
     */
74
    public function indexAction()
75
    {
76
        $this->acceptableviewmodelselector($this->acceptCriteria);
77
78
        $this->view->form = $this->ajaxForm;
79
80
        return $this->view;
81
    }
82
83
    /**
84
     * @return JsonModel
85
     */
86
    protected function uploadAction()
87
    {
88
        $request = $this->getRequest();
89
        $data = [];
90
91
        if ($request->isXmlHttpRequest()) {
92
            $data = $this->prepareImages();
93
        }
94
95
        return new JsonModel($data);
96
    }
97
98
    /**
99
     * Deleted image with from a given src.
100
     *
101
     * @method deleteimageAction
102
     *
103
     * @return bool
104
     */
105
    protected function deleteimageAction()
106
    {
107
        $request = $this->getRequest();
108
        $status = false;
109
110
        if ($request->isPost()) {
111
            $data = $request->getPost()->toArray();
112
113
            if ($request->isXmlHttpRequest()) {
114
                if (is_file('public'.$data['img'])) {
115
                    unlink('public'.$data['img']);
116
                    $status = true;
117
                }
118
            }
119
        }
120
121
        return $status;
122
    }
123
124
    /**
125
     * Get all files from all folders and list them in the gallery
126
     * getcwd() is there to make the work with images path easier.
127
     *
128
     * @return JsonModel
129
     */
130
    protected function filesAction()
131
    {
132
        chdir(getcwd().'/public/');
133
134
        $dir = new \RecursiveDirectoryIterator('userfiles/', \FilesystemIterator::SKIP_DOTS);
135
        $it = new \RecursiveIteratorIterator($dir, \RecursiveIteratorIterator::SELF_FIRST);
136
        $it->setMaxDepth(50);
137
        $files = [];
138
        $i = 0;
139
        foreach ($it as $file) {
140
            if ($file->isFile()) {
141
                $files[$i]['filelink'] = DIRECTORY_SEPARATOR.$file->getPath().DIRECTORY_SEPARATOR.$file->getFilename();
142
                $files[$i]['filename'] = $file->getFilename();
143
                $i++;
144
            }
145
        }
146
        chdir(dirname(getcwd()));
147
        $model = new JsonModel();
148
        $model->setVariables(['files' => $files]);
149
150
        return $model;
151
    }
152
153
    /**
154
     * Upload all images async.
155
     *
156
     * @return array
157
     */
158
    private function prepareImages()
159
    {
160
        $adapter = new Http();
161
162
        $size = new Size(['min' => '10kB', 'max' => '5MB', 'useByteString' => true]);
163
        $extension = new Extension(['jpg', 'gif', 'png', 'jpeg', 'bmp', 'webp', 'svg'], true);
164
165
        if (extension_loaded('fileinfo')) {
166
            $adapter->setValidators([new IsImage()]);
167
        }
168
169
        $adapter->setValidators([$size, $extension]);
170
171
        $adapter->setDestination('public/userfiles/images/');
0 ignored issues
show
Deprecated Code introduced by
The method Zend\File\Transfer\Adapt...apter::setDestination() has been deprecated with message: Will be changed to be a filter!!!

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
172
173
        return $this->uploadFiles($adapter);
174
    }
175
176
    /**
177
     * @param Http $adapter
178
     *
179
     * @return array
180
     */
181
    private function uploadFiles(Http $adapter)
182
    {
183
        $uploadStatus = [];
184
185
        foreach ($adapter->getFileInfo() as $key => $file) {
186
            if (!$adapter->isValid($file['name'])) {
187
                foreach ($adapter->getMessages() as $key => $msg) {
188
                    $uploadStatus['errorFiles'][] = $file['name'].' '.strtolower($msg);
189
                }
190
            }
191
192
            // @codeCoverageIgnoreStart
193
            if (!$adapter->receive($file['name'])) {
194
                $uploadStatus['errorFiles'][] = $file['name'].' was not uploaded';
195
            } else {
196
                $uploadStatus['successFiles'][] = $file['name'].' was successfully uploaded';
197
            }
198
            // @codeCoverageIgnoreEnd
199
        }
200
201
        return $uploadStatus;
202
    }
203
}
204