Completed
Push — master ( 6fdefe...ec2cdb )
by Jeff
04:37 queued 01:52
created

ContentType::fromType()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 9
rs 9.6666
cc 2
eloc 5
nc 2
nop 1
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 Content[] $contents
12
 * @property FieldHasContentType[] $fieldHasContentTypes
13
 * @property Field[] $fields
14
 */
15
class ContentType extends \yii\db\ActiveRecord
16
{
17
    const BASE_CACHE_TIME = 3600;
18
    const SUB_PATH = 'app\\models\\types\\';
19
20
    public $name;
21
    public $description;
22
    public $html;
23
    public $css;
24
    public $js;
25
    public $appendParams;
26
    public $selfUpdate;
27
    public $input;
28
    public $output;
29
    public $usable;
30
    public $preview;
31
    public $canPreview;
32
33
    const KINDS = [
34
        'NONE' => 'none',
35
        'RAW' => 'raw',
36
        'URL' => 'url',
37
        'FILE' => 'file',
38
        'TEXT' => 'text',
39
        'POS' => 'latlong',
40
    ];
41
42
    /**
43
     * {@inheritdoc}
44
     */
45
    public static function tableName()
46
    {
47
        return 'content_type';
48
    }
49
50
    /**
51
     * {@inheritdoc}
52
     */
53 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...
54
    {
55
        return [
56
            [['id'], 'required'],
57
            [['id'], 'string', 'max' => 45],
58
        ];
59
    }
60
61
    public function contentRules()
62
    {
63
        return [];
64
    }
65
66
    /**
67
     * {@inheritdoc}
68
     */
69
    public function attributeLabels()
70
    {
71
        return [
72
            'id' => Yii::t('app', 'ID'),
73
            'tName' => Yii::t('app', 'Type'),
74
            'tDescription' => Yii::t('app', 'Description'),
75
            'html' => Yii::t('app', 'HTML'),
76
            'css' => Yii::t('app', 'CSS'),
77
            'js' => Yii::t('app', 'JS'),
78
        ];
79
    }
80
81
    public function contentLabels()
82
    {
83
        return [];
84
    }
85
86
    /**
87
     * Get class from content type ID.
88
     *
89
     * @param string $typeId content type id
90
     *
91
     * @return string class name
92
     */
93
    public static function fromType($typeId)
94
    {
95
        $className = self::SUB_PATH.$typeId;
96
        if (!class_exists($className)) {
97
            throw new ServerErrorHttpException(Yii::t('app', 'The requested content type has no class.'));
98
        }
99
100
        return $className;
101
    }
102
103
    /**
104
     * Overload default instantiate to fill attributes from specific content type.
105
     *
106
     * @param array $row
107
     *
108
     * @return array transformed row
109
     */
110
    public static function instantiate($row)
111
    {
112
        $typeClass = self::fromType($row['id']);
113
114
        return new $typeClass();
115
    }
116
117
    /**
118
     * Get all filtered content types.
119
     *
120
     * @param bool $selfUpdate does content type manages itself
121
     * @param bool $usableOnly show only usable content types
122
     *
123
     * @return array content types
124
     */
125
    public static function getAll($selfUpdate = null, $usableOnly = true)
126
    {
127
        $types = self::find()->all();
128
129
        return array_filter($types, function ($t) use ($selfUpdate, $usableOnly) {
130
            return ($selfUpdate === null || $t->selfUpdate == $selfUpdate) && (!$usableOnly || $t->usable);
131
        });
132
    }
133
134
    /**
135
     * Get all filterd content types in array.
136
     *
137
     * @param bool $selfUpdate does content type manages itself
138
     * @param bool $usableOnly show only usable content types
139
     *
140
     * @return array content types
141
     */
142
    public static function getAllList($selfUpdate = null, $usableOnly = true)
143
    {
144
        $types = self::getAll($selfUpdate, $usableOnly);
145
146
        $list = [];
147
148
        foreach ($types as $t) {
149
            $list[$t->id] = $t->tName;
150
        }
151
152
        return $list;
153
    }
154
155
    /**
156
     * Get all file based content types.
157
     *
158
     * @return array content types
159
     */
160
    public static function getAllFileTypeIds()
161
    {
162
        $types = self::find()->all();
163
164
        return array_filter(array_map(function ($t) {
165
            return $t->input == self::KINDS['FILE'] ? $t->id : null;
166
        }, $types));
167
    }
168
169
    /**
170
     * Downloads content from URL through proxy if necessary.
171
     *
172
     * @param string $url
173
     *
174
     * @return string content
175
     */
176
    public static function downloadContent($url)
177
    {
178
        if (\Yii::$app->params['proxy']) {
179
            $ctx = [
180
                'http' => [
181
                    'proxy' => 'tcp://vdebian:8080',
182
                    'request_fulluri' => true,
183
                ],
184
            ];
185
186
            return file_get_contents($url, false, stream_context_create($ctx));
187
        } else {
188
            return file_get_contents($url);
189
        }
190
    }
191
192
    /**
193
     * Check cache existence.
194
     *
195
     * @param string $key cache key
196
     *
197
     * @return bool has cached data
198
     */
199
    public function hasCache($key)
200
    {
201
        return \Yii::$app->cache->exists($this->id.$key);
202
    }
203
204
    /**
205
     * Get from cache.
206
     *
207
     * @param string $key cache key
208
     *
209
     * @return string cached data
210
     */
211
    public function fromCache($key)
212
    {
213
        $cache = \Yii::$app->cache;
214
        $cacheKey = $this->id.$key;
215
        if ($cache->exists($cacheKey)) {
216
            return $cache->get($cacheKey);
217
        }
218
    }
219
220
    /**
221
     * Store to cache.
222
     *
223
     * @param string $key     cache key
224
     * @param string $content cache data
225
     */
226
    public function toCache($key, $content)
227
    {
228
        $cache = \Yii::$app->cache;
229
        $cacheKey = $this->id.$key;
230
        $cache->set($cacheKey, $content, static::BASE_CACHE_TIME);
231
    }
232
233
    /**
234
     * @return \yii\db\ActiveQuery
235
     */
236
    public function getContents()
237
    {
238
        return $this->hasMany(Content::className(), ['type_id' => 'id']);
239
    }
240
241
    /**
242
     * @return \yii\db\ActiveQuery
243
     */
244
    public function getFieldHasContentTypes()
245
    {
246
        return $this->hasMany(FieldHasContentType::className(), ['content_type_id' => 'id']);
247
    }
248
249
    /**
250
     * @return \yii\db\ActiveQuery
251
     */
252
    public function getFields()
253
    {
254
        return $this->hasMany(Field::className(), ['id' => 'field_id'])->viaTable('field_has_content_type', ['content_type_id' => 'id']);
255
    }
256
257
    /**
258
     * Get translated content type name.
259
     *
260
     * @return string name
261
     */
262
    public function getTName()
263
    {
264
        return \Yii::t('app', $this->name);
265
    }
266
267
    /**
268
     * Get translated content type description.
269
     *
270
     * @return string description
271
     */
272
    public function getTDescription()
273
    {
274
        return \Yii::t('app', $this->description);
275
    }
276
277
    /**
278
     * File management methods.
279
     */
280
281
    /**
282
     * Take a file instance and upload it to FS, also save in DB.
283
     *
284
     * @param \FileInstance $fileInstance
0 ignored issues
show
Bug introduced by
There is no parameter named $fileInstance. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
285
     *
286
     * @return bool success
287
     */
288
    public function upload()
289
    {
290
        return false;
291
    }
292
293
    /**
294
     * Take an url and download it, also save it in DB.
295
     *
296
     * @param string $url
0 ignored issues
show
Bug introduced by
There is no parameter named $url. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
297
     *
298
     * @return bool|string[] error or json success string
299
     */
300
    public function sideload()
301
    {
302
        return false;
303
    }
304
305
    /**
306
     * Custom error getter for upload/sideload temp file.
307
     *
308
     * @return string error
309
     */
310
    public function getLoadError()
311
    {
312
        return '';
313
    }
314
315
    /**
316
     * Before save event
317
     * Handles file movement from tmp directory to proper media storage
318
     * Makes sure there is no overwrite by appending to filename.
319
     *
320
     * @param bool $insert is inserted
0 ignored issues
show
Bug introduced by
There is no parameter named $insert. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
321
     *
322
     * @return bool success
323
     */
324
    public function beforeSaveContent()
325
    {
326
        return true;
327
    }
328
}
329