SaveOperation   A
last analyzed

Complexity

Total Complexity 26

Size/Duplication

Total Lines 212
Duplicated Lines 7.55 %

Coupling/Cohesion

Components 2
Dependencies 7

Importance

Changes 0
Metric Value
wmc 26
lcom 2
cbo 7
dl 16
loc 212
c 0
b 0
f 0
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A get_file() 0 4 1
A lazy_get_properties() 0 19 2
A action() 0 6 1
C control() 0 38 7
C validate() 16 45 8
A process() 0 19 4
A resolve_request_file_from_pathname() 0 19 3

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
/*
4
 * This file is part of the Icybee package.
5
 *
6
 * (c) Olivier Laviale <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Icybee\Modules\Files\Operation;
13
14
use ICanBoogie\ErrorCollection;
15
use ICanBoogie\HTTP\Request;
16
use ICanBoogie\HTTP\File as HTTPFile;
17
18
use Icybee\Modules\Files\File;
19
use Icybee\Modules\Files\Module;
20
21
/**
22
 * Save a file.
23
 *
24
 * @property-read HTTPFile|null $file The file associated with the request.
25
 * @property Module $module
26
 * @property File $record
27
 */
28
class SaveOperation extends \Icybee\Modules\Nodes\Operation\SaveOperation
29
{
30
	/**
31
	 * Name of the _user-file_ slot.
32
	 *
33
	 * @var string
34
	 */
35
	const USERFILE = File::HTTP_FILE;
36
37
	/**
38
	 * @var HTTPFile|bool The optional file to save with the record.
39
	 */
40
	protected $file;
41
42
	protected function get_file()
43
	{
44
		return $this->file;
45
	}
46
47
	/**
48
	 * @var array Accepted file types.
49
	 */
50
	protected $accept;
51
52
	/**
53
	 * Unset {@link File::MIME}, {@link File::SIZE}, and {@link File::EXTENSION} properties because
54
	 * they can only be set from a HTTP file. {@link File::DESCRIPTION} is set to and empty
55
	 * string if it is not defined.
56
	 *
57
	 * {@inheritdoc}
58
	 */
59
	protected function lazy_get_properties()
60
	{
61
		$properties = parent::lazy_get_properties() + [
62
63
			'description' => ''
64
65
		];
66
67
		unset($properties[File::MIME]);
68
		unset($properties[File::SIZE]);
69
		unset($properties[File::EXTENSION]);
70
71
		if ($this->file)
72
		{
73
			$properties[File::HTTP_FILE] = $this->file;
74
		}
75
76
		return $properties;
77
	}
78
79
	/**
80
	 * {@inheritdoc}
81
	 *
82
	 * The temporary files stored in the repository are cleaned before the operation is processed.
83
	 */
84
	public function action(Request $request)
85
	{
86
		$this->module->clean_temporary_files();
87
88
		return parent::action($request);
89
	}
90
91
	/**
92
	 * If PATH is not defined, we check for a file upload, which is required if the operation key
93
	 * is empty. If a file upload is found, the Uploaded object is set as the operation `file`
94
	 * property, and the PATH parameter of the operation is set to the file location.
95
	 *
96
	 * Note that if the upload is not required - because the operation key is defined for updating
97
	 * an entry - the PATH parameter of the operation is set to TRUE to avoid error reporting from
98
	 * the form validation.
99
	 *
100
	 * TODO: maybe this is not ideal, since the file upload should be made optional when the form
101
	 * is generated to edit existing entries.
102
	 *
103
	 * @inheritdoc
104
	 */
105
	protected function control(array $controls)
106
	{
107
		$request = $this->request;
108
		$path = $request[File::HTTP_FILE];
109
		$file = $request->files[self::USERFILE];
110
111
		if ($file && $file->is_valid)
112
		{
113
			$filename = \ICanBoogie\generate_v4_uuid();
114
			$pathname = \ICanBoogie\REPOSITORY . 'tmp' . DIRECTORY_SEPARATOR . $filename;
115
116
			$file->move($pathname);
117
		}
118
		else if ($path && strpos($path, \ICanBoogie\strip_root(\ICanBoogie\REPOSITORY . "files")) !== 0)
119
		{
120
			$file = $this->resolve_request_file_from_pathname($path);
121
122
			if (!$file)
123
			{
124
				$this->response->errors->add(File::HTTP_FILE, "Invalid or deleted file: %pathname", [ 'pathname' => $path ]);
125
			}
126
		}
127
128
		unset($request[File::HTTP_FILE]);
129
130
		$this->file = $file;
131
132
		if ($file)
133
		{
134
			#
135
			# This is used during form validation.
136
			#
137
138
			$request[File::HTTP_FILE] = $file->pathname;
139
		}
140
141
		return parent::control($controls);
142
	}
143
144
	/**
145
	 * The method validates unless there was an error during the file upload.
146
	 *
147
	 * @inheritdoc
148
	 */
149
	protected function validate(ErrorCollection $errors)
150
	{
151
		$file = $this->file;
152
153
		if ($file)
154
		{
155
			$error_message = $file->error_message;
156
157
			$max_file_size = $this->app->registry["{$this->module->flat_id}.max_file_size"] * 1024;
158
159 View Code Duplication
			if ($max_file_size && $max_file_size < $file->size)
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...
160
			{
161
				$error_message = $errors->add(
162
					File::HTTP_FILE,
163
					"Maximum file size is :size Mb",
164
					[ ':size' => round($max_file_size / 1024) ]
165
				);
166
			}
167
168 View Code Duplication
			if ($this->accept && !$file->match($this->accept))
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->accept of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
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...
169
			{
170
				$error_message = $errors->add(
171
					File::HTTP_FILE,
172
					"Only the following file types are accepted: %accepted.",
173
					[ '%accepted' => implode(', ', $this->accept)
174
				]);
175
			}
176
177
			if ($error_message)
178
			{
179
				$errors->add(File::HTTP_FILE, "Unable to upload file %file: :message.", [
180
181
					'%file' => $file->name,
182
					':message' => $error_message
183
184
				]);
185
			}
186
		}
187
		else if (!$this->key)
188
		{
189
			$errors->add(File::HTTP_FILE, "File is required.");
190
		}
191
192
		return parent::validate($errors);
193
	}
194
195
	/**
196
	 * Trigger a {@link File\MoveEvent} when the path of the updated record is updated.
197
	 *
198
	 * @inheritdoc
199
	 */
200
	protected function process()
201
	{
202
		$record = $this->record;
203
		$oldpath = $record ? $record->pathname->relative : null;
204
205
		$rc = parent::process();
206
207
		if ($oldpath)
0 ignored issues
show
Bug Best Practice introduced by
The expression $oldpath of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
208
		{
209
			$newpath = $this->record->pathname->relative;
210
211
			if ($oldpath != $newpath)
212
			{
213
				new File\MoveEvent($record, $oldpath, $newpath);
214
			}
215
		}
216
217
		return $rc;
218
	}
219
220
	protected function resolve_request_file_from_pathname($pathname)
221
	{
222
		$filename = basename($pathname);
223
		$info_pathname = \ICanBoogie\REPOSITORY . 'tmp' . DIRECTORY_SEPARATOR . $filename . '.info';
224
225
		if (!file_exists($info_pathname))
226
		{
227
			return null;
228
		}
229
230
		$properties = json_decode(file_get_contents($info_pathname), true);
231
232
		if (!$properties)
233
		{
234
			return null;
235
		}
236
237
		return HTTPFile::from($properties);
238
	}
239
}
240