Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
Public Member Functions | Static Public Member Functions | Data Fields | Protected Member Functions | Static Protected Member Functions | Protected Attributes
Uploader Class Reference
Inheritance diagram for Uploader:
Uploader Uploader Uploader ContentUploader

Public Member Functions

 __construct ( $fileId, Mime $fileMime=null)
 
 save ($destinationFolder, $newFileName=null)
 
 getFileExtension ()
 
 addValidateCallback ($callbackName, $callbackObject, $callbackMethod)
 
 removeValidateCallback ($callbackName)
 
 correctFileNameCase ($fileName)
 
 checkMimeType ($validTypes=[])
 
 getUploadedFileName ()
 
 setAllowCreateFolders ($flag)
 
 setAllowRenameFiles ($flag)
 
 setFilesDispersion ($flag)
 
 setFilenamesCaseSensitivity ($flag)
 
 setAllowedExtensions ($extensions=[])
 
 checkAllowedExtension ($extension)
 

Static Public Member Functions

static getCorrectFileName ($fileName)
 
static getNewFileName ($destinationFile)
 
static getDispretionPath ($fileName)
 
static getDispersionPath ($fileName)
 

Data Fields

const SINGLE_STYLE = 0
 
const MULTIPLE_STYLE = 1
 
const TMP_NAME_EMPTY = 666
 
const MAX_IMAGE_WIDTH = 4096
 
const MAX_IMAGE_HEIGHT = 2160
 

Protected Member Functions

 _afterSave ($result)
 
 chmod ($file)
 
 _moveFile ($tmpPath, $destPath)
 
 _validateFile ()
 

Static Protected Member Functions

static _addDirSeparator ($dir)
 

Protected Attributes

 $_file
 
 $_fileMimeType
 
 $_uploadType
 
 $_uploadedFileName
 
 $_uploadedFileDir
 
 $_allowCreateFolders = true
 
 $_allowRenameFiles = false
 
 $_enableFilesDispersion = false
 
 $_caseInsensitiveFilenames = true
 
 $_dispretionPath = null
 
 $_fileExists = false
 
 $_allowedExtensions = null
 
 $_validateCallbacks = []
 
 $_result
 

Detailed Description

File upload class

ATTENTION! This class must be used like abstract class and must added validation by protected file extension list to extended class

@api

Since
100.0.2

Definition at line 17 of file Uploader.php.

Constructor & Destructor Documentation

◆ __construct()

__construct (   $fileId,
Mime  $fileMime = null 
)

Init upload

Parameters
string | array$fileId
\Magento\Framework\File\Mime | null$fileMime
Exceptions

Definition at line 168 of file Uploader.php.

171  {
172  $this->_setUploadFileId($fileId);
173  if (!file_exists($this->_file['tmp_name'])) {
174  $code = empty($this->_file['tmp_name']) ? self::TMP_NAME_EMPTY : 0;
175  throw new \Exception('The file was not uploaded.', $code);
176  } else {
177  $this->_fileExists = true;
178  }
179  $this->fileMime = $fileMime ?: \Magento\Framework\App\ObjectManager::getInstance()->get(Mime::class);
180  }
$code
Definition: info.phtml:12

Member Function Documentation

◆ _addDirSeparator()

static _addDirSeparator (   $dir)
staticprotected

Add directory separator

Parameters
string$dir
Returns
string

Definition at line 406 of file Uploader.php.

407  {
408  if (substr($dir, -1) != '/') {
409  $dir .= '/';
410  }
411  return $dir;
412  }

◆ _afterSave()

_afterSave (   $result)
protected

After save logic

Parameters
array$result
Returns
$this @SuppressWarnings(PHPMD.UnusedFormalParameter)

Definition at line 189 of file Uploader.php.

190  {
191  return $this;
192  }

◆ _moveFile()

_moveFile (   $tmpPath,
  $destPath 
)
protected

Move files from TMP folder into destination folder

Parameters
string$tmpPath
string$destPath
Returns
bool|void

Definition at line 293 of file Uploader.php.

294  {
295  if (is_uploaded_file($tmpPath)) {
296  return move_uploaded_file($tmpPath, $destPath);
297  } elseif (is_file($tmpPath)) {
298  return rename($tmpPath, $destPath);
299  }
300  }
elseif(isset( $params[ 'redirect_parent']))
Definition: iframe.phtml:17
rename($oldPath, $newPath, DriverInterface $targetDriver=null)
Definition: File.php:286

◆ _validateFile()

_validateFile ( )
protected

Validate file before save

Returns
void
Exceptions

Definition at line 308 of file Uploader.php.

309  {
310  if ($this->_fileExists === false) {
311  return;
312  }
313 
314  //is file extension allowed
315  if (!$this->checkAllowedExtension($this->getFileExtension())) {
316  throw new \Exception('Disallowed file type.');
317  }
318  //run validate callbacks
319  foreach ($this->_validateCallbacks as $params) {
320  if (is_object($params['object'])
321  && method_exists($params['object'], $params['method'])
322  && is_callable([$params['object'], $params['method']])
323  ) {
324  $params['object']->{$params['method']}($this->_file['tmp_name']);
325  }
326  }
327  }
$params[\Magento\Store\Model\StoreManager::PARAM_RUN_CODE]
Definition: website.php:18

◆ addValidateCallback()

addValidateCallback (   $callbackName,
  $callbackObject,
  $callbackMethod 
)

Add validation callback model for us in self::_validateFile()

Parameters
string$callbackName
object$callbackObject
string$callbackMethodMethod name of $callbackObject. It must have interface (string $tmpFilePath)
Returns
\Magento\Framework\File\Uploader

Definition at line 348 of file Uploader.php.

349  {
350  $this->_validateCallbacks[$callbackName] = ['object' => $callbackObject, 'method' => $callbackMethod];
351  return $this;
352  }

◆ checkAllowedExtension()

checkAllowedExtension (   $extension)

Check if specified extension is allowed

Parameters
string$extension
Returns
boolean

Definition at line 513 of file Uploader.php.

514  {
515  if (!is_array($this->_allowedExtensions) || empty($this->_allowedExtensions)) {
516  return true;
517  }
518 
519  return in_array(strtolower($extension), $this->_allowedExtensions);
520  }

◆ checkMimeType()

checkMimeType (   $validTypes = [])

Used to check if uploaded file mime type is valid or not

Parameters
string[]$validTypes @access public
Returns
bool

Definition at line 421 of file Uploader.php.

422  {
423  if (count($validTypes) > 0) {
424  if (!in_array($this->_getMimeType(), $validTypes)) {
425  return false;
426  }
427  }
428  return true;
429  }

◆ chmod()

chmod (   $file)
protected

Set access permissions to file.

Parameters
string$file
Returns
void
Deprecated:
100.0.8

Definition at line 281 of file Uploader.php.

282  {
283  chmod($file, 0777);
284  }

◆ correctFileNameCase()

correctFileNameCase (   $fileName)

Convert filename to lowercase in case of case-insensitive file names

Parameters
string$fileName
Returns
string

Definition at line 392 of file Uploader.php.

393  {
394  if ($this->_caseInsensitiveFilenames) {
395  return strtolower($fileName);
396  }
397  return $fileName;
398  }
$fileName
Definition: translate.phtml:15

◆ getCorrectFileName()

static getCorrectFileName (   $fileName)
static

Correct filename with special chars and spaces

Parameters
string$fileName
Returns
string

Definition at line 375 of file Uploader.php.

376  {
377  $fileName = preg_replace('/[^a-z0-9_\\-\\.]+/i', '_', $fileName);
378  $fileInfo = pathinfo($fileName);
379 
380  if (preg_match('/^_+$/', $fileInfo['filename'])) {
381  $fileName = 'file.' . $fileInfo['extension'];
382  }
383  return $fileName;
384  }
$fileName
Definition: translate.phtml:15

◆ getDispersionPath()

static getDispersionPath (   $fileName)
static

Get dispertion path

Parameters
string$fileName
Returns
string
Since
101.0.4

Definition at line 642 of file Uploader.php.

643  {
644  $char = 0;
645  $dispertionPath = '';
646  while ($char < 2 && $char < strlen($fileName)) {
647  if (empty($dispertionPath)) {
648  $dispertionPath = '/' . ('.' == $fileName[$char] ? '_' : $fileName[$char]);
649  } else {
650  $dispertionPath = self::_addDirSeparator(
651  $dispertionPath
652  ) . ('.' == $fileName[$char] ? '_' : $fileName[$char]);
653  }
654  $char++;
655  }
656  return $dispertionPath;
657  }
$fileName
Definition: translate.phtml:15

◆ getDispretionPath()

static getDispretionPath (   $fileName)
static

Get dispertion path

Parameters
string$fileName
Returns
string
Deprecated:
101.0.4

Definition at line 630 of file Uploader.php.

631  {
633  }
$fileName
Definition: translate.phtml:15
static getDispersionPath($fileName)
Definition: Uploader.php:642

◆ getFileExtension()

getFileExtension ( )

Returns extension of the uploaded file

Returns
string

Definition at line 334 of file Uploader.php.

335  {
336  return $this->_fileExists ? pathinfo($this->_file['name'], PATHINFO_EXTENSION) : '';
337  }

◆ getNewFileName()

static getNewFileName (   $destinationFile)
static

Get new file name if the same is already exists

Parameters
string$destinationFile
Returns
string

Definition at line 605 of file Uploader.php.

606  {
607  $fileInfo = pathinfo($destinationFile);
608  if (file_exists($destinationFile)) {
609  $index = 1;
610  $baseName = $fileInfo['filename'] . '.' . $fileInfo['extension'];
611  while (file_exists($fileInfo['dirname'] . '/' . $baseName)) {
612  $baseName = $fileInfo['filename'] . '_' . $index . '.' . $fileInfo['extension'];
613  $index++;
614  }
615  $destFileName = $baseName;
616  } else {
617  return $fileInfo['basename'];
618  }
619 
620  return $destFileName;
621  }
$index
Definition: list.phtml:44

◆ getUploadedFileName()

getUploadedFileName ( )

Returns a name of uploaded file

@access public

Returns
string

Definition at line 437 of file Uploader.php.

438  {
440  }

◆ removeValidateCallback()

removeValidateCallback (   $callbackName)

Delete validation callback model for us in self::_validateFile()

Parameters
string$callbackName@access public
Returns
\Magento\Framework\File\Uploader

Definition at line 361 of file Uploader.php.

362  {
363  if (isset($this->_validateCallbacks[$callbackName])) {
364  unset($this->_validateCallbacks[$callbackName]);
365  }
366  return $this;
367  }

◆ save()

save (   $destinationFolder,
  $newFileName = null 
)

Used to save uploaded file into destination folder with original or new file name (if specified).

Parameters
string$destinationFolder
string$newFileName
Returns
array
Exceptions

Definition at line 203 of file Uploader.php.

204  {
205  $this->_validateFile();
206  $this->validateDestination($destinationFolder);
207 
208  $this->_result = false;
209  $destinationFile = $destinationFolder;
210  $fileName = isset($newFileName) ? $newFileName : $this->_file['name'];
211  $fileName = static::getCorrectFileName($fileName);
212  if ($this->_enableFilesDispersion) {
214  $this->setAllowCreateFolders(true);
215  $this->_dispretionPath = static::getDispersionPath($fileName);
216  $destinationFile .= $this->_dispretionPath;
217  $this->_createDestinationFolder($destinationFile);
218  }
219 
220  if ($this->_allowRenameFiles) {
221  $fileName = static::getNewFileName(
222  static::_addDirSeparator($destinationFile) . $fileName
223  );
224  }
225 
226  $destinationFile = static::_addDirSeparator($destinationFile) . $fileName;
227 
228  try {
229  $this->_result = $this->_moveFile($this->_file['tmp_name'], $destinationFile);
230  } catch (\Exception $e) {
231  // if the file exists and we had an exception continue anyway
232  if (file_exists($destinationFile)) {
233  $this->_result = true;
234  } else {
235  throw $e;
236  }
237  }
238 
239  if ($this->_result) {
240  if ($this->_enableFilesDispersion) {
241  $fileName = str_replace('\\', '/', self::_addDirSeparator($this->_dispretionPath)) . $fileName;
242  }
243  $this->_uploadedFileName = $fileName;
244  $this->_uploadedFileDir = $destinationFolder;
245  $this->_result = $this->_file;
246  $this->_result['path'] = $destinationFolder;
247  $this->_result['file'] = $fileName;
248 
249  $this->_afterSave($this->_result);
250  }
251 
252  return $this->_result;
253  }
$fileName
Definition: translate.phtml:15
_moveFile($tmpPath, $destPath)
Definition: Uploader.php:293

◆ setAllowCreateFolders()

setAllowCreateFolders (   $flag)

Used to set _allowCreateFolders value

Parameters
bool$flag@access public
Returns
$this

Definition at line 449 of file Uploader.php.

450  {
451  $this->_allowCreateFolders = $flag;
452  return $this;
453  }

◆ setAllowedExtensions()

setAllowedExtensions (   $extensions = [])

Set allowed extensions

Parameters
string[]$extensions
Returns
$this

Definition at line 499 of file Uploader.php.

500  {
501  foreach ((array)$extensions as $extension) {
502  $this->_allowedExtensions[] = strtolower($extension);
503  }
504  return $this;
505  }

◆ setAllowRenameFiles()

setAllowRenameFiles (   $flag)

Used to set _allowRenameFiles value

Parameters
bool$flag@access public
Returns
$this

Definition at line 462 of file Uploader.php.

463  {
464  $this->_allowRenameFiles = $flag;
465  return $this;
466  }

◆ setFilenamesCaseSensitivity()

setFilenamesCaseSensitivity (   $flag)

File names Case-sensitivity setter

Parameters
bool$flag
Returns
$this

Definition at line 487 of file Uploader.php.

488  {
489  $this->_caseInsensitiveFilenames = $flag;
490  return $this;
491  }

◆ setFilesDispersion()

setFilesDispersion (   $flag)

Used to set _enableFilesDispersion value

Parameters
bool$flag@access public
Returns
$this

Definition at line 475 of file Uploader.php.

476  {
477  $this->_enableFilesDispersion = $flag;
478  return $this;
479  }

Field Documentation

◆ $_allowCreateFolders

$_allowCreateFolders = true
protected

Definition at line 67 of file Uploader.php.

◆ $_allowedExtensions

$_allowedExtensions = null
protected

Definition at line 110 of file Uploader.php.

◆ $_allowRenameFiles

$_allowRenameFiles = false
protected

Definition at line 76 of file Uploader.php.

◆ $_caseInsensitiveFilenames

$_caseInsensitiveFilenames = true
protected

Definition at line 94 of file Uploader.php.

◆ $_dispretionPath

$_dispretionPath = null
protected

Definition at line 100 of file Uploader.php.

◆ $_enableFilesDispersion

$_enableFilesDispersion = false
protected

Definition at line 84 of file Uploader.php.

◆ $_file

$_file
protected

Definition at line 25 of file Uploader.php.

◆ $_fileExists

$_fileExists = false
protected

Definition at line 105 of file Uploader.php.

◆ $_fileMimeType

$_fileMimeType
protected

Definition at line 33 of file Uploader.php.

◆ $_result

$_result
protected

Definition at line 159 of file Uploader.php.

◆ $_uploadedFileDir

$_uploadedFileDir
protected

Definition at line 58 of file Uploader.php.

◆ $_uploadedFileName

$_uploadedFileName
protected

Definition at line 50 of file Uploader.php.

◆ $_uploadType

$_uploadType
protected

Definition at line 41 of file Uploader.php.

◆ $_validateCallbacks

$_validateCallbacks = []
protected

Definition at line 118 of file Uploader.php.

◆ MAX_IMAGE_HEIGHT

const MAX_IMAGE_HEIGHT = 2160

Maximum Image Height resolution in pixels. For image resizing on client side

Deprecated:
See also
\Magento\Framework\Image\Adapter\UploadConfigInterface::getMaxHeight()

Definition at line 151 of file Uploader.php.

◆ MAX_IMAGE_WIDTH

const MAX_IMAGE_WIDTH = 4096

Maximum Image Width resolution in pixels. For image resizing on client side

Deprecated:
See also
\Magento\Framework\Image\Adapter\UploadConfigInterface::getMaxWidth()

Definition at line 144 of file Uploader.php.

◆ MULTIPLE_STYLE

const MULTIPLE_STYLE = 1

Definition at line 130 of file Uploader.php.

◆ SINGLE_STYLE

const SINGLE_STYLE = 0

#+ File upload type (multiple or single)

Definition at line 128 of file Uploader.php.

◆ TMP_NAME_EMPTY

const TMP_NAME_EMPTY = 666

#- Temp file name empty code

Definition at line 137 of file Uploader.php.


The documentation for this class was generated from the following file: