AttributeTypeAttributeAvController   A
last analyzed

Complexity

Total Complexity 30

Size/Duplication

Total Lines 257
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 30
lcom 1
cbo 3
dl 0
loc 257
rs 10
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
C updateMetaAction() 0 65 11
A deleteMetaAction() 0 37 5
A dispatchEvent() 0 27 2
A getAttributeAttributeType() 0 15 3
A getLocale() 0 12 3
A uploadFile() 0 44 4
A generateUniqueFileName() 0 6 1
A resetUpdateForm() 0 6 1
1
<?php
2
/*************************************************************************************/
3
/*      This file is part of the module AttributeType                                */
4
/*                                                                                   */
5
/*      For the full copyright and license information, please view the LICENSE.txt  */
6
/*      file that was distributed with this source code.                             */
7
/*************************************************************************************/
8
9
namespace AttributeType\Controller;
10
11
use AttributeType\AttributeType;
12
use AttributeType\Event\AttributeTypeEvents;
13
use AttributeType\Event\AttributeTypeAvMetaEvent;
14
use AttributeType\Form\AttributeTypeAvMetaUpdateForm;
15
use AttributeType\Model\AttributeAttributeType;
16
use AttributeType\Model\AttributeAttributeTypeQuery;
17
use AttributeType\Model\AttributeTypeAvMeta;
18
use AttributeType\Model\AttributeTypeAvMetaQuery;
19
use AttributeType\Model\AttributeTypeQuery;
20
use Symfony\Component\Filesystem\Filesystem;
21
use Symfony\Component\HttpFoundation\File\UploadedFile;
22
use Thelia\Core\Security\AccessManager;
23
use Thelia\Core\Security\Resource\AdminResources;
24
use Thelia\Files\Exception\ProcessFileException;
25
use Thelia\Model\Lang;
26
use Thelia\Model\LangQuery;
27
28
/**
29
 * Class AttributeTypeAttributeAvController
30
 * @package AttributeType\Controller
31
 * @author Gilles Bourgeat <[email protected]>
32
 */
33
class AttributeTypeAttributeAvController extends AttributeTypeController
34
{
35
    /** @var Lang[] */
36
    protected $langs = array();
37
38
    /** @var AttributeAttributeType[] */
39
    protected $attributeAttributeTypes = array();
40
41
    /**
42
     * @param int $attribute_id
43
     * @return null|\Symfony\Component\HttpFoundation\Response|\Thelia\Core\HttpFoundation\Response
44
     */
45
    public function updateMetaAction($attribute_id)
46
    {
47
        if (null !== $response = $this->checkAuth(array(AdminResources::ATTRIBUTE), null, AccessManager::UPDATE)) {
48
            return $response;
49
        }
50
51
        $form = $this->createForm("attribute_type_av_meta.update");
52
53
        try {
54
            $formUpdate = $this->validateForm($form);
55
56
            $attributeAvs = $formUpdate->get('attribute_av')->getData();
57
58
            foreach ($attributeAvs as $attributeAvId => $attributeAv) {
59
                foreach ($attributeAv['lang'] as $langId => $lang) {
60
                    foreach ($lang['attribute_type'] as $attributeTypeId => $value) {
61
                        $values = [];
62
                        $values[$langId] = $value;
63
                        $attributeType = AttributeTypeQuery::create()
64
                            ->findOneById($attributeTypeId);
65
66
                        if ($attributeType->getInputType() === "image") {
67
                            if (null === $value) {
68
                                continue;
69
                            }
70
71
                            $uploadedFileName = $this->uploadFile($value);
72
                            $values[$langId] = $uploadedFileName;
73
74
                            if (!$attributeType->getIsMultilingualAttributeAvValue()) {
75
                                $activeLangs = LangQuery::create()
76
                                    ->filterByActive(1)
77
                                    ->find();
78
                                /** @var Lang $lang */
79
                                foreach ($activeLangs as $lang) {
80
                                    $values[$lang->getId()] = $uploadedFileName;
81
                                }
82
                            }
83
                        }
84
85
                         foreach ($values as $langId => $langValue) {
86
                             $this->dispatchEvent(
87
                                 $this->getAttributeAttributeType($attributeTypeId, $attribute_id),
88
                                 $attributeAvId,
89
                                 $langId,
90
                                 $langValue
91
                             );
92
                         }
93
                    }
94
                }
95
            }
96
97
            $this->resetUpdateForm();
98
            return $this->generateSuccessRedirect($form);
99
        } catch (\Exception $e) {
100
            $this->setupFormErrorContext(
101
                $this->getTranslator()->trans("%obj modification", array('%obj' => $this->objectName)),
102
                $e->getMessage(),
103
                $form,
104
                $e
105
            );
106
107
            return $this->viewAttribute($attribute_id);
108
        }
109
    }
110
111
    public function deleteMetaAction($attribute_id, $attribute_type_id, $attribute_av_id, $lang_id)
112
    {
113
        if (null !== $response = $this->checkAuth(array(AdminResources::ATTRIBUTE), null, AccessManager::DELETE)) {
114
            return $response;
115
        }
116
        $form = $this->createForm("attribute_type.delete");
117
        try {
118
            $this->validateForm($form);
119
            $attributeType = AttributeTypeQuery::create()
120
                ->findOneById($attribute_type_id);
121
            $attributeAttributeType =  $this->getAttributeAttributeType($attribute_type_id, $attribute_id);
122
            $eventName = AttributeTypeEvents::ATTRIBUTE_TYPE_AV_META_DELETE;
123
            $attributeAvMetaQuery = AttributeTypeAvMetaQuery::create()
124
                ->filterByAttributeAvId($attribute_av_id)
125
                ->filterByAttributeAttributeTypeId($attributeAttributeType->getId());
126
            if ($attributeType->getIsMultilingualAttributeAvValue()) {
127
                $attributeAvMetaQuery->filterByLocale($this->getLocale($lang_id));
128
            }
129
            $attributeAvMetas = $attributeAvMetaQuery->find();
130
            foreach ($attributeAvMetas as $attributeAvMeta) {
131
                $this->dispatch(
132
                    $eventName,
133
                    (new AttributeTypeAvMetaEvent($attributeAvMeta))
134
                );
135
            }
136
            $this->resetUpdateForm();
137
            return $this->generateSuccessRedirect($form);
138
        } catch (\Exception $e) {
139
            $this->setupFormErrorContext(
140
                $this->getTranslator()->trans("%obj modification", array('%obj' => $this->objectName)),
141
                $e->getMessage(),
142
                $form,
143
                $e
144
            );
145
            return $this->viewAttribute($attribute_id);
146
        }
147
    }
148
149
    /**
150
     * @param AttributeAttributeType $attributeAttributeType
151
     * @param int $attributeAvId
152
     * @param int $langId
153
     * @param string $value
154
     * @throws \Exception
155
     */
156
    protected function dispatchEvent(AttributeAttributeType $attributeAttributeType, $attributeAvId, $langId, $value)
157
    {
158
        $eventName = AttributeTypeEvents::ATTRIBUTE_TYPE_AV_META_UPDATE;
159
160
        $attributeAvMeta = AttributeTypeAvMetaQuery::create()
161
            ->filterByAttributeAvId($attributeAvId)
162
            ->filterByAttributeAttributeTypeId($attributeAttributeType->getId())
163
            ->filterByLocale($this->getLocale($langId))
164
            ->findOne();
165
166
        // create if not exist
167
        if ($attributeAvMeta === null) {
168
            $eventName = AttributeTypeEvents::ATTRIBUTE_TYPE_AV_META_CREATE;
169
170
            $attributeAvMeta = (new AttributeTypeAvMeta())
171
                ->setAttributeAvId($attributeAvId)
172
                ->setAttributeAttributeTypeId($attributeAttributeType->getId())
173
                ->setLocale($this->getLocale($langId));
174
        }
175
176
        $attributeAvMeta->setValue($value);
177
178
        $this->dispatch(
179
            $eventName,
180
            (new AttributeTypeAvMetaEvent($attributeAvMeta))
181
        );
182
    }
183
184
    /**
185
     * @param int $attributeTypeId
186
     * @param int $attributeId
187
     * @return AttributeAttributeType
188
     * @throws \Exception
189
     */
190
    protected function getAttributeAttributeType($attributeTypeId, $attributeId)
191
    {
192
        if (!isset($this->attributeAttributeTypes[$attributeTypeId])) {
193
            $this->attributeAttributeTypes[$attributeTypeId] = AttributeAttributeTypeQuery::create()
194
                ->filterByAttributeTypeId($attributeTypeId)
195
                ->filterByAttributeId($attributeId)
196
                ->findOne();
197
198
            if ($this->attributeAttributeTypes[$attributeTypeId] === null) {
199
                throw new \Exception('AttributeAttributeType not found');
200
            }
201
        }
202
203
        return $this->attributeAttributeTypes[$attributeTypeId];
204
    }
205
206
    /**
207
     * @param int $langId
208
     * @return string
209
     * @throws \Exception
210
     */
211
    protected function getLocale($langId)
212
    {
213
        if (!isset($this->langs[$langId])) {
214
            $this->langs[$langId] = LangQuery::create()->findPk($langId);
215
216
            if ($this->langs[$langId] === null) {
217
                throw new \Exception('Lang not found');
218
            }
219
        }
220
221
        return $this->langs[$langId]->getLocale();
222
    }
223
224
    /**
225
     * @param UploadedFile $file
226
     * @return string
227
     */
228
    protected function uploadFile(UploadedFile $file)
229
    {
230
        if ($file->getError() == UPLOAD_ERR_INI_SIZE) {
231
            $message = $this->getTranslator()
232
                ->trans(
233
                    'File is too large, please retry with a file having a size less than %size%.',
234
                    array('%size%' => ini_get('upload_max_filesize')),
235
                    'core'
236
                );
237
            throw new ProcessFileException($message, 403);
238
        }
239
        $validMimeTypes = [
240
            'image/jpeg' => ["jpg", "jpeg"],
241
            'image/png' => ["png"],
242
            'image/gif' => ["gif"]
243
        ];
244
        $mimeType = $file->getMimeType();
245
        if (!isset($validMimeTypes[$mimeType])) {
246
            $message = $this->getTranslator()
247
                ->trans(
248
                    'Only files having the following mime type are allowed: %types%',
249
                    [ '%types%' => implode(', ', array_keys($validMimeTypes))]
250
                );
251
            throw new ProcessFileException($message, 415);
252
        }
253
        $regex = "#^(.+)\.(".implode("|", $validMimeTypes[$mimeType]).")$#i";
254
        $realFileName = $file->getClientOriginalName();
255
        if (!preg_match($regex, $realFileName)) {
256
            $message = $this->getTranslator()
257
                ->trans(
258
                    "There's a conflict between your file extension \"%ext\" and the mime type \"%mime\"",
259
                    [
260
                        '%mime' => $mimeType,
261
                        '%ext' => $file->getClientOriginalExtension()
262
                    ]
263
                );
264
            throw new ProcessFileException($message, 415);
265
        }
266
        $fileSystem = new Filesystem();
267
        $fileSystem->mkdir(THELIA_WEB_DIR. DS .AttributeType::ATTRIBUTE_TYPE_AV_IMAGE_FOLDER);
268
        $fileName = $this->generateUniqueFileName().'_'.$realFileName;
269
        $file->move(THELIA_WEB_DIR. DS .AttributeType::ATTRIBUTE_TYPE_AV_IMAGE_FOLDER, $fileName);
270
        return DS . AttributeType::ATTRIBUTE_TYPE_AV_IMAGE_FOLDER. DS .$fileName;
271
    }
272
273
    /**
274
     * @return string
275
     */
276
    protected function generateUniqueFileName()
277
    {
278
        // md5() reduces the similarity of the file names generated by
279
        // uniqid(), which is based on timestamps
280
        return substr(md5(uniqid()), 0, 10);
281
    }
282
283
    protected function resetUpdateForm() {
284
        $this->getParserContext()->remove(AttributeTypeAvMetaUpdateForm::class.':form');
285
        $theliaFormErrors = $this->getRequest()->getSession()->get('thelia.form-errors');
286
        unset($theliaFormErrors[AttributeTypeAvMetaUpdateForm::class.':form']);
287
        $this->getRequest()->getSession()->set('thelia.form-errors', $theliaFormErrors);
288
    }
289
}
290