Completed
Branch s3_upload (4473df)
by satoru
02:12
created

ContentsFileBehavior::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 2
1
<?php
2
3
namespace ContentsFile\Model\Behavior;
4
5
use ArrayObject;
6
use Cake\Core\Configure;
7
use Cake\Event\Event;
8
use Cake\Network\Exception\InternalErrorException;
9
use Cake\ORM\Behavior;
10
use Cake\Datasource\EntityInterface;
11
use Cake\ORM\Table;
12
use Cake\ORM\TableRegistry;
13
use ContentsFile\Model\Behavior\Traits\NormalContentsFileBehaviorTrait;
14
use ContentsFile\Model\Behavior\Traits\S3ContentsFileBehaviorTrait;
15
use ContentsFile\Model\Behavior\Traits\ImageContentsFileBehaviorTrait;
16
17
class ContentsFileBehavior extends Behavior {
18
19
    use NormalContentsFileBehaviorTrait;
20
    use S3ContentsFileBehaviorTrait;
21
    use ImageContentsFileBehaviorTrait;
22
23
    private $tp;
0 ignored issues
show
Unused Code introduced by
The property $tp is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
24
    /**
25
     * __construct
26
     * @author hagiwara
27
     * @param Table $table
28
     * @param array $config
29
     */
30
    public function __construct(Table $table, array $config = [])
31
    {
32
        parent::__construct($table, $config);
33
        // 指定外のものが指定されている場合はエラーとする
34
        if (!in_array(Configure::read('ContentsFile.Setting.type'), ['s3', 'normal'])) {
35
            throw new InternalErrorException('contentsFileConfig type illegal');
36
        }
37
        // Configureの設定不足をチェックする
38
        $this->{Configure::read('ContentsFile.Setting.type') . 'ParamCheck'}();
39
}
40
41
    /**
42
     * afterSave
43
     * 画像をafterSaveで保存する
44
     * @author hagiwara
45
     * @param Event $event
46
     * @param EntityInterface $entity
47
     * @param ArrayObject $options
48
     */
49
    public function afterSave(Event $event, EntityInterface $entity, ArrayObject $options)
0 ignored issues
show
Unused Code introduced by
The parameter $event 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...
Unused Code introduced by
The parameter $options 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...
50
    {
51
        //設定値をentityから取得
52
        $contentsFileConfig = $entity->getContentsFileSettings();
0 ignored issues
show
Bug introduced by
The method getContentsFileSettings() does not seem to exist on object<Cake\Datasource\EntityInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
53
        $attachmentModel = TableRegistry::get('Attachments');
54
        foreach ($contentsFileConfig['fields'] as $field => $fieldSettings) {
55
            // ファイルの削除を最初に確認
56
            if ($entity->{'delete_' . $field} == true) {
57
                // 該当フィールドを削除
58
                if (!$this->fileDelete($entity, [$field])) {
59
                    return false;
60
                }
61
                // ファイルの削除に成功したら保存処理は飛ばす
62
                continue;
63
            }
64
            //contents_file_の方に入ったentityをベースに処理する
65
            $fileInfo = $entity->{'contents_file_' . $field};
66
            if (
67
                !empty($fileInfo) &&
68
                //tmp_file_nameがある=アップロードしたファイルがある
69
                array_key_exists('tmp_file_name', $fileInfo)
70
            ) {
71
                // ファイルの削除
72
                $attachmentSaveData = [
73
                    'model' => $this->_table->alias(),
74
                    'model_id' => $entity->id,
0 ignored issues
show
Bug introduced by
Accessing id on the interface Cake\Datasource\EntityInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
75
                    'field_name' => $fileInfo['field_name'],
76
                    'file_name' => $fileInfo['file_name'],
77
                    'file_content_type' => $fileInfo['file_content_type'],
78
                    'file_size' => $fileInfo['file_size'],
79
                ];
80
                $attachmentEntity = $attachmentModel->newEntity($attachmentSaveData);
81
                // 通常とS3で画像保存方法の切り替え
82
                if (!$this->{Configure::read('ContentsFile.Setting.type') . 'FileSave'}($fileInfo, $fieldSettings, $attachmentSaveData)) {
83
                    return false;
84
                }
85
86
                //元のデータがあるかfind(あれば更新にする)
87
                $attachmentDataCheck = $attachmentModel->find('all')
88
                    ->where(['model' => $fileInfo['model']])
89
                    ->where(['model_id' => $entity->id])
0 ignored issues
show
Bug introduced by
Accessing id on the interface Cake\Datasource\EntityInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
90
                    ->where(['field_name' => $fileInfo['field_name']])
91
                    ->first();
92
                if (!empty($attachmentDataCheck)) {
93
                    $attachmentEntity->id = $attachmentDataCheck->id;
0 ignored issues
show
Bug introduced by
Accessing id on the interface Cake\Datasource\EntityInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
94
                }
95
                if (!$attachmentModel->save($attachmentEntity)) {
96
                    return false;
97
                }
98
            }
99
        }
100
101
        return true;
102
103
    }
104
105
    /**
106
     * fileDelete
107
     * ファイル削除
108
     * @author hagiwara
109
     * @param EntityInterface $entity
110
     * @param array $fields
111
     */
112
    public function fileDelete(EntityInterface $entity, $fields = [])
113
    {
114
        // 新規作成データ時は何もしない
115
        if (empty($entity->id)) {
0 ignored issues
show
Bug introduced by
Accessing id on the interface Cake\Datasource\EntityInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
116
            return true;
117
        }
118
        $attachmentModel = TableRegistry::get('Attachments');
119
        $contentsFileConfig = $entity->getContentsFileSettings();
0 ignored issues
show
Bug introduced by
The method getContentsFileSettings() does not seem to exist on object<Cake\Datasource\EntityInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
120
        if (!empty($contentsFileConfig['fields'])) {
121
            foreach ($contentsFileConfig['fields'] as $field => $config) {
122
                // fieldsの指定がない場合は全部消す
123
                if (empty($fields) || in_array($field, $fields)) {
124
125
                    $modelName = $entity->source();
126
                    $modelId = $entity->id;
0 ignored issues
show
Bug introduced by
Accessing id on the interface Cake\Datasource\EntityInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
127
                    // 添付ファイルデータの削除
128
                    $deleteAttachmentData = $attachmentModel->find('all')
129
                        ->where(['Attachments.model' => $modelName])
130
                        ->where(['Attachments.model_id' => $modelId])
131
                        ->where(['Attachments.field_name' => $field])
132
                        ->first();
133
134
                    if (!empty($deleteAttachmentData->id)) {
135
                        $attachmentModel->delete($deleteAttachmentData);
136
                        // 通常とS3でファイルの削除方法の切り替え
137
                        if (!$this->{Configure::read('ContentsFile.Setting.type') . 'FileDelete'}($modelName, $modelId, $field)) {
138
                            return false;
139
                        }
140
                    }
141
                }
142
            }
143
        }
144
        return true;
145
    }
146
147
    /**
148
     * getPathInfo
149
     * 通常のpathinfoに加えてContentsFile独自のpathも一緒に設定する
150
     * @author hagiwara
151
     * @param string $imagePath
152
     * @param array $resize
153
     */
154
    public function getPathInfo($imagePath, $resize = []) {
155
        $pathinfo = pathinfo($imagePath);
156
        $pathinfo['resize_dir'] = $pathinfo['dirname'] . '/contents_file_resize_' . $pathinfo['filename'];
157
        //一旦ベースのパスを通しておく
158
        $pathinfo['resize_filepath'] = $imagePath;
159
        if (!empty($resize)) {
160
            if (!isset($resize['width'])) {
161
                $resize['width'] = 0;
162
            }
163
            if (!isset($resize['height'])) {
164
                $resize['height'] = 0;
165
            }
166
            $pathinfo['resize_filepath'] = $pathinfo['resize_dir'] . '/' . $resize['width'] . '_' . $resize['height'];
167
        }
168
        return $pathinfo;
169
    }
170
171
    /**
172
     * mkdir
173
     * ディレクトリの作成(パーミッションの設定のため
174
     * @author hagiwara
175
     * @param string $permission
176
     * @param integer $path
177
     * @param boolean $recursive
178
     */
179
    private function mkdir($path, $permission, $recursive)
180
    {
181
        if (is_dir($path)) {
182
            return true;
183
        }
184
        $oldumask = umask(0);
185
        $result = mkdir($path, $permission, $recursive);
186
        umask($oldumask);
187
        return $result;
188
    }
189
}
190