Completed
Pull Request — master (#36)
by satoru
01:53
created

ContentsFileTrait::getContentsFile()   B

Complexity

Conditions 6
Paths 4

Size

Total Lines 38
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 38
rs 8.439
c 0
b 0
f 0
cc 6
eloc 25
nc 4
nop 2
1
<?php
2
3
namespace ContentsFile\Model\Entity;
4
5
use Cake\Utility\Security;
6
use Cake\ORM\TableRegistry;
7
use Cake\I18n\Time;
8
use ContentsFile\Aws\S3;
9
use Cake\Network\Exception\InternalErrorException;
10
use Cake\Core\Configure;
11
use Cake\Filesystem\File;
12
13
trait ContentsFileTrait
14
{
15
    private $contentsFileSettings = [];
16
17
    /**
18
     * contentsFileSettings
19
     * 設定値のセッティング
20
     *
21
     * @author hagiwara
22
     */
23
    private function contentsFileSettings()
24
    {
25
        $default = [];
26
        //設定値はまとめる
27
        $settings = $this->contentsFileConfig;
0 ignored issues
show
Bug introduced by
The property contentsFileConfig does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
28
        $this->contentsFileSettings = array_merge($default, $settings);
29
    }
30
31
    /**
32
     * getContentsFileSettings
33
     * 設定値のセッティングの取得
34
     *
35
     * @author hagiwara
36
     */
37
    public function getContentsFileSettings()
38
    {
39
        if (empty($this->contentsFileSettings)) {
40
            $this->contentsFileSettings();
41
        }
42
        return $this->contentsFileSettings;
43
    }
44
45
    /**
46
     * getContentsFile
47
     * ファイルのgetterのセッティング
48
     *
49
     * @author hagiwara
50
     * @param string $property
51
     * @param array $value
52
     */
53
    public function getContentsFile($property, $value)
54
    {
55
        $this->contentsFileSettings();
56
        if (
57
            //attachmentにデータが登録時のみ
58
            !empty($this->id) &&
59
            //設定値に設定されているとき
60
            preg_match('/^contents_file_(.*)$/', $property, $match) &&
61
            array_key_exists($match[1], $this->contentsFileSettings['fields'])
62
        ) {
63
            //何もセットされていないとき
64
            if (empty($this->_properties[$property])) {
65
                //attachmentからデータを探しに行く
66
                $attachmentModel = TableRegistry::get('Attachments');
67
                $attachmentData = $attachmentModel->find('all')
68
                    ->where(['model' => $this->source()])
0 ignored issues
show
Bug introduced by
It seems like source() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
69
                    ->where(['model_id' => $this->id])
0 ignored issues
show
Bug introduced by
The property id does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
70
                    ->where(['field_name' => $match[1]])
71
                    ->first()
72
                ;
73
                if (!empty($attachmentData)) {
74
                    $value = [
75
                        'model' => $attachmentData->model,
76
                        'model_id' => $attachmentData->model_id,
77
                        'field_name' => $attachmentData->field_name,
78
                        'file_name' => $attachmentData->file_name,
79
                        'file_content_type' => $attachmentData->file_content_type,
80
                        'file_size' => $attachmentData->file_size,
81
                        'file_random_path' => $attachmentData->file_random_path,
82
                    ];
83
                }
84
            } else {
85
                //それ以外はpropertiesの値を取得(setterで値を編集している場合はそれを反映するために必要)
86
                $value = $this->_properties[$property];
0 ignored issues
show
Bug introduced by
The property _properties does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
87
            }
88
        }
89
        return $value;
90
    }
91
92
    /**
93
     * setContentsFile
94
     * ファイルのsetterのセッティング
95
     *
96
     * @author hagiwara
97
     */
98
    public function setContentsFile()
99
    {
100
        $this->contentsFileSettings();
101
        foreach ($this->contentsFileSettings['fields'] as $field => $fieldSetting) {
102
            // 通常のパターン
103
            if (!array_key_exists('type', $fieldSetting) || $fieldSetting['type'] == 'normal') {
104
                $this->normalSetContentsFile($field, $fieldSetting);
105
            } else {
106
                $this->ddSetContentsFile($field, $fieldSetting);
107
            }
108
        }
109
        return $this;
110
    }
111
112
    /**
113
     * normalSetContentsFile
114
     * ファイルのsetterのセッティング
115
     *
116
     * @author hagiwara
117
     */
118
    private function normalSetContentsFile($field, $fieldSetting)
119
    {
120
            $fileInfo = $this->{$field};
121
            if (
122
                //ファイルの情報がある
123
                !empty($fileInfo) &&
124
                //エラーのフィールドがある=ファイルをアップロード中
125
                array_key_exists('error', $fileInfo) &&
126
                //空アップロード時は通さない(もともとのデータを活かす)
127
                $fileInfo['error'] != UPLOAD_ERR_NO_FILE
128
            ) {
129
                $fileSet = [
130
                    'model' => $this->source(),
0 ignored issues
show
Bug introduced by
It seems like source() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
131
                    'model_id' => $this->id,
132
                    'field_name' => $field,
133
                    'file_name' => $fileInfo['name'],
134
                    'file_content_type' => Configure::read('ContentsFile.Setting.type'),
135
                    'file_size' => $fileInfo['size'],
136
                    'file_error' => $fileInfo['error'],
137
                ];
138
139
                //$fileInfoにtmp_nameがいるときはtmpディレクトリへのファイルのコピーを行う
140
                if (!empty($fileInfo['tmp_name'])) {
141
                    $tmpFileName = Security::hash(rand() . Time::now()->i18nFormat('YYYY/MM/dd HH:ii:ss') . $fileInfo['name']);
142
143
                    if ($this->getExt($fileInfo['name']) !== null) {
144
                        $tmpFileName .= '.' . $this->getExt($fileInfo['name']);
145
                    }
146
147
                    // tmpディレクトリへのアップロードのエラー(パーミッションなど)
148
                    if (!$this->tmpUpload($fileInfo['tmp_name'], $fieldSetting, $tmpFileName)) {
149
                        throw new InternalErrorException('tmp upload error');
150
                    }
151
                    $fileSet['tmp_file_name'] = $tmpFileName;
152
                }
153
                //これを残して次に引き渡したくないので
154
                unset($this->{$field});
155
156
                $this->{'contents_file_' . $field} = $fileSet;
157
                $this->{'contents_file_' . $field . '_filename'} = $fileInfo['name'];
158
            }
159
    }
160
161
    /**
162
     * ddSetContentsFile
163
     * ファイルのsetterのセッティング
164
     *
165
     * @author hagiwara
166
     */
167
    private function ddSetContentsFile($field, $fieldSetting)
168
    {
169
170
        $fileInfo = $this->{$field};
171
        if (!empty($fileInfo)) {
172
            if (!preg_match('/^data:([^;]+);base64,(.+)$/', $fileInfo, $fileMatch)) {
173
                // ちゃんとファイルアップがないのでエラー
174
                throw new InternalErrorException('tmp upload erroar');
175
            }
176
            $filename = $this->{'contents_file_' . $field . '_filename'};
177
178
            $filebody = base64_decode($fileMatch[2]);
179
            $filesize = strlen($filebody);
180
181
            $tmpFileName = Security::hash(rand() . Time::now()->i18nFormat('YYYY/MM/dd HH:ii:ss') . $filename);
182
183
            if ($this->getExt($filename) !== null) {
184
                $tmpFileName .= '.' . $this->getExt($filename);
185
            }
186
            // まずは一時的にファイルを書き出す
187
            $ddTmpFileName = TMP . Security::hash(rand() . Time::now()->i18nFormat('YYYY/MM/dd HH:ii:ss') . $filename);
188
            $fp = new File($ddTmpFileName);
189
            $fp->write($filebody);
190
191
            // tmpディレクトリへのアップロードのエラー(パーミッションなど)
192
            if (!$this->tmpUpload($ddTmpFileName, $fieldSetting, $tmpFileName)) {
193
                throw new InternalErrorException('tmp upload error');
194
            }
195
            $fp->delete();
196
            $fp->close();
197
198
            $fileSet = [
199
                'model' => $this->source(),
0 ignored issues
show
Bug introduced by
It seems like source() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
200
                'model_id' => $this->id,
201
                'field_name' => $field,
202
                'file_name' => $filename,
203
                'file_content_type' => Configure::read('ContentsFile.Setting.type'),
204
                'file_size' => $filesize,
205
                'file_error' => 0,
206
            ];
207
208
            $fileSet['tmp_file_name'] = $tmpFileName;
209
210
            //これを残して次に引き渡したくないので
211
            unset($this->{$field});
212
213
            $this->{'contents_file_' . $field} = $fileSet;
214
            $this->{'contents_file_' . $field . '_filename'} = $filename;
215
        }
216
    }
217
218
    /**
219
     * getExt
220
     * 拡張子の取得
221
     *
222
     * @author hagiwara
223
     * @param string $file
224
     */
225
    private function getExt($file)
226
    {
227
        $fileExplode = explode('.', $file);
228
        //この場合拡張子なし
229
        if (count($fileExplode) == 1) {
230
            return null;
231
        }
232
        return $fileExplode[(count($fileExplode) - 1)];
233
    }
234
235
    /**
236
     * tmpUpload
237
     * tmpディレクトリへのアップロード
238
     *
239
     * @author hagiwara
240
     * @param string $tmpFileName
241
     * @param array $fieldSetting
242
     * @param string $tmpFileName
243
     */
244
    private function tmpUpload($tmpName, $fieldSetting, $tmpFileName)
0 ignored issues
show
Unused Code introduced by
The parameter $fieldSetting is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
245
    {
246
        // すでにtraitのため、ここはif文での分岐処理
247
        if (Configure::read('ContentsFile.Setting.type') == 'normal') {
248
            return copy($tmpName, Configure::read('ContentsFile.Setting.Normal.tmpDir') . $tmpFileName);
249
        } elseif (Configure::read('ContentsFile.Setting.type') == 's3') {
250
            $uploadFileName = Configure::read('ContentsFile.Setting.S3.tmpDir') . $tmpFileName;
251
            $S3 = new S3();
252
            return $S3->upload($tmpName, $uploadFileName);
253
        } else {
254
            throw new InternalErrorException('contentsFileConfig type illegal');
255
        }
256
    }
257
}
258