AttachFileBehavior::objectMethods()   B
last analyzed

Complexity

Conditions 6
Paths 8

Size

Total Lines 31
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 2
Metric Value
c 2
b 0
f 2
dl 0
loc 31
rs 8.439
cc 6
eloc 19
nc 8
nop 1
1
<?php
2
3
namespace ItBlaster\AttachFileBundle\Behavior;
4
5
/**
6
 * Загрузка файлов
7
 *
8
 * Class AttachFileBehavior
9
 * @package ItBlaster\AttachFileBundle\Behavior
10
 */
11
class AttachFileBehavior extends \Behavior
12
{
13
    protected $parameters = array(
14
        'file_columns'  =>  '',
15
        'i18n'  => ''
16
    );
17
    protected $builder;
18
19
    protected $file_columns = array();
20
    protected $i18n_file_columns = array();
21
22
    /**
23
     * Проверяем существование столбцов original_name, file_name, ext, size
24
     *
25
     * @throws InvalidArgumentException
26
     */
27
    public function modifyTable()
28
    {
29
        $table = $this->getTable();
0 ignored issues
show
Unused Code introduced by
$table is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
30
        $file_columns = explode(',',$this->getParameter('file_columns'));
31
        foreach ($file_columns as $file_column) {
32
            $file_column = trim($file_column);
33
            if ($file_column) {
34
                $this->file_columns[]= $file_column;
35
            }
36
        }
37
38
        if ($this->getParameter('i18n')) {
39
            $file_columns = explode(',',$this->getParameter('i18n'));
40
            foreach ($file_columns as $file_column) {
41
                $file_column = trim($file_column);
42
                if ($file_column) {
43
                    $this->i18n_file_columns[]= $file_column;
44
                }
45
            }
46
        }
47
    }
48
49
    /**
50
     * Добавляем поле $file в модель
51
     *
52
     * @return string The code to be added to model class
53
     */
54
    public function objectAttributes()
55
    {
56
57
        $table_name = $this->getTable()->getName();
58
        $attributes = '
59
protected $class_alias = "' . $table_name . '"; //название класса в венгерском стиле
60
protected $files = array();
61
protected $file_objects = array();';
62
63
        if (count($this->file_columns)) {
64
            $attributes .= '
65
protected $file_fields = array(';
66
            foreach ($this->file_columns as $file_column) {
67
                $attributes .= '"' . $file_column . '",';
68
            }
69
70
            $attributes .= ');
71
';
72
        }
73
        return $attributes;
74
    }
75
76
    /**
77
     * добавляем методы в модель
78
     *
79
     * @param $builder
80
     * @return string
81
     */
82
    public function objectMethods($builder)
83
    {
84
        $this->builder = $builder;
85
        $script = '';
86
87
        $this->getClassAlias($script);
88
89
        if ($this->getParameter('i18n')) {
90
            $this->addDeleteI18nFiles($script);
91
        }
92
93
        if (count($this->file_columns)) {
94
            $this->saveFiles($script);
95
            $this->deleteFiles($script);
96
            $this->getFileObject($script);
97
            foreach ($this->file_columns as $file_column) {
98
                $this->addGetColumnFile($script, $file_column);
99
                $this->addSetColumnFile($script, $file_column);
100
                $this->addGetColumnPath($script, $file_column);
101
            }
102
        }
103
104
        if (count($this->i18n_file_columns)) {
105
            foreach ($this->i18n_file_columns as $file_column) {
106
                $this->addGetI18nColumnPath($script, $file_column);
107
                $this->addGetI18nColumnObject($script, $file_column);
108
            }
109
        }
110
111
        return $script;
112
    }
113
114
    /**
115
     * Удаление прикреплённых файлов к объектам i18n
116
     */
117
    public function addDeleteI18nFiles(&$script)
118
    {
119
        $script .= '
120
/**
121
 * Удаление прикреплённых файлов
122
 */
123
public function deleteI18nFiles()
124
{
125
    $files = \ItBlaster\AttachFileBundle\Model\AttachFileQuery::create()
126
            ->filterByModel($this->getClassAlias()."_i18n")
127
            ->filterByObjectId($this->getId())
128
            ->find();
129
    if (count($files)) {
130
        $files_dir = "";
131
        foreach($files as $file_object) {
132
            $files_dir = $file_object->fullFilePathDir();
133
            $file_object->deleteFile();
134
            $file_object->delete();
135
        }
136
        $files = glob($files_dir."*.*");
137
        if (is_dir($files_dir) && !count($files)) { //если в папке есть ещё чьи то файлы, то папку не трогаем. Если пустая, то удаляем
138
            return rmdir($files_dir);
139
        }
140
        return true;
141
    }
142
}
143
        ';
144
    }
145
146
    /**
147
     * Алиас класса
148
     *
149
     * @param $script
150
     */
151
    protected function getClassAlias(&$script)
152
    {
153
        $script .= '
154
/**
155
 * Алиас класса
156
 *
157
 * @return string
158
 */
159
public function getClassAlias()
160
{
161
    return $this->class_alias;
162
}
163
    ';
164
    }
165
166
    /**
167
     * Метод сохранения файла в postSave
168
     * После сохранения объекта сохраняем загруженный файл
169
     *
170
     * @param $builder
171
     * @return string
172
     */
173 View Code Duplication
    public function postSave($builder)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
174
    {
175
        $this->builder = $builder;
176
        $script = '';
177
        if (count($this->file_columns)) {
178
            $script .= "\$this->saveFiles(); //После сохранения объекта сохраняем загруженный файл";
179
        }
180
        return $script;
181
    }
182
183
    /**
184
     * Удаляем файлы перед удалением объекта
185
     *
186
     * @param $builder
187
     * @return string
188
     */
189 View Code Duplication
    public function preDelete($builder)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
190
    {
191
        $this->builder = $builder;
192
        $script = '';
193
        if (count($this->file_columns)) {
194
            $script .= "
195
\$this->deleteFiles(); //Перед удалением объекта удаляем загруженные файлы";
196
        }
197
        if ($this->getParameter('i18n')) {
198
            $script .= "
199
\$this->deleteI18nFiles(); //Перед удалением объекта удаляем загруженные i18n файлы";
200
        }
201
202
        return $script;
203
    }
204
205
    /**
206
     * Перевод из венгерского стиля в CamelCase
207
     *
208
     * @param $name
209
     * @return mixed
210
     */
211
    protected function CamelCase($name)
212
    {
213
        return ucfirst(\Propel\PropelBundle\Util\PropelInflector::camelize($name));
214
    }
215
216
    /**
217
     * Сохраняет файлы
218
     *
219
     * @param $script
220
     */
221
    protected function  saveFiles(&$script)
222
    {
223
        $script .= '
224
/**
225
 * Сохраняем файл в uploads
226
 *
227
 * @return \Symfony\Component\HttpFoundation\File\UploadedFile
228
 */
229
public function saveFiles()
230
{
231
    if (count ($this->files)) {
232
        /** @var \Symfony\Component\HttpFoundation\File\UploadedFile $file */
233
        $need_save = 0;
234
        foreach ($this->files as $field => $file) {
235
            if ($file) {
236
                $file_object = $this->getFileObject($field);
237
                if ($file_object->getFileName() ) { //если уже какой то файл сохранён
238
                    $file_object->deleteFile();
239
                }
240
                $file_object->setObjectId($this->getId());
241
                $file_name = uniqid();
242
                $original_name = $file->getClientOriginalName();
243
                $ext = $file->getClientOriginalExtension();
244
                $size = $file->getSize();
245
246
                $file->move($file_object->fullFilePathDir(), $file_name . "." . $ext); //перемещаем файл в uploads
247
                $file_object
248
                    ->setOriginalName($original_name)
249
                    ->setFileName($file_name)
250
                    ->setExt($ext)
251
                    ->setSize($size)
252
                    ->save();
253
                $need_save++;
254
                $this->files[$field] = null;
255
                $name = ucfirst(\Propel\PropelBundle\Util\PropelInflector::camelize($field));
256
                $this->setByName($name, $file_object->getId());
257
            }
258
        }
259
        if ($need_save) {
260
            $this->save();
261
        }
262
    }
263
}
264
    ';
265
    }
266
267
    /**
268
     * Удаляем файлы
269
     *
270
     * @param $script
271
     */
272
    protected function deleteFiles(&$script)
273
    {
274
        $script .= '
275
/**
276
 * Удаление прикреплённых файлов
277
 *
278
 * @return bool
279
 */
280
public function deleteFiles()
281
{
282
    $files_dir = "";
283
    foreach($this->file_fields as $field) {
284
        $file_object = $this->getFileObject($field);
285
        $files_dir = $file_object->fullFilePathDir();
286
        $file_object->deleteFile();
287
        $file_object->delete();
288
    }
289
    $files = glob($files_dir."*.*");
290
    if (is_dir($files_dir) && !count($files)) { //если в папке есть ещё чьи то файлы, то папку не трогаем. Если пустая, то удаляем
291
        return rmdir($files_dir);
292
    }
293
    return true;
294
}
295
        ';
296
    }
297
298
    /**
299
     * Возврашает файл конкретного поля
300
     *
301
     * @param $script
302
     */
303 View Code Duplication
    protected function addGetColumnFile(&$script, $file_column)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
304
    {
305
        $name = $this->CamelCase($file_column);
306
        $script .= '
307
/**
308
 * Возврашает файл '.$file_column.'
309
 *
310
 * @return \Symfony\Component\HttpFoundation\File\UploadedFile
311
 */
312
public function get'.$name.'File()
313
{
314
    return isset($this->files["'.$file_column.'"]) ? $this->files["'.$file_column.'"] : false;
315
}
316
    ';
317
    }
318
319
    /**
320
     * Запоминаем файл
321
     *
322
     * @param $script
323
     */
324 View Code Duplication
    protected function addSetColumnFile(&$script, $file_column)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
325
    {
326
        $name = $this->CamelCase($file_column);
327
        $script .= '
328
/**
329
 * Устанавливает файл
330
 *
331
 * @param \Symfony\Component\HttpFoundation\File\UploadedFile $v
332
 */
333
public function set'.$name.'File($v)
334
{
335
        $this->files["'.$file_column.'"] = $v;
336
        if ($v) {
337
            $file_object = $this->getFileObject("'.$file_column.'");
338
            $this->set'.$name.'(uniqid());
339
        }
340
}
341
    ';
342
    }
343
344
    /**
345
     * Путь до файла
346
     *
347
     * @param $script
348
     * @param $file_column
349
     */
350 View Code Duplication
    protected function addGetColumnPath(&$script, $file_column)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
351
    {
352
        $name = $this->CamelCase($file_column);
353
        $script .= '
354
/**
355
 * Путь до файла '.$file_column.'
356
 *
357
 * @return \Symfony\Component\HttpFoundation\File\UploadedFile
358
 */
359
public function get'.$name.'Path()
360
{
361
    $file_object = $this->getFileObject("'.$file_column.'");
362
    return $file_object && $file_object->issetFile() ? $file_object->getFilePath() : "";
363
}
364
    ';
365
    }
366
367
    /**
368
     * Путь до файла
369
     *
370
     * @param $script
371
     * @param $file_column
372
     */
373 View Code Duplication
    protected function addGetI18nColumnPath(&$script, $file_column)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
374
    {
375
        $name = $this->CamelCase($file_column);
376
        $script .= '
377
/**
378
 * Путь до файла '.$file_column.'
379
 *
380
 * @return \Symfony\Component\HttpFoundation\File\UploadedFile
381
 */
382
public function get'.$name.'Path()
383
{
384
    return $this->getCurrentTranslation()->get'.$name.'Path();
385
}
386
    ';
387
    }
388
389
    /**
390
     * Объект файла
391
     *
392
     * @param $script
393
     * @param $file_column
394
     */
395 View Code Duplication
    protected function addGetI18nColumnObject(&$script, $file_column)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
396
    {
397
        $name = $this->CamelCase($file_column);
398
        $script .= '
399
/**
400
 * Путь до файла '.$file_column.'
401
 *
402
 * @return \Symfony\Component\HttpFoundation\File\UploadedFile
403
 */
404
public function get'.$name.'Object()
405
{
406
    return $this->getCurrentTranslation()->getFileObject("'.$file_column.'");;
407
}
408
    ';
409
    }
410
411
    /**
412
     * Объект файла
413
     *
414
     * @param $script
415
     */
416
    protected function getFileObject(&$script)
417
    {
418
        $script .= '
419
/**
420
 * Объект файла
421
 *
422
 * @param $field
423
 * @return AttachFile
424
 */
425
public function getFileObject($field)
426
{
427
    if (!isset($this->file_objects[$field])) {
428
        $name = ucfirst(\Propel\PropelBundle\Util\PropelInflector::camelize($field));
429
        $file_object_id = $this->getByName($name);
430
        $file_object = $file_object_id ? \ItBlaster\AttachFileBundle\Model\AttachFileQuery::create()->findOneById($file_object_id) : false;
431
432
        if ($file_object) {
433
            $this->file_objects[$field] = $file_object;
434
        } else {
435
            $file_object = new \ItBlaster\AttachFileBundle\Model\AttachFile();
436
            $file_object
437
                ->setObjectId($this->getId())
438
                ->setModel($this->getClassAlias())
439
                ->setField($field)
440
                ->setObjectId($this->getId());
441
            $this->file_objects[$field] = $file_object;
442
        }
443
    }
444
    return $this->file_objects[$field];
445
}
446
    ';
447
    }
448
}