Completed
Push — master ( 9f512c...f454b5 )
by Jeff
11:54
created

Content::getData()   B

Complexity

Conditions 5
Paths 9

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 18
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 10
nc 9
nop 0
1
<?php
2
3
namespace app\models;
4
5
use Yii;
6
7
/**
8
 * This is the model class for table "content".
9
 *
10
 * @property int $id
11
 * @property string $name
12
 * @property string $description
13
 * @property int $flow_id
14
 * @property string $type_id
15
 * @property string $data
16
 * @property int $duration
17
 * @property string $start_ts
18
 * @property string $end_ts
19
 * @property string $add_ts
20
 * @property bool $enabled
21
 * @property Flow $flow
22
 * @property ContentType $type
23
 */
24
class Content extends \yii\db\ActiveRecord
25
{
26
    /**
27
     * {@inheritdoc}
28
     */
29
    public static function tableName()
30
    {
31
        return 'content';
32
    }
33
34
    /**
35
     * {@inheritdoc}
36
     */
37
    public function rules()
38
    {
39
        return array_merge([
40
            [['name', 'flow_id', 'type_id'], 'required'],
41
            [['flow_id', 'duration'], 'integer'],
42
            [['data'], 'string'],
43
            [['start_ts', 'end_ts', 'add_ts'], 'safe'],
44
            [['enabled'], 'boolean'],
45
            [['name'], 'string', 'max' => 64],
46
            [['type_id'], 'string', 'max' => 45],
47
            [['description'], 'string', 'max' => 1024],
48
            [['flow_id'], 'exist', 'skipOnError' => true, 'targetClass' => Flow::className(), 'targetAttribute' => ['flow_id' => 'id']],
49
            [['type_id'], 'exist', 'skipOnError' => true, 'targetClass' => ContentType::className(), 'targetAttribute' => ['type_id' => 'id']],
50
        ], $this->type ? $this->type->contentRules() : []);
51
    }
52
53
    /**
54
     * {@inheritdoc}
55
     */
56
    public function attributeLabels()
57
    {
58
        return array_merge([
59
            'id' => Yii::t('app', 'ID'),
60
            'name' => Yii::t('app', 'Name'),
61
            'description' => Yii::t('app', 'Description'),
62
            'flow_id' => Yii::t('app', 'Flow'),
63
            'type_id' => Yii::t('app', 'Type'),
64
            'data' => Yii::t('app', 'Content'),
65
            'duration' => Yii::t('app', 'Duration in seconds'),
66
            'start_ts' => Yii::t('app', 'Start at'),
67
            'end_ts' => Yii::t('app', 'End on'),
68
            'add_ts' => Yii::t('app', 'Added at'),
69
            'enabled' => Yii::t('app', 'Enabled'),
70
        ], $this->type ? $this->type->contentLabels() : []);
71
    }
72
73
    /**
74
     * @return \yii\db\ActiveQuery
75
     */
76
    public function getFlow()
77
    {
78
        return $this->hasOne(Flow::className(), ['id' => 'flow_id']);
79
    }
80
81
    /**
82
     * @return \yii\db\ActiveQuery
83
     */
84
    public function getType()
85
    {
86
        return $this->hasOne(ContentType::className(), ['id' => 'type_id']);
87
    }
88
89
    /**
90
     * Build a query for a specific user, allowing to see only authorized contents.
91
     *
92
     * @param \yii\web\User $user
93
     *
94
     * @return \yii\db\ActiveQuery
95
     */
96
    public static function availableQuery($user)
97
    {
98
        if ($user->can('setFlowContent')) {
99
            return self::find()->joinWith(['type']);
100 View Code Duplication
        } elseif ($user->can('setOwnFlowContent') && $user->identity instanceof \app\models\User) {
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...
101
            return self::find()->joinWith(['type', 'flow.users'])->where(['username' => $user->identity->username]);
102
        }
103
    }
104
105
    /**
106
     * Check if a specific user is allowed to see this content.
107
     *
108
     * @param \yii\web\User $user
109
     *
110
     * @return bool can see
111
     */
112 View Code Duplication
    public function canView($user)
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...
113
    {
114
        if ($user->can('setFlowContent')) {
115
            return true;
116
        }
117
        if ($user->can('setOwnFlowContent') && in_array($user->identity, $this->flow->users)) {
118
            return true;
119
        }
120
121
        return false;
122
    }
123
124
    /**
125
     * Get raw data and transform it to content type specific needs.
126
     *
127
     * @param string $data
128
     *
129
     * @return string transformed data
130
     */
131
    public function processData($data)
132
    {
133
        return $this->type->processData($data);
134
    }
135
136
    /**
137
     * Retrieve data for content
138
     * Transforming it if necessary (mostly urls).
139
     *
140
     * @return string|null usable data
141
     */
142
    public function getData()
143
    {
144
        $data = $this->data;
145
        if ($this->type->appendParams) {
146
            $data .= (strpos($data, '#') === false ? '#' : ';').$this->type->appendParams;
147
        }
148
149
        $data = $this->processData($data);
150
        if ($data === null) {
151
            return null;
152
        }
153
154
        if ($this->type->html) {
155
            return str_replace('%data%', $data, $this->type->html);
156
        }
157
158
        return $data;
159
    }
160
161
    public function beforeSave($insert)
162
    {
163
        if (!parent::beforeSave($insert)) {
164
            return false;
165
        }
166
167
        $res = $this->type->transformDataBeforeSave($insert, $this->data);
168
        if ($res == null) {
169
            return false;
170
        }
171
172
        $this->data = $res;
173
174
        return true;
175
    }
176
177
    /**
178
     * After delete event
179
     * Try to delete file if necessary.
180
     */
181
    public function afterDelete()
182
    {
183
        if ($this->shouldDeleteFile()) {
184
            unlink($this->getRealFilepath());
185
        }
186
        parent::afterDelete();
187
    }
188
189
    /**
190
     * Decide if content file should be deleted by checking usage in DB.
191
     *
192
     * @return bool deletable
193
     */
194
    protected function shouldDeleteFile()
195
    {
196
        if ($this->type->input == ContentType::KINDS['FILE']) {
197
            return self::find()
198
                ->joinWith(['type'])
199
                ->where([ContentType::tableName().'.id' => ContentType::getAllFileTypeIds()])
200
                ->andWhere(['data' => $this->data])
201
                ->count() == 0;
202
        }
203
204
        return false;
205
    }
206
207
    /**
208
     * Get filepath from web root.
209
     *
210
     * @return string filepath
211
     */
212
    public function getFilepath()
213
    {
214
        $type = $this->type;
215
216
        return str_replace($type::BASE_URI, '', $this->getWebFilepath());
217
    }
218
219
    /**
220
     * Get Yii aliased filepath.
221
     *
222
     * @return string filepath
223
     */
224
    public function getWebFilepath()
225
    {
226
        return $this->data;
227
    }
228
229
    /**
230
     * Get filesystem filepath.
231
     *
232
     * @return string filepath
233
     */
234
    public function getRealFilepath()
235
    {
236
        return \Yii::getAlias('@app/').'web/'.$this->getFilepath();
237
    }
238
}
239