Completed
Push — master ( ff3359...a874a2 )
by satoru
10s
created

ContentsFileController::loader()   C

Complexity

Conditions 8
Paths 9

Size

Total Lines 52
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 52
rs 6.8493
cc 8
eloc 31
nc 9
nop 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace ContentsFile\Controller;
4
5
use Cake\Core\Configure;
6
use Cake\ORM\TableRegistry;
7
use Cake\Utility\Inflector;
8
use Cake\Network\Exception\NotFoundException;
9
use ContentsFile\Controller\AppController;
10
use ContentsFile\Controller\Traits\NormalContentsFileControllerTrait;
11
use ContentsFile\Controller\Traits\S3ContentsFileControllerTrait;
12
13
class ContentsFileController extends AppController
14
{
15
    use S3ContentsFileControllerTrait;
16
    use NormalContentsFileControllerTrait;
17
    private $baseModel;
18
19
    /**
20
     * initialize
21
     * Configureの最後のスラッシュの設定
22
     */
23
    public function initialize()
24
    {
25
        parent::initialize();
26
        // /が最後についていない場合はつける
27
        if (!preg_match('#/$#', Configure::read('ContentsFile.Setting.Normal.tmpDir'))) {
28
            Configure::write('ContentsFile.Setting.Normal.tmpDir', Configure::read('ContentsFile.Setting.Normal.tmpDir') . '/');
29
        }
30
        if (!preg_match('#/$#', Configure::read('ContentsFile.Setting.Normal.fileDir'))) {
31
            Configure::write('ContentsFile.Setting.Normal.fileDir', Configure::read('ContentsFile.Setting.Normal.fileDir') . '/');
32
        }
33
        if (!preg_match('#/$#', Configure::read('ContentsFile.Setting.S3.tmpDir'))) {
34
            Configure::write('ContentsFile.Setting.S3.tmpDir', Configure::read('ContentsFile.Setting.S3.tmpDir') . '/');
35
        }
36
        if (!preg_match('#/$#', Configure::read('ContentsFile.Setting.S3.fileDir'))) {
37
            Configure::write('ContentsFile.Setting.S3.fileDir', Configure::read('ContentsFile.Setting.S3.fileDir') . '/');
38
        }
39
        if (!preg_match('#/$#', Configure::read('ContentsFile.Setting.S3.workingDir'))) {
40
            Configure::write('ContentsFile.Setting.S3.workingDir', Configure::read('ContentsFile.Setting.S3.workingDir'). '/');
41
        }
42
    }
43
44
    /**
45
     * loader
46
     * @author hagiwara
47
     */
48
    public function loader()
49
    {
50
        $this->autoRender = false;
51
52
        // 必要なパラメータがない場合はエラー
53
        if (
54
            empty($this->request->query['model']) ||
55
            empty($this->request->query['field_name'])
56
        ) {
57
            throw new NotFoundException('404 error');
58
        }
59
60
        //Entityに接続して設定値を取得
61
        $this->baseModel = TableRegistry::get($this->request->query['model']);
62
63
        // このレベルで切り出す
64
        $fieldName = $this->request->query['field_name'];
65
        $filename = '';
66
        if (!empty($this->request->query['tmp_file_name'])) {
67
            $filename = $this->request->query['tmp_file_name'];
68
            $filepath = $this->{Configure::read('ContentsFile.Setting.type') . 'TmpFilePath'}($filename);
69
            Configure::read('ContentsFile.Setting.Normal.tmpDir') . $filename;
70
        } elseif (!empty($this->request->query['model_id'])) {
71
            //表示条件をチェックする
72
            $checkMethodName = 'contentsFileCheck' . Inflector::camelize($fieldName);
73
            if (method_exists($this->baseModel, $checkMethodName)) {
74
                //エラーなどの処理はTableに任せる
75
                $this->baseModel->{$checkMethodName}($this->request->query['model_id']);
76
            }
77
            //attachementからデータを取得
78
            $attachmentModel = TableRegistry::get('Attachments');
79
            $attachmentData = $attachmentModel->find('all')
80
                ->where(['model' => $this->request->query['model']])
81
                ->where(['model_id' => $this->request->query['model_id']])
82
                ->where(['field_name' => $this->request->query['field_name']])
83
                ->first()
84
            ;
85
            if (empty($attachmentData)) {
86
                throw new NotFoundException('404 error');
87
            }
88
            $filename = $attachmentData->file_name;
89
            $filepath = $this->{Configure::read('ContentsFile.Setting.type') . 'FilePath'}($attachmentData);
90
91
            //通常のセットの時のみresize設定があれば見る
92
            if (!empty($this->request->query['resize'])) {
93
                $filepath = $this->{Configure::read('ContentsFile.Setting.type') . 'ResizeSet'}($filepath, $this->request->query['resize']);
94
            }
95
        }
96
        
97
        $this->fileDownloadHeader($filename);
98
        $this->{Configure::read('ContentsFile.Setting.type') . 'Loader'}($filename, $filepath);
0 ignored issues
show
Bug introduced by
The variable $filepath does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
99
    }
100
101
    /**
102
     * getFileType
103
     * @author hagiwara
104
     * @param string $ext
105
     */
106
    private function getFileType($ext)
107
    {
108
        $aContentTypes = [
109
            'txt'=>'text/plain',
110
            'htm'=>'text/html',
111
            'html'=>'text/html',
112
            'jpg'=>'image/jpeg',
113
            'jpeg'=>'image/jpeg',
114
            'gif'=>'image/gif',
115
            'png'=>'image/png',
116
            'bmp'=>'image/x-bmp',
117
            'ai'=>'application/postscript',
118
            'psd'=>'image/x-photoshop',
119
            'eps'=>'application/postscript',
120
            'pdf'=>'application/pdf',
121
            'swf'=>'application/x-shockwave-flash',
122
            'lzh'=>'application/x-lha-compressed',
123
            'zip'=>'application/x-zip-compressed',
124
            'sit'=>'application/x-stuffit'
125
        ];
126
        $sContentType = 'application/octet-stream';
127
128
        if (!empty($aContentTypes[$ext])) {
129
            $sContentType = $aContentTypes[$ext];
130
        }
131
        return $sContentType;
132
    }
133
134
    /**
135
     * getMimeType
136
     * @author hagiwara
137
     * @param string $filename
138
     */
139
    private function getMimeType($filename)
140
    {
141
        $aContentTypes = [
142
            'txt'=>'text/plain',
143
            'htm'=>'text/html',
144
            'html'=>'text/html',
145
            'jpg'=>'image/jpeg',
146
            'jpeg'=>'image/jpeg',
147
            'gif'=>'image/gif',
148
            'png'=>'image/png',
149
            'bmp'=>'image/x-bmp',
150
            'ai'=>'application/postscript',
151
            'psd'=>'image/x-photoshop',
152
            'eps'=>'application/postscript',
153
            'pdf'=>'application/pdf',
154
            'swf'=>'application/x-shockwave-flash',
155
            'lzh'=>'application/x-lha-compressed',
156
            'zip'=>'application/x-zip-compressed',
157
            'sit'=>'application/x-stuffit'
158
        ];
159
        $sContentType = 'application/octet-stream';
160
161
        if (($pos = strrpos($filename, ".")) !== false) {
162
            // 拡張子がある場合
163
            $ext = strtolower(substr($filename, $pos + 1));
164
            if (strlen($ext)) {
165
                return $aContentTypes[$ext] ? $aContentTypes[$ext] : $sContentType;
166
            }
167
        }
168
        return $sContentType;
169
    }
170
    
171
    /**
172
     * fileDownloadHeader
173
     * @author hagiwara
174
     * @param string $filename
175
     */
176
    private function fileDownloadHeader($filename)
177
    {
178
        // loaderよりダウンロードするかどうか
179
        if (!empty($this->request->query['download']) && $this->request->query['download'] == true) {
180
            // IE/Edge対応
181
            if (strstr(env('HTTP_USER_AGENT'), 'MSIE') || strstr(env('HTTP_USER_AGENT'), 'Trident') || strstr(env('HTTP_USER_AGENT'), 'Edge')) {
182
                $filename = mb_convert_encoding($filename, "SJIS", "UTF-8");
183
            }
184
            header('Content-Disposition: attachment;filename="' . $filename . '"');
185
        }
186
    }
187
}
188