Completed
Pull Request — master (#26)
by satoru
02:14
created

S3ContentsFileBehaviorTrait::s3ImageResize()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 30
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 30
rs 8.8571
cc 2
eloc 19
nc 2
nop 2
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
        $oldFilepath = Configure::read('ContentsFile.Setting.S3.tmpDir') . $fileInfo['tmp_file_name'];
73
74
        // 該当ファイルを消す
75
        // 失敗=ディレクトリが存在しないため、成功失敗判定は行わない。
76
        $this->s3FileDelete($attachmentSaveData['model'], $attachmentSaveData['model_id'], $fileInfo['field_name']);
77
78
        // tmpに挙がっているファイルを移
79
        if (!$S3->move($oldFilepath, $newFilepath)) {
80
            return false;
81
        }
82
83
84
        //リサイズ画像作成
85 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...
86
            foreach ($fieldSettings['resize'] as $resizeSettings) {
87
                if (!$this->s3ImageResize($newFilepath, $resizeSettings)) {
88
                    return false;
89
                }
90
            }
91
        }
92
        return true;
93
    }
94
95
    /**
96
     * s3FileDelete
97
     * S3のファイル削除
98
     * @author hagiwara
99
     * @param string $modelName
100
     * @param integer $modelId
101
     * @param string $field
102
     */
103
    private function s3FileDelete($modelName, $modelId, $field)
104
    {
105
        //attachementからデータを取得
106
        $attachmentModel = TableRegistry::get('Attachments');
107
        $attachmentData = $attachmentModel->find('all')
108
            ->where(['model' => $modelName])
109
            ->where(['model_id' => $modelId])
110
            ->where(['field_name' => $field])
111
            ->first()
112
        ;
113
        // 削除するべきファイルがない
114
        if (empty($attachmentData)) {
115
            return false;
116
        }
117 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...
118
            $deleteField = $attachmentData->file_random_path;
119
        } else {
120
            $deleteField = $attachmentData->field_name;
121
        }
122
123
       $S3 = new S3();
124
        // リサイズのディレクトリ
125
        $resizeDir = Configure::read('ContentsFile.Setting.S3.fileDir') . $modelName . '/' . $modelId . '/' . 'contents_file_resize_' . $deleteField . '/';
126
        if (!$S3->deleteRecursive($resizeDir)) {
127
            return false;
128
        }
129
130
        // 大元のファイル
131
        $deleteFile = Configure::read('ContentsFile.Setting.S3.fileDir') . $modelName . '/' . $modelId . '/' . $deleteField;
132
        if (!$S3->delete($deleteFile)) {
133
            return false;
134
        }
135
        return true;
136
    }
137
138
    /**
139
     * s3ImageResize
140
     * 画像のリサイズ処理(S3用)
141
     * @author hagiwara
142
     * @param string $filepath
143
     * @param array $resize
144
     */
145
    public function s3ImageResize($filepath, $resize)
146
    {
147
        $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...
148
        $S3 = new S3();
149
        // Exception = 存在していない場合
150
        $tmpFileName = Security::hash(rand() . Time::now()->i18nFormat('YYYY/MM/dd HH:ii:ss'));
151
        $tmpPath = Configure::read('ContentsFile.Setting.S3.workingDir') . $tmpFileName;
152
        // ベースのファイルを取得
153
        $baseObject = $S3->download($filepath);
154
        $fp = fopen($tmpPath, 'w');
155
        fwrite($fp, $baseObject['Body']);
156
        fclose($fp);
157
        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...
158
            //失敗時はそのままのパスを返す(画像以外の可能性あり)
159
            unlink($tmpPath);
160
            return $filepath;
161
        }
162
        $resizeFileDir = Configure::read('ContentsFile.Setting.S3.workingDir') . 'contents_file_resize_' . $tmpFileName;
163
        $resizeFolder = new Folder($resizeFileDir);
164
        // 一つのはず
165
        $resizeImg = $resizeFolder->findRecursive()[0];
166
167
        // リサイズ画像をアップロード
168
        $S3->upload($resizeImg, $imagepathinfo['resize_filepath']);
169
170
        // tmpディレクトリの不要なディレクトリ/ファイルを削除
171
        $resizeFolder->delete();
172
        unlink($tmpPath);
173
        return $imagepathinfo['resize_filepath'];
174
    }
175
176
}
177