Completed
Push — master ( 8e3af1...9c2c26 )
by satoru
01:52
created

S3ContentsFileBehaviorTrait::s3FileSave()   C

Complexity

Conditions 7
Paths 16

Size

Total Lines 35
Code Lines 19

Duplication

Lines 12
Ratio 34.29 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 12
loc 35
rs 6.7272
c 1
b 0
f 0
cc 7
eloc 19
nc 16
nop 3
1
<?php
2
3
namespace ContentsFile\Model\Behavior\Traits;
4
5
use ContentsFile\Aws\S3;
6
use Cake\Core\Configure;
7
use Cake\Filesystem\Folder;
8
use Cake\I18n\Time;
9
use Cake\Network\Exception\InternalErrorException;
10
use Cake\ORM\TableRegistry;
11
use Cake\Utility\Security;
12
13
/**
14
 * S3ContentsFileBehaviorTrait
15
 * 通常のファイルアップ系の処理
16
 * メソッド名の先頭に必ずs3を付けること
17
 */
18
trait S3ContentsFileBehaviorTrait
19
{
20
21
    /**
22
     * s3ParamCheck
23
     * 通常の設定値チェック
24
     * @author hagiwara
25
     */
26
    private function s3ParamCheck()
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
27
    {
28
        // S3に必要な設定がそろっているかチェックする
29
        $s3Setting = Configure::read('ContentsFile.Setting.S3');
30 View Code Duplication
        if (
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...
31
            !is_array($s3Setting) ||
32
            !array_key_exists('key', $s3Setting) ||
33
            !array_key_exists('secret', $s3Setting) ||
34
            !array_key_exists('bucket', $s3Setting) ||
35
            !array_key_exists('tmpDir', $s3Setting) ||
36
            !array_key_exists('fileDir', $s3Setting) ||
37
            !array_key_exists('workingDir', $s3Setting)
38
39
        ) {
40
            throw new InternalErrorException('contentsFileS3Config paramater shortage');
41
        }
42
43
        // /が最後についていない場合はつける
44
        if (!preg_match('#/$#', $s3Setting['tmpDir'])) {
45
            Configure::write('ContentsFile.Setting.S3.tmpDir', $s3Setting['tmpDir'] . '/');
46
        }
47
        if (!preg_match('#/$#', $s3Setting['fileDir'])) {
48
            Configure::write('ContentsFile.Setting.S3.fileDir', $s3Setting['fileDir'] . '/');
49
        }
50
        if (!preg_match('#/$#', $s3Setting['workingDir'])) {
51
            Configure::write('ContentsFile.Setting.S3.workingDir', $s3Setting['workingDir'] . '/');
52
        }
53
    }
54
55
    /**
56
     * s3FileSave
57
     * ファイルをS3に保存
58
     * @author hagiwara
59
     * @param array $fileInfo
60
     * @param array $fieldSettings
61
     * @param array $attachmentSaveData
62
     */
63
    private function s3FileSave($fileInfo, $fieldSettings, $attachmentSaveData)
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
64
    {
65
        $S3 = new S3();
66
        $newFiledir = Configure::read('ContentsFile.Setting.S3.fileDir') . $attachmentSaveData['model'] . '/' . $attachmentSaveData['model_id'] . '/';
67 View Code Duplication
        if (Configure::read('ContentsFile.Setting.randomFile') === true) {
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...
68
            $newFilepath = $newFiledir . $attachmentSaveData['file_random_path'];
69
        } else {
70
            $newFilepath = $newFiledir . $fileInfo['field_name'];
71
        }
72
        if (Configure::read('ContentsFile.Setting.ext') === true) {
73
            $ext = (new \SplFileInfo($attachmentSaveData['file_name']))->getExtension();
74
            $newFilepath .= '.' . $ext;
75
        }
76
        $oldFilepath = Configure::read('ContentsFile.Setting.S3.tmpDir') . $fileInfo['tmp_file_name'];
77
78
        // 該当ファイルを消す
79
        // 失敗=ディレクトリが存在しないため、成功失敗判定は行わない。
80
        $this->s3FileDelete($attachmentSaveData['model'], $attachmentSaveData['model_id'], $fileInfo['field_name']);
81
82
        // tmpに挙がっているファイルを移
83
        if (!$S3->move($oldFilepath, $newFilepath)) {
84
            return false;
85
        }
86
87
88
        //リサイズ画像作成
89 View Code Duplication
        if (!empty($fieldSettings['resize'])) {
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...
90
            foreach ($fieldSettings['resize'] as $resizeSettings) {
91
                if (!$this->s3ImageResize($newFilepath, $resizeSettings)) {
92
                    return false;
93
                }
94
            }
95
        }
96
        return true;
97
    }
98
99
    /**
100
     * s3FileDelete
101
     * S3のファイル削除
102
     * @author hagiwara
103
     * @param string $modelName
104
     * @param integer $modelId
105
     * @param string $field
106
     */
107
    private function s3FileDelete($modelName, $modelId, $field)
108
    {
109
        //attachementからデータを取得
110
        $attachmentModel = TableRegistry::get('Attachments');
111
        $attachmentData = $attachmentModel->find('all')
112
            ->where(['model' => $modelName])
113
            ->where(['model_id' => $modelId])
114
            ->where(['field_name' => $field])
115
            ->first()
116
        ;
117
        // 削除するべきファイルがない
118
        if (empty($attachmentData)) {
119
            return false;
120
        }
121 View Code Duplication
        if (Configure::read('ContentsFile.Setting.randomFile') === true && $attachmentData->file_random_path != '') {
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...
122
            $deleteField = $attachmentData->file_random_path;
123
        } else {
124
            $deleteField = $attachmentData->field_name;
125
        }
126
127
       $S3 = new S3();
128
        // リサイズのディレクトリ
129
        $resizeDir = Configure::read('ContentsFile.Setting.S3.fileDir') . $modelName . '/' . $modelId . '/' . 'contents_file_resize_' . $deleteField . '/';
130
        if (!$S3->deleteRecursive($resizeDir)) {
131
            return false;
132
        }
133
134
        // 大元のファイル
135
        $deleteFile = Configure::read('ContentsFile.Setting.S3.fileDir') . $modelName . '/' . $modelId . '/' . $deleteField;
136
        if (Configure::read('ContentsFile.Setting.ext') === true) {
137
            $ext = (new \SplFileInfo($attachmentData->file_name))->getExtension();
138
            $deleteFile .= '.' . $ext;
139
        }
140
        if (!$S3->delete($deleteFile)) {
141
            return false;
142
        }
143
        return true;
144
    }
145
146
    /**
147
     * s3ImageResize
148
     * 画像のリサイズ処理(S3用)
149
     * @author hagiwara
150
     * @param string $filepath
151
     * @param array $resize
152
     */
153
    public function s3ImageResize($filepath, $resize)
154
    {
155
        $imagepathinfo = $this->getPathinfo($filepath, $resize);
0 ignored issues
show
Bug introduced by
It seems like getPathinfo() 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...
156
        $S3 = new S3();
157
        // Exception = 存在していない場合
158
        $tmpFileName = Security::hash(rand() . Time::now()->i18nFormat('YYYY/MM/dd HH:ii:ss'));
159
        $tmpPath = Configure::read('ContentsFile.Setting.S3.workingDir') . $tmpFileName;
160
        // ベースのファイルを取得
161
        $baseObject = $S3->download($filepath);
162
        $fp = fopen($tmpPath, 'w');
163
        fwrite($fp, $baseObject['Body']);
164
        fclose($fp);
165
        if (!$this->imageResize($tmpPath, $resize)) {
0 ignored issues
show
Bug introduced by
The method imageResize() does not exist on ContentsFile\Model\Behav...ntentsFileBehaviorTrait. Did you maybe mean s3ImageResize()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
166
            //失敗時はそのままのパスを返す(画像以外の可能性あり)
167
            unlink($tmpPath);
168
            return $filepath;
169
        }
170
        $resizeFileDir = Configure::read('ContentsFile.Setting.S3.workingDir') . 'contents_file_resize_' . $tmpFileName;
171
        $resizeFolder = new Folder($resizeFileDir);
172
        // 一つのはず
173
        $resizeImg = $resizeFolder->findRecursive()[0];
174
175
        // リサイズ画像をアップロード
176
        $S3->upload($resizeImg, $imagepathinfo['resize_filepath']);
177
178
        // tmpディレクトリの不要なディレクトリ/ファイルを削除
179
        $resizeFolder->delete();
180
        unlink($tmpPath);
181
        return $imagepathinfo['resize_filepath'];
182
    }
183
184
}
185