ContentType   A
last analyzed

Complexity

Total Complexity 31

Size/Duplication

Total Lines 311
Duplicated Lines 2.57 %

Coupling/Cohesion

Components 3
Dependencies 3

Importance

Changes 0
Metric Value
wmc 31
lcom 3
cbo 3
dl 8
loc 311
rs 9.92
c 0
b 0
f 0

22 Methods

Rating   Name   Duplication   Size   Complexity  
A tableName() 0 4 1
A rules() 8 8 1
A contentRules() 0 4 1
A attributeLabels() 0 13 1
A contentLabels() 0 4 1
A fromType() 0 9 2
A instantiate() 0 6 1
A processData() 0 4 1
A getAll() 0 8 5
A getAllList() 0 12 2
A getAllFileTypeIds() 0 8 2
A downloadContent() 0 19 3
A hasCache() 0 4 1
A fromCache() 0 7 1
A toCache() 0 6 1
A getContents() 0 4 1
A getFieldHasContentTypes() 0 4 1
A getFields() 0 4 1
A upload() 0 4 1
A sideload() 0 4 1
A getLoadError() 0 4 1
A transformDataBeforeSave() 0 4 1

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 app\models;
4
5
use Yii;
6
7
/**
8
 * This is the model class for table "content_type".
9
 *
10
 * @property string $id Class name
11
 * @property bool $enabled
12
 * @property Content[] $contents
13
 * @property FieldHasContentType[] $fieldHasContentTypes
14
 * @property Field[] $fields
15
 */
16
class ContentType extends \yii\db\ActiveRecord
17
{
18
    const BASE_CACHE_TIME = 3600;
19
    const SUB_PATH = 'app\\models\\types\\';
20
21
    public $name;
22
    public $description;
23
    public $html;
24
    public $css;
25
    public $js;
26
    public $appendParams;
27
    public $selfUpdate;
28
    public $input;
29
    public $output;
30
    public $usable;
31
    public $exemple;
32
    public $canPreview;
33
34
    const KINDS = [
35
        'NONE' => 'none',
36
        'RAW' => 'raw',
37
        'URL' => 'url',
38
        'FILE' => 'file',
39
        'TEXT' => 'text',
40
        'POS' => 'latlong',
41
    ];
42
43
    /**
44
     * {@inheritdoc}
45
     */
46
    public static function tableName()
47
    {
48
        return 'content_type';
49
    }
50
51
    /**
52
     * {@inheritdoc}
53
     */
54 View Code Duplication
    public function rules()
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...
55
    {
56
        return [
57
            [['id', 'enabled'], 'required'],
58
            [['id'], 'string', 'max' => 45],
59
            [['enabled'], 'boolean'],
60
        ];
61
    }
62
63
    public function contentRules()
64
    {
65
        return [];
66
    }
67
68
    /**
69
     * {@inheritdoc}
70
     */
71
    public function attributeLabels()
72
    {
73
        return [
74
            'id' => Yii::t('app', 'ID'),
75
            'name' => Yii::t('app', 'Type'),
76
            'description' => Yii::t('app', 'Description'),
77
            'usable' => Yii::t('app', 'Usable'),
78
            'enabled' => Yii::t('app', 'Enabled'),
79
            'html' => Yii::t('app', 'HTML'),
80
            'css' => Yii::t('app', 'CSS'),
81
            'js' => Yii::t('app', 'JS'),
82
        ];
83
    }
84
85
    public function contentLabels()
86
    {
87
        return [];
88
    }
89
90
    /**
91
     * Get class from content type ID.
92
     *
93
     * @param string $typeId content type id
94
     *
95
     * @return string class name
96
     */
97
    public static function fromType($typeId)
98
    {
99
        $className = self::SUB_PATH . $typeId;
100
        if (!class_exists($className)) {
101
            throw new ServerErrorHttpException(Yii::t('app', 'The requested content type has no class.'));
102
        }
103
104
        return $className;
105
    }
106
107
    /**
108
     * Overload default instantiate to fill attributes from specific content type.
109
     *
110
     * @param array $row
111
     *
112
     * @return array transformed row
113
     */
114
    public static function instantiate($row)
115
    {
116
        $typeClass = self::fromType($row['id']);
117
118
        return new $typeClass();
119
    }
120
121
    /**
122
     * Get raw data and transform it to content type specific needs.
123
     *
124
     * @param string $data
125
     *
126
     * @return string transformed data
127
     */
128
    public function processData($data)
129
    {
130
        return $data;
131
    }
132
133
    /**
134
     * Get all filtered content types.
135
     *
136
     * @param bool $selfUpdate does content type manages itself
137
     * @param bool $usableOnly show only usable content types
138
     *
139
     * @return array content types
140
     */
141
    public static function getAll($selfUpdate = null, $usableOnly = true)
142
    {
143
        $types = self::find()->all();
144
145
        return array_filter($types, function ($t) use ($selfUpdate, $usableOnly) {
146
            return ($selfUpdate === null || $t->selfUpdate == $selfUpdate) && (!$usableOnly || ($t->usable && $t->enabled));
147
        });
148
    }
149
150
    /**
151
     * Get all filterd content types in array.
152
     *
153
     * @param bool $selfUpdate does content type manages itself
154
     * @param bool $usableOnly show only usable content types
155
     *
156
     * @return array content types
157
     */
158
    public static function getAllList($selfUpdate = null, $usableOnly = true)
159
    {
160
        $types = self::getAll($selfUpdate, $usableOnly);
161
162
        $list = [];
163
164
        foreach ($types as $t) {
165
            $list[$t->id] = $t->name;
166
        }
167
168
        return $list;
169
    }
170
171
    /**
172
     * Get all file based content types.
173
     *
174
     * @return array content types
175
     */
176
    public static function getAllFileTypeIds()
177
    {
178
        $types = self::find()->all();
179
180
        return array_filter(array_map(function ($t) {
181
            return $t->input == self::KINDS['FILE'] ? $t->id : null;
182
        }, $types));
183
    }
184
185
    /**
186
     * Downloads content from URL through proxy if necessary.
187
     *
188
     * @param string $url
189
     *
190
     * @return string content
191
     */
192
    public static function downloadContent($url)
193
    {
194
        try {
195
            $http = [
196
                'timeout' => 10,
197
            ];
198
199
            if (\Yii::$app->params['proxy']) {
200
                $http += [
201
                    'proxy' => str_replace('http://', 'tcp://', \Yii::$app->params['proxy']),
202
                    'request_fulluri' => true,
203
                ];
204
            }
205
206
            return file_get_contents($url, false, stream_context_create(['http' => $http]));
207
        } catch (yii\base\ErrorException $e) {
208
            return '';
209
        }
210
    }
211
212
    /**
213
     * Check cache existence.
214
     *
215
     * @param string $key cache key
216
     *
217
     * @return bool has cached data
218
     */
219
    public function hasCache($key)
220
    {
221
        return \Yii::$app->cache->exists($this->id . $key);
222
    }
223
224
    /**
225
     * Get from cache.
226
     *
227
     * @param string $key cache key
228
     *
229
     * @return string cached data
230
     */
231
    public function fromCache($key)
232
    {
233
        $cache = \Yii::$app->cache;
234
        $cacheKey = $this->id . $key;
235
236
        return $cache->get($cacheKey);
237
    }
238
239
    /**
240
     * Store to cache.
241
     *
242
     * @param string $key     cache key
243
     * @param string $content cache data
244
     */
245
    public function toCache($key, $content)
246
    {
247
        $cache = \Yii::$app->cache;
248
        $cacheKey = $this->id . $key;
249
        $cache->set($cacheKey, $content, static::BASE_CACHE_TIME);
250
    }
251
252
    /**
253
     * @return \yii\db\ActiveQuery
254
     */
255
    public function getContents()
256
    {
257
        return $this->hasMany(Content::class, ['type_id' => 'id']);
258
    }
259
260
    /**
261
     * @return \yii\db\ActiveQuery
262
     */
263
    public function getFieldHasContentTypes()
264
    {
265
        return $this->hasMany(FieldHasContentType::class, ['content_type_id' => 'id']);
266
    }
267
268
    /**
269
     * @return \yii\db\ActiveQuery
270
     */
271
    public function getFields()
272
    {
273
        return $this->hasMany(Field::class, ['id' => 'field_id'])->viaTable('field_has_content_type', ['content_type_id' => 'id']);
274
    }
275
276
    /**
277
     * File management methods.
278
     */
279
280
    /**
281
     * Take a file instance and upload it to FS, also save in DB.
282
     *
283
     * @param \yii\web\UploadedFile|null $fileInstance
284
     *
285
     * @return bool|array error or json success string
286
     */
287
    public function upload($fileInstance)
288
    {
289
        return false;
290
    }
291
292
    /**
293
     * Take an url and download it, also save it in DB.
294
     *
295
     * @param string $url
296
     *
297
     * @return bool|array error or json success string
298
     */
299
    public function sideload($url)
300
    {
301
        return false;
302
    }
303
304
    /**
305
     * Custom error getter for upload/sideload temp file.
306
     *
307
     * @return string error
308
     */
309
    public function getLoadError()
310
    {
311
        return '';
312
    }
313
314
    /**
315
     * Transform data on beforeSave event.
316
     *
317
     * @param bool   $insert is inserted
318
     * @param string $data   content data
319
     *
320
     * @return string transformed data
321
     */
322
    public function transformDataBeforeSave($insert, $data)
323
    {
324
        return $data;
325
    }
326
}
327