Completed
Push — master ( ec2cdb...73e231 )
by Jeff
04:58
created

ContentType::processData()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
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
            'name' => Yii::t('app', 'Type'),
74
            'description' => 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 raw data and transform it to content type specific needs.
119
     *
120
     * @param string $data
121
     *
122
     * @return string transformed data
123
     */
124
    public function processData($data)
125
    {
126
        return $data;
127
    }
128
129
    /**
130
     * Get all filtered content types.
131
     *
132
     * @param bool $selfUpdate does content type manages itself
133
     * @param bool $usableOnly show only usable content types
134
     *
135
     * @return array content types
136
     */
137
    public static function getAll($selfUpdate = null, $usableOnly = true)
138
    {
139
        $types = self::find()->all();
140
141
        return array_filter($types, function ($t) use ($selfUpdate, $usableOnly) {
142
            return ($selfUpdate === null || $t->selfUpdate == $selfUpdate) && (!$usableOnly || $t->usable);
143
        });
144
    }
145
146
    /**
147
     * Get all filterd content types in array.
148
     *
149
     * @param bool $selfUpdate does content type manages itself
150
     * @param bool $usableOnly show only usable content types
151
     *
152
     * @return array content types
153
     */
154
    public static function getAllList($selfUpdate = null, $usableOnly = true)
155
    {
156
        $types = self::getAll($selfUpdate, $usableOnly);
157
158
        $list = [];
159
160
        foreach ($types as $t) {
161
            $list[$t->id] = $t->name;
162
        }
163
164
        return $list;
165
    }
166
167
    /**
168
     * Get all file based content types.
169
     *
170
     * @return array content types
171
     */
172
    public static function getAllFileTypeIds()
173
    {
174
        $types = self::find()->all();
175
176
        return array_filter(array_map(function ($t) {
177
            return $t->input == self::KINDS['FILE'] ? $t->id : null;
178
        }, $types));
179
    }
180
181
    /**
182
     * Downloads content from URL through proxy if necessary.
183
     *
184
     * @param string $url
185
     *
186
     * @return string content
187
     */
188
    public static function downloadContent($url)
189
    {
190
        if (\Yii::$app->params['proxy']) {
191
            $ctx = [
192
                'http' => [
193
                    'proxy' => 'tcp://vdebian:8080',
194
                    'request_fulluri' => true,
195
                ],
196
            ];
197
198
            return file_get_contents($url, false, stream_context_create($ctx));
199
        } else {
200
            return file_get_contents($url);
201
        }
202
    }
203
204
    /**
205
     * Check cache existence.
206
     *
207
     * @param string $key cache key
208
     *
209
     * @return bool has cached data
210
     */
211
    public function hasCache($key)
212
    {
213
        return \Yii::$app->cache->exists($this->id.$key);
214
    }
215
216
    /**
217
     * Get from cache.
218
     *
219
     * @param string $key cache key
220
     *
221
     * @return string cached data
222
     */
223
    public function fromCache($key)
224
    {
225
        $cache = \Yii::$app->cache;
226
        $cacheKey = $this->id.$key;
227
        if ($cache->exists($cacheKey)) {
228
            return $cache->get($cacheKey);
229
        }
230
    }
231
232
    /**
233
     * Store to cache.
234
     *
235
     * @param string $key     cache key
236
     * @param string $content cache data
237
     */
238
    public function toCache($key, $content)
239
    {
240
        $cache = \Yii::$app->cache;
241
        $cacheKey = $this->id.$key;
242
        $cache->set($cacheKey, $content, static::BASE_CACHE_TIME);
243
    }
244
245
    /**
246
     * @return \yii\db\ActiveQuery
247
     */
248
    public function getContents()
249
    {
250
        return $this->hasMany(Content::className(), ['type_id' => 'id']);
251
    }
252
253
    /**
254
     * @return \yii\db\ActiveQuery
255
     */
256
    public function getFieldHasContentTypes()
257
    {
258
        return $this->hasMany(FieldHasContentType::className(), ['content_type_id' => 'id']);
259
    }
260
261
    /**
262
     * @return \yii\db\ActiveQuery
263
     */
264
    public function getFields()
265
    {
266
        return $this->hasMany(Field::className(), ['id' => 'field_id'])->viaTable('field_has_content_type', ['content_type_id' => 'id']);
267
    }
268
269
    /**
270
     * File management methods.
271
     */
272
273
    /**
274
     * Take a file instance and upload it to FS, also save in DB.
275
     *
276
     * @param \FileInstance $fileInstance
277
     *
278
     * @return bool|array error or json success string
279
     */
280
    public function upload($fileInstance)
281
    {
282
        return false;
283
    }
284
285
    /**
286
     * Take an url and download it, also save it in DB.
287
     *
288
     * @param string $url
289
     *
290
     * @return bool|array error or json success string
291
     */
292
    public function sideload($url)
293
    {
294
        return false;
295
    }
296
297
    /**
298
     * Custom error getter for upload/sideload temp file.
299
     *
300
     * @return string error
301
     */
302
    public function getLoadError()
303
    {
304
        return '';
305
    }
306
307
    /**
308
     * Transform data on beforeSave event
309
     *
310
     * @param bool $insert is inserted
311
     * @param string $data content data
312
     *
313
     * @return string transformed data
314
     */
315
    public function transformDataBeforeSave($insert, $data)
316
    {
317
        return $data;
318
    }
319
}
320