Save::getSaveAs()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
/**
4
 * Copyright 2019 Amin Yazdanpanah<http://www.aminyazdanpanah.com>.
5
 *
6
 * Licensed under the MIT License;
7
 * you may not use this file except in compliance with the License.
8
 * You may obtain a copy of the License at
9
 *
10
 *      https://opensource.org/licenses/MIT
11
 *
12
 * Unless required by applicable law or agreed to in writing, software
13
 * distributed under the License is distributed on an "AS IS" BASIS,
14
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
 * See the License for the specific language governing permissions and
16
 * limitations under the License.
17
 */
18
19
namespace AYazdanpanah\SaveUploadedFiles;
20
21
22
use AYazdanpanah\SaveUploadedFiles\Exception\Exception;
23
use AYazdanpanah\SaveUploadedFiles\Exception\SaveExceptionInterface;
24
25
abstract class Save implements FileInterface
26
{
27
28
    /**
29
     * @var Validator
30
     */
31
    private $validator;
32
33
    /**
34
     * @var string
35
     */
36
    private $path = '';
37
38
    /**
39
     * @var string
40
     */
41
    private $file_path = '';
42
43
    /**
44
     * @var bool
45
     */
46
    private $override;
47
    /**
48
     * @var mixed
49
     */
50
    private $save_as;
51
52
    /**
53
     * @var mixed
54
     */
55
    private $export_data;
56
57
    /**
58
     * @param $path
59
     * @param callable $export
60
     * @return array
61
     */
62
    public function save($path, callable $export)
63
    {
64
        $this->path = $path;
65
66
        try {
67
            $this->validate();
68
            $this->moveFile();
69
            $this->export($export);
70
            return $this->output(true, "The file \"" . $this->getBaseNameFile() . "\" has been uploaded.");
71
        } catch (SaveExceptionInterface $e) {
72
            return $this->output(false, $e->getMessage());
0 ignored issues
show
Bug introduced by
The method getMessage() does not exist on AYazdanpanah\SaveUploade...\SaveExceptionInterface. Since it exists in all sub-types, consider adding an abstract or default implementation to AYazdanpanah\SaveUploade...\SaveExceptionInterface. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

72
            return $this->output(false, $e->/** @scrutinizer ignore-call */ getMessage());
Loading history...
73
        }
74
    }
75
76
    /**
77
     * @throws Exception
78
     */
79
    private function validate()
80
    {
81
        $this->validator
82
            ->setFileSize($this->getFileSize())
83
            ->setFileExtension($this->getFileExtension())
84
            ->validate();
85
    }
86
87
    /**
88
     * @throws Exception
89
     */
90
    private function moveFile()
91
    {
92
        if (!is_dir($this->path)) {
93
            mkdir($this->path, 0777, true);
94
        }
95
96
        if (null !== $this->getSaveAs()) {
0 ignored issues
show
introduced by
The condition null !== $this->getSaveAs() is always true.
Loading history...
97
            $this->file_path = $this->path . "/" . $this->getSaveAs() . "." . $this->getFileExtension();
98
        } else {
99
            $this->file_path = $this->path . "/" . $this->getbasenamefile();
100
        }
101
102
        if (!$this->isOverride() && file_exists($this->file_path)) {
103
            throw new Exception("Sorry, file already exists. The file path: \"" . $this->file_path . "\"");
104
        }
105
106
        if (!move_uploaded_file($this->getFileTmpName(), $this->file_path)) {
107
            throw new Exception("Sorry, there was an error uploading your file. Maybe the path does not have permission to write");
108
        }
109
    }
110
111
    /**
112
     * @param $status
113
     * @param $output
114
     * @return array
115
     */
116
    private function output($status, $output)
117
    {
118
        $output = [
119
            'status' => $status,
120
            'output' => $output,
121
        ];
122
123
        try {
124
            $output = array_merge(
125
                $output,
126
                [
127
                    'file_details' => [
128
                        'name' => $this->getFileName(),
129
                        'type' => $this->getFileType(),
130
                        'tmp_name' => $this->getFileTmpName(),
131
                        'size' => $this->getFileSize(),
132
                        'extension' => $this->getFileExtension(),
133
                        'basename' => $this->getbasenamefile(),
134
                        'save_as' => (null === $this->getSaveAs()) ? $this->getbasenamefile() : $this->getSaveAs() . '.' . $this->getFileExtension(),
0 ignored issues
show
introduced by
The condition null === $this->getSaveAs() is always false.
Loading history...
135
                        'dir_path' => $this->path,
136
                        'file_path' => $this->file_path,
137
                        'upload_datetime' => date("Y-m-d H:i:s"),
138
                        'stat' => !is_file($this->file_path)?:stat($this->file_path),
139
                        'mime_content_type' => !is_file($this->file_path)?:mime_content_type($this->file_path),
140
                        'export' => $this->export_data,
141
                    ]
142
                ]
143
            );
144
        } catch (Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
145
        }
146
147
        return $output;
148
    }
149
150
    /**
151
     * @param bool $override
152
     * @return Save
153
     */
154
    public function setOverride(bool $override): Save
155
    {
156
        $this->override = $override;
157
        return $this;
158
    }
159
160
    /**
161
     * @return bool
162
     */
163
    public function isOverride(): bool
164
    {
165
        return $this->override;
166
    }
167
168
    /**
169
     * @param mixed $save_as
170
     * @return Save
171
     */
172
    public function setSaveAs($save_as): Save
173
    {
174
        $this->save_as = $save_as;
175
        return $this;
176
    }
177
178
    /**
179
     * @return string
180
     */
181
    public function getSaveAs()
182
    {
183
        return $this->save_as;
184
    }
185
186
    private function export(callable $export)
187
    {
188
        $this->export_data = $export($this->file_path);
189
    }
190
191
    /**
192
     * @param Validator $validator
193
     * @return Save
194
     */
195
    public function setValidator(Validator $validator): Save
196
    {
197
        $this->validator = $validator;
198
        return $this;
199
    }
200
}