Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
File.php
Go to the documentation of this file.
1 <?php
7 
9 use Magento\Customer\Model\FileProcessorFactory;
16 
20 class File extends AbstractData
21 {
28 
34  protected $urlEncoder;
35 
39  protected $_fileValidator;
40 
44  protected $_fileSystem;
45 
49  private $uploaderFactory;
50 
54  protected $fileProcessor;
55 
61 
79  public function __construct(
80  \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate,
83  \Magento\Framework\Locale\ResolverInterface $localeResolver,
84  $value,
86  $isAjax,
88  \Magento\MediaStorage\Model\File\Validator\NotProtectedExtension $fileValidator,
89  Filesystem $fileSystem,
90  UploaderFactory $uploaderFactory,
91  \Magento\Customer\Model\FileProcessorFactory $fileProcessorFactory = null
92  ) {
93  parent::__construct($localeDate, $logger, $attribute, $localeResolver, $value, $entityTypeCode, $isAjax);
94  $this->urlEncoder = $urlEncoder;
95  $this->_fileValidator = $fileValidator;
96  $this->_fileSystem = $fileSystem;
97  $this->uploaderFactory = $uploaderFactory;
98  $this->fileProcessorFactory = $fileProcessorFactory ?: ObjectManager::getInstance()
99  ->get(\Magento\Customer\Model\FileProcessorFactory::class);
100  $this->fileProcessor = $this->fileProcessorFactory->create(['entityTypeCode' => $this->_entityTypeCode]);
101  }
102 
107  public function extractValue(\Magento\Framework\App\RequestInterface $request)
108  {
109  $extend = $this->_getRequestValue($request);
110 
111  $attrCode = $this->getAttribute()->getAttributeCode();
112  if ($this->_requestScope) {
113  $value = [];
114  if (strpos($this->_requestScope, '/') !== false) {
115  $scopes = explode('/', $this->_requestScope);
116  $mainScope = array_shift($scopes);
117  } else {
118  $mainScope = $this->_requestScope;
119  $scopes = [];
120  }
121 
122  if (!empty($_FILES[$mainScope])) {
123  foreach ($_FILES[$mainScope] as $fileKey => $scopeData) {
124  foreach ($scopes as $scopeName) {
125  if (isset($scopeData[$scopeName])) {
126  $scopeData = $scopeData[$scopeName];
127  } else {
128  $scopeData[$scopeName] = [];
129  }
130  }
131 
132  if (isset($scopeData[$attrCode])) {
133  $value[$fileKey] = $scopeData[$attrCode];
134  }
135  }
136  } elseif (isset($extend[0]['file']) && !empty($extend[0]['file'])) {
143  $value = $this->getIsAjaxRequest() ? $extend[0]['file'] : $extend[0];
144  } else {
145  $value = [];
146  }
147  } else {
148  if (isset($_FILES[$attrCode])) {
149  $value = $_FILES[$attrCode];
150  } else {
151  $value = [];
152  }
153  }
154 
155  if (!empty($extend['delete'])) {
156  $value['delete'] = true;
157  }
158 
159  return $value;
160  }
161 
169  protected function _validateByRules($value)
170  {
171  $label = $value['name'];
172  $rules = $this->getAttribute()->getValidationRules();
173  $extension = pathinfo($value['name'], PATHINFO_EXTENSION);
174  $fileExtensions = ArrayObjectSearch::getArrayElementByName(
175  $rules,
176  'file_extensions'
177  );
178  if ($fileExtensions !== null) {
179  $extensions = explode(',', $fileExtensions);
180  $extensions = array_map('trim', $extensions);
181  if (!in_array($extension, $extensions)) {
182  return [__('"%1" is not a valid file extension.', $extension)];
183  }
184  }
185 
189  if (!$this->_fileValidator->isValid($extension)) {
190  return $this->_fileValidator->getMessages();
191  }
192 
193  if (!$this->_isUploadedFile($value['tmp_name'])) {
194  return [__('"%1" is not a valid file.', $label)];
195  }
196 
197  $maxFileSize = ArrayObjectSearch::getArrayElementByName(
198  $rules,
199  'max_file_size'
200  );
201  if ($maxFileSize !== null) {
202  $size = $value['size'];
203  if ($maxFileSize < $size) {
204  return [__('"%1" exceeds the allowed file size.', $label)];
205  }
206  }
207 
208  return [];
209  }
210 
219  protected function _isUploadedFile($filename)
220  {
221  if (is_uploaded_file($filename)) {
222  return true;
223  }
224 
225  // This case is required for file uploader UI component
226  $temporaryFile = FileProcessor::TMP_DIR . '/' . pathinfo($filename)['basename'];
227  if ($this->fileProcessor->isExist($temporaryFile)) {
228  return true;
229  }
230 
231  return false;
232  }
233 
239  public function validateValue($value)
240  {
241  if ($this->getIsAjaxRequest()) {
242  return true;
243  }
244 
245  $errors = [];
246  $attribute = $this->getAttribute();
247  $label = $attribute->getStoreLabel();
248 
249  $toDelete = !empty($value['delete']) ? true : false;
250  $toUpload = !empty($value['tmp_name']) ? true : false;
251 
252  if (!$toUpload && !$toDelete && $this->_value) {
253  return true;
254  }
255 
256  if (!$attribute->isRequired() && !$toUpload) {
257  return true;
258  }
259 
260  if ($attribute->isRequired() && !$toUpload) {
261  $errors[] = __('"%1" is a required value.', $label);
262  }
263 
264  if ($toUpload) {
265  $errors = array_merge($errors, $this->_validateByRules($value));
266  }
267 
268  if (count($errors) == 0) {
269  return true;
270  }
271 
272  return $errors;
273  }
274 
280  public function compactValue($value)
281  {
282  if ($this->getIsAjaxRequest()) {
283  return $this;
284  }
285 
286  // Remove outdated file (in the case of file uploader UI component)
287  if (empty($value) && !empty($this->_value)) {
288  $this->fileProcessor->removeUploadedFile($this->_value);
289  return $value;
290  }
291 
292  if (isset($value['file']) && !empty($value['file'])) {
293  if ($value['file'] == $this->_value) {
294  return $this->_value;
295  }
297  } else {
299  }
300 
301  return $result;
302  }
303 
310  protected function processUiComponentValue(array $value)
311  {
312  $result = $this->fileProcessor->moveTemporaryFile($value['file']);
313  return $result;
314  }
315 
322  protected function processInputFieldValue($value)
323  {
324  $toDelete = false;
325  if ($this->_value) {
326  if (!$this->getAttribute()->isRequired()
327  && !empty($value['delete'])
328  ) {
329  $toDelete = true;
330  }
331  if (!empty($value['tmp_name'])) {
332  $toDelete = true;
333  }
334  }
335 
336  $mediaDir = $this->_fileSystem->getDirectoryWrite(DirectoryList::MEDIA);
338 
339  if ($toDelete) {
340  $mediaDir->delete($this->_entityTypeCode . '/' . ltrim($this->_value, '/'));
341  $result = '';
342  }
343 
344  if (!empty($value['tmp_name'])) {
345  try {
346  $uploader = $this->uploaderFactory->create(['fileId' => $value]);
347  $uploader->setFilesDispersion(true);
348  $uploader->setFilenamesCaseSensitivity(false);
349  $uploader->setAllowRenameFiles(true);
350  $uploader->save($mediaDir->getAbsolutePath($this->_entityTypeCode), $value['name']);
351  $result = $uploader->getUploadedFileName();
352  } catch (\Exception $e) {
353  $this->_logger->critical($e);
354  }
355  }
356 
357  return $result;
358  }
359 
363  public function restoreValue($value)
364  {
365  return $this->_value;
366  }
367 
372  {
373  $output = '';
374  if ($this->_value) {
375  switch ($format) {
376  case \Magento\Customer\Model\Metadata\ElementFactory::OUTPUT_FORMAT_JSON:
377  $output = ['value' => $this->_value, 'url_key' => $this->urlEncoder->encode($this->_value)];
378  break;
379  }
380  }
381 
382  return $output;
383  }
384 
391  protected function getFileProcessor()
392  {
393  return $this->fileProcessor;
394  }
395 }
elseif(isset( $params[ 'redirect_parent']))
Definition: iframe.phtml:17
extractValue(\Magento\Framework\App\RequestInterface $request)
Definition: File.php:107
__()
Definition: __.php:13
$logger
_getRequestValue(\Magento\Framework\App\RequestInterface $request)
$label
Definition: details.phtml:21
$value
Definition: gender.phtml:16
$format
Definition: list.phtml:12
if(!validateInput($options, $requiredOptions)) $fileExtensions
outputValue($format=\Magento\Customer\Model\Metadata\ElementFactory::OUTPUT_FORMAT_TEXT)
Definition: File.php:371
__construct(\Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate, \Psr\Log\LoggerInterface $logger, \Magento\Customer\Api\Data\AttributeMetadataInterface $attribute, \Magento\Framework\Locale\ResolverInterface $localeResolver, $value, $entityTypeCode, $isAjax, \Magento\Framework\Url\EncoderInterface $urlEncoder, \Magento\MediaStorage\Model\File\Validator\NotProtectedExtension $fileValidator, Filesystem $fileSystem, UploaderFactory $uploaderFactory, \Magento\Customer\Model\FileProcessorFactory $fileProcessorFactory=null)
Definition: File.php:79
$errors
Definition: overview.phtml:9