Passed
Push — master ( cc8463...0206ad )
by Mihail
09:28
created

FormNarrowContentUpdate   A

Complexity

Total Complexity 23

Size/Duplication

Total Lines 225
Duplicated Lines 17.33 %

Coupling/Cohesion

Components 1
Dependencies 15

Importance

Changes 0
Metric Value
dl 39
loc 225
rs 9.1666
c 0
b 0
f 0
wmc 23
lcom 1
cbo 15

10 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
B before() 0 21 5
A sources() 0 10 1
A labels() 0 10 1
A rules() 5 23 2
A types() 0 6 1
B make() 0 47 5
A categoryIds() 9 9 2
A validatePath() 14 14 3
A generateCommentHash() 11 11 2

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace Apps\Model\Front\Content;
4
5
use Apps\ActiveRecord\Content;
6
use Apps\ActiveRecord\ContentCategory;
7
use Ffcms\Core\App;
8
use Ffcms\Core\Arch\Model;
9
use Ffcms\Core\Helper\FileSystem\Directory;
10
use Ffcms\Core\Helper\FileSystem\Normalize;
11
use Ffcms\Core\Helper\Type\Obj;
12
use Ffcms\Core\Helper\Type\Str;
13
use Gregwar\Image\Image;
14
15
class FormNarrowContentUpdate extends Model
16
{
17
    public $title = [];
18
    public $text = [];
19
    public $path;
20
    public $categoryId;
21
    /** @var \Symfony\Component\HttpFoundation\File\UploadedFile $poster */
22
    public $poster;
23
24
    public $authorId;
25
26
    /** @var Content */
27
    private $_record;
28
    /** @var array */
29
    private $_configs;
30
31
    private $_new = false;
32
33
    /**
34
     * FormNarrowContentUpdate constructor. Pass record object inside.
35
     * @param Content $record
36
     * @param array $configs
37
     */
38
    public function __construct(Content $record, $configs)
39
    {
40
        $this->_record = $record;
41
        $this->_configs = $configs;
42
        parent::__construct();
43
    }
44
45
    /**
46
    * Set default values from database record
47
    */
48
    public function before()
49
    {
50
        // set data from db record
51
        $this->title = $this->_record->title;
52
        $this->text = $this->_record->text;
53
        $this->path = $this->_record->path;
54
        $this->categoryId = $this->_record->category_id;
55
56
        // set current user id
57
        $this->authorId = App::$User->identity()->getId();
58
        // set true if it is a new content item
59
        if ($this->_record->id === null || (int)$this->_record->id < 1) {
60
            $this->_new = true;
61
        }
62
63
        // set random path slug if not defined
64
        if ($this->path === null || Str::likeEmpty($this->path)) {
65
            $randPath = date('d-m-Y') . '-' . Str::randomLatin(mt_rand(8,12));
66
            $this->path = Str::lowerCase($randPath);
67
        }
68
    }
69
70
    /**
71
     * Form field input sources: post/get/file
72
     * {@inheritDoc}
73
     * @see \Ffcms\Core\Arch\Model::sources()
74
     */
75
    public function sources()
76
    {
77
        return [
78
            'poster' => 'file',
79
            'title' => 'post',
80
            'text' => 'post',
81
            'path' => 'post',
82
            'categoryId' => 'post'
83
        ];
84
    }
85
86
    /**
87
    * Form labels
88
    * @return array
89
    */
90
    public function labels()
91
    {
92
        return [
93
            'title' => __('Title'),
94
            'text' => __('Text'),
95
            'path' => __('Path slug'),
96
            'categoryId' => __('Category'),
97
            'poster' => __('Poster')
98
        ];
99
    }
100
101
    /**
102
    * Content update form validation rules
103
    * @return array
104
    */
105
    public function rules()
106
    {
107
        $r = [
108
            [['path', 'categoryId'], 'required'],
109
            ['title.' . App::$Request->getLanguage(), 'required'],
110
            ['text.' . App::$Request->getLanguage(), 'required', null, true, true],
111
            ['text', 'used', null, true, true],
112
            ['path', 'direct_match', '/^[a-zA-Z0-9\-]+$/'],
113
            ['categoryId', 'in', $this->categoryIds()],
114
            ['path', 'Apps\Model\Front\Content\FormNarrowContentUpdate::validatePath'],
115
            ['poster', 'used'],
116
            ['poster', 'isFile', ['jpg', 'png', 'gif', 'jpeg']],
117
            ['poster', 'sizeFile', (int)$this->_configs['gallerySize'] * 1024] // in bytes
118
        ];
119
120 View Code Duplication
        foreach (App::$Properties->get('languages') as $lang) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
121
            $r[] = ['title.' . $lang, 'length_max', 120, null, true, true];
122
            $r[] = ['keywords.' . $lang, 'length_max', 150];
123
            $r[] = ['description.' . $lang, 'length_max', 250];
124
        }
125
126
        return $r;
127
    }
128
129
    /**
130
     * Set attribute validation types
131
     * @return array
132
     */
133
    public function types()
134
    {
135
        return [
136
            'text' => 'html'
137
        ];
138
    }
139
140
    /**
141
     * Save input data to database
142
     */
143
    public function make()
144
    {
145
        // save data to db
146
        $this->_record->title = $this->title;
147
        $this->_record->text = $this->text;
148
        $this->_record->path = $this->path;
149
        $this->_record->category_id = (int)$this->categoryId;
150
        $this->_record->display = 0; // set to premoderation
151
        $this->_record->author_id = (int)$this->authorId;
152
        if ($this->_new === true) {
153
            $this->_record->comment_hash = $this->generateCommentHash();
154
        }
155
156
        $this->_record->save();
157
158
        // work with poster data
159
        if ($this->poster !== null) {
160
            // lets move poster from tmp to gallery
161
            $originDir = '/upload/gallery/' . $this->_record->id . '/orig/';
162
            $thumbDir = '/upload/gallery/' . $this->_record->id . '/thumb/';
163
            if (!Directory::exist($originDir)) {
164
                Directory::create($originDir);
165
            }
166
            if (!Directory::exist($thumbDir)) {
167
                Directory::create($thumbDir);
168
            }
169
170
            $fileName = App::$Security->simpleHash($this->poster->getClientOriginalName() . $this->poster->getSize());
171
            $newFullName = $fileName . '.' . $this->poster->guessExtension();
172
            // move poster to upload gallery directory
173
            $this->poster->move(Normalize::diskFullPath($originDir), $newFullName);
174
            // initialize image resizer
175
            $thumb = new Image();
176
            $thumb->setCacheDir(root . '/Private/Cache/images');
177
178
            // open original file, resize it and save
179
            $thumbSaveName = Normalize::diskFullPath($thumbDir) . '/' . $fileName . '.jpg';
180
            $thumb->open(Normalize::diskFullPath($originDir) . DIRECTORY_SEPARATOR . $newFullName)
181
                ->cropResize($this->_configs['galleryResize'])
182
                ->save($thumbSaveName, 'jpg', 90);
183
            $thumb = null;
0 ignored issues
show
Unused Code introduced by
$thumb 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...
184
185
            // update poster in database
186
            $this->_record->poster = $newFullName;
187
            $this->_record->save();
188
        }
189
    }
190
191
    /**
192
     * Get allowed category ids as array (string values for validation)
193
     * @return array
194
     */
195 View Code Duplication
    public function categoryIds()
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...
196
    {
197
        $data = ContentCategory::getSortedCategories();
198
        $response = [];
199
        foreach ($data as $key=>$val) {
200
            $response[] = (string)$key;
201
        }
202
        return $response;
203
    }
204
205
    /**
206
     * Validate content item pathway
207
     * @return bool
208
     */
209 View Code Duplication
    public function validatePath()
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...
210
    {
211
        // try to find this item
212
        $find = Content::where('path', '=', $this->path);
213
        // exclude self id
214
        if ($this->_record->id !== null && Obj::isLikeInt($this->_record->id)) {
215
            $find->where('id', '!=', $this->_record->id);
216
        }
217
218
        // limit only current category id
219
        $find->where('category_id', '=', $this->categoryId);
220
221
        return $find->count() < 1;
222
    }
223
224
    /**
225
     * Generate random string for comment hash value
226
     * @return string
227
     */
228 View Code Duplication
    private function generateCommentHash()
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...
229
    {
230
        $hash = Str::randomLatinNumeric(mt_rand(32, 128));
231
        $find = Content::where('comment_hash', '=', $hash)->count();
232
        // hmmm, is always exist? Chance of it is TOOOO low, but lets recursion re-generate
233
        if ($find !== 0) {
234
            return $this->generateCommentHash();
235
        }
236
237
        return $hash;
238
    }
239
}