-
Notifications
You must be signed in to change notification settings - Fork 9.4k
/
Copy pathImage.php
279 lines (253 loc) · 9.2 KB
/
Image.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
<?php
/**
* Copyright 2014 Adobe
* All Rights Reserved.
*/
declare(strict_types=1);
namespace Magento\Customer\Model\Metadata\Form;
use Magento\Customer\Api\AddressMetadataInterface;
use Magento\Customer\Api\CustomerMetadataInterface;
use Magento\Customer\Api\Data\AttributeMetadataInterface;
use Magento\Customer\Model\FileProcessor;
use Magento\Customer\Model\FileProcessorFactory;
use Magento\Framework\Api\ArrayObjectSearch;
use Magento\Framework\Api\Data\ImageContentInterface;
use Magento\Framework\Api\Data\ImageContentInterfaceFactory;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\Exception\FileSystemException;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\File\UploaderFactory;
use Magento\Framework\Filesystem;
use Magento\Framework\Filesystem\Directory\ReadInterface;
use Magento\Framework\Filesystem\Directory\WriteFactory;
use Magento\Framework\Filesystem\Directory\WriteInterface;
use Magento\Framework\Filesystem\Io\File as IoFileSystem;
use Magento\Framework\Locale\ResolverInterface;
use Magento\Framework\Stdlib\DateTime\TimezoneInterface;
use Magento\Framework\Url\EncoderInterface;
use Magento\MediaStorage\Model\File\Validator\NotProtectedExtension;
use Psr\Log\LoggerInterface;
/**
* Metadata for form image field
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class Image extends File
{
/**
* @var ImageContentInterfaceFactory
*/
private $imageContentFactory;
/**
* @var IoFileSystem
*/
private $ioFileSystem;
/**
* @var ReadInterface
*/
private $mediaEntityTmpReadDirectory;
/**
* @var WriteInterface
*/
private $mediaWriteDirectory;
/**
* @param TimezoneInterface $localeDate
* @param LoggerInterface $logger
* @param AttributeMetadataInterface $attribute
* @param ResolverInterface $localeResolver
* @param null|string $value
* @param string $entityTypeCode
* @param bool $isAjax
* @param EncoderInterface $urlEncoder
* @param NotProtectedExtension $fileValidator
* @param Filesystem $fileSystem
* @param UploaderFactory $uploaderFactory
* @param FileProcessorFactory|null $fileProcessorFactory
* @param ImageContentInterfaceFactory|null $imageContentInterfaceFactory
* @param IoFileSystem|null $ioFileSystem
* @param DirectoryList|null $directoryList
* @param WriteFactory|null $writeFactory
* @SuppressWarnings(PHPMD.ExcessiveParameterList)
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
* @throws FileSystemException
*/
public function __construct(
TimezoneInterface $localeDate,
LoggerInterface $logger,
AttributeMetadataInterface $attribute,
ResolverInterface $localeResolver,
$value,
$entityTypeCode,
$isAjax,
EncoderInterface $urlEncoder,
NotProtectedExtension $fileValidator,
Filesystem $fileSystem,
UploaderFactory $uploaderFactory,
?FileProcessorFactory $fileProcessorFactory = null,
?ImageContentInterfaceFactory $imageContentInterfaceFactory = null,
?IoFileSystem $ioFileSystem = null,
?DirectoryList $directoryList = null,
?WriteFactory $writeFactory = null
) {
parent::__construct(
$localeDate,
$logger,
$attribute,
$localeResolver,
$value,
$entityTypeCode,
$isAjax,
$urlEncoder,
$fileValidator,
$fileSystem,
$uploaderFactory,
$fileProcessorFactory
);
$this->imageContentFactory = $imageContentInterfaceFactory ?: ObjectManager::getInstance()
->get(ImageContentInterfaceFactory::class);
$this->ioFileSystem = $ioFileSystem ?: ObjectManager::getInstance()
->get(IoFileSystem::class);
$this->mediaWriteDirectory = $fileSystem->getDirectoryWrite(DirectoryList::MEDIA);
$this->mediaEntityTmpReadDirectory = $fileSystem->getDirectoryReadByPath(
$this->mediaWriteDirectory->getAbsolutePath() . $this->_entityTypeCode
. DIRECTORY_SEPARATOR . FileProcessor::TMP_DIR . DIRECTORY_SEPARATOR
);
}
/**
* Validate file by attribute validate rules
*
* Return array of errors
*
* @param array $value
* @return string[]
* @throws LocalizedException
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
protected function _validateByRules($value)
{
$label = $value['name'];
$rules = $this->getAttribute()->getValidationRules();
$temporaryFile = $value['tmp_name'];
if (!$this->ioFileSystem->fileExists($temporaryFile)) {
$temporaryFile = $this->mediaEntityTmpReadDirectory->getAbsolutePath($temporaryFile);
}
try {
// phpcs:ignore Magento2.Functions.DiscouragedFunction
$imageProp = getimagesize($temporaryFile);
} catch (\Throwable $e) {
$imageProp = false;
}
if (!$this->_isUploadedFile($value['tmp_name']) || !$imageProp) {
return [__('"%1" is not a valid file.', $label)];
}
$allowImageTypes = [1 => 'gif', 2 => 'jpg', 3 => 'png'];
if (!isset($allowImageTypes[$imageProp[2]])) {
return [__('"%1" is not a valid image format.', $label)];
}
// modify image name
$extension = $this->ioFileSystem->getPathInfo($value['name'])['extension'];
if ($extension != $allowImageTypes[$imageProp[2]]) {
$value['name'] = $this->ioFileSystem->getPathInfo($value['name'])['filename']
. '.'
. $allowImageTypes[$imageProp[2]];
}
$maxFileSize = ArrayObjectSearch::getArrayElementByName(
$rules,
'max_file_size'
);
$errors = [];
if ($maxFileSize !== null) {
$size = $value['size'];
if ($maxFileSize < $size) {
$errors[] = __('"%1" exceeds the allowed file size.', $label);
}
}
$maxImageWidth = ArrayObjectSearch::getArrayElementByName(
$rules,
'max_image_width'
);
if ($maxImageWidth !== null) {
if ($maxImageWidth < $imageProp[0]) {
$r = $maxImageWidth;
$errors[] = __('"%1" width exceeds allowed value of %2 px.', $label, $r);
}
}
$maxImageHeight = ArrayObjectSearch::getArrayElementByName(
$rules,
'max_image_height'
);
if ($maxImageHeight !== null) {
if ($maxImageHeight < $imageProp[1]) {
$r = $maxImageHeight;
$errors[] = __('"%1" height exceeds allowed value of %2 px.', $label, $r);
}
}
return $errors;
}
/**
* Process file uploader UI component data
*
* @param array $value
* @return bool|int|ImageContentInterface|string
* @throws LocalizedException
*/
protected function processUiComponentValue(array $value)
{
if ($this->_entityTypeCode == AddressMetadataInterface::ENTITY_TYPE_ADDRESS) {
return $this->processCustomerAddressValue($value);
}
if ($this->_entityTypeCode == CustomerMetadataInterface::ENTITY_TYPE_CUSTOMER) {
return $this->processCustomerValue($value);
}
return $this->_value;
}
/**
* Process file uploader UI component data for customer_address entity
*
* @param array $value
* @return string
* @throws LocalizedException
*/
protected function processCustomerAddressValue(array $value)
{
$fileName = $this->mediaWriteDirectory
->getDriver()
->getRealPathSafety(
$this->mediaEntityTmpReadDirectory->getAbsolutePath(
ltrim(
$value['file'],
'/'
)
)
);
return $this->getFileProcessor()->moveTemporaryFile(
$this->mediaEntityTmpReadDirectory->getRelativePath($fileName)
);
}
/**
* Process file uploader UI component data for customer entity
*
* @param array $value
* @return bool|int|ImageContentInterface|string
* @throws LocalizedException
*/
protected function processCustomerValue(array $value)
{
$file = ltrim($value['file'], '/');
if ($this->mediaEntityTmpReadDirectory->isExist($file)) {
$temporaryFile = FileProcessor::TMP_DIR . '/' . $file;
$base64EncodedData = $this->getFileProcessor()->getBase64EncodedData($temporaryFile);
/** @var ImageContentInterface $imageContentDataObject */
$imageContentDataObject = $this->imageContentFactory->create()
->setName($value['name'])
->setBase64EncodedData($base64EncodedData)
->setType($value['type']);
// Remove temporary file
$this->getFileProcessor()->removeUploadedFile($temporaryFile);
return $imageContentDataObject;
}
return $this->_value ?: $value['file'];
}
}