Class luya\admin\helpers\Storage

Inheritanceluya\admin\helpers\Storage
Available since version1.0.0

Helper class to handle remove, upload and moving of storage files.

The class provides common functions in order to work with the Storage component. This helper method will only work if the {{luya\admin\storage\BaseFileSystemStorage}} component is registered which is by default the case when the LUYA admin module is provided.

Public Methods

Hide inherited methods

Method Description Defined By
extractFilesDataFromFilesArray() Extract $_FILES array. luya\admin\helpers\Storage
extractFilesDataFromMultipleFiles() Example Input unform: luya\admin\helpers\Storage
getImageResolution() Get the image resolution of a given file path. luya\admin\helpers\Storage
getUploadErrorMessage() Get the upload error message from a given $_FILES error code id. luya\admin\helpers\Storage
getUploadErrorMessages() Get the file upload error messages. luya\admin\helpers\Storage
moveFileToFolder() Move a storage file to another folder. luya\admin\helpers\Storage
moveFilesToFolder() Move an array of storage fileIds to another folder. luya\admin\helpers\Storage
refreshFile() Update the hash file sum, file size and remove image filter version from this file. luya\admin\helpers\Storage
removeFile() Remove a file from the storage system. luya\admin\helpers\Storage
removeImage() Remove an image from the storage system and database. luya\admin\helpers\Storage
replaceFile() Replace the source of a file on the webeserver based on new and old source path informations. luya\admin\helpers\Storage
replaceFileFromContent() Replace the current file based on image data luya\admin\helpers\Storage
uploadFromContent() Upload a file with content luya\admin\helpers\Storage
uploadFromFileArray() Add File to the storage container by providing the $_FILES array name. luya\admin\helpers\Storage
uploadFromFiles() Add Files to storage component by just providing $_FILES array, used for multi file storage. luya\admin\helpers\Storage

Protected Methods

Hide inherited methods

Method Description Defined By
verifyAndSaveFile() luya\admin\helpers\Storage

Method Details

Hide inherited methods

extractFilesDataFromFilesArray() public static method

Extract $_FILES array.

public static array extractFilesDataFromFilesArray ( array $file )
$file array

                public static function extractFilesDataFromFilesArray(array $file)
{
    if (!isset($file['tmp_name'])) {
        return [];
    }
    $files = [];
    if (is_array($file['tmp_name'])) {
        foreach ($file['tmp_name'] as $index => $value) {
            // skip empty or none exsting tmp file names
            if (!isset($file['tmp_name'][$index]) || empty($file['tmp_name'][$index])) {
                continue;
            }
            // create files structure array
            $files[] = [
                'name' => $file['name'][$index],
                'type' => $file['type'][$index],
                'tmp_name' => $file['tmp_name'][$index],
                'error' => $file['error'][$index],
                'size' => $file['size'][$index],
            ];
        }
    } elseif (isset($file['tmp_name']) && !empty($file['tmp_name'])) {
        $files[] = [
            'name' => $file['name'],
            'type' => $file['type'],
            'tmp_name' => $file['tmp_name'],
            'error' => $file['error'],
            'size' => $file['size'],
        ];
    }
    return $files;
}

            
extractFilesDataFromMultipleFiles() public static method

Example Input unform:

  Array
  (
      [name] => Array
          (
              [attachment] => Array
                  (
                      [0] => Altersfragen-Leimental (4).pdf
                      [1] => Altersfragen-Leimental (2).pdf
                  )

          )

      [type] => Array
          (
              [attachment] => Array
                  (
                      [0] => application/pdf
                      [1] => application/pdf
                  )
          )
      [tmp_name] => Array
          (
              [attachment] => Array
                  (
                      [0] => /tmp/phpNhqnwR
                      [1] => /tmp/phpbZ8XSn
                  )
          )
      [error] => Array
          (
              [attachment] => Array
                  (
                      [0] => 0
                      [1] => 0
                  )
          )
      [size] => Array
          (
              [attachment] => Array
                  (
                      [0] => 261726
                      [1] => 255335
                  )
          )
  )

to:


  Array
  (
      [0] => Array
          (
              [name] => Altersfragen-Leimental (4).pdf
              [type] => application/pdf
              [tmp_name] => /tmp/phpNhqnwR
              [error] => 0
              [size] => 261726
          )
      [1] => Array
          (
              [name] => Altersfragen-Leimental (2).pdf
              [type] => application/pdf
              [tmp_name] => /tmp/phpbZ8XSn
              [error] => 0
              [size] => 255335
          )
  )
public static array extractFilesDataFromMultipleFiles ( array $files )
$files array

                public static function extractFilesDataFromMultipleFiles(array $files)
{
    $data = [];
    $i=0;
    foreach ($files as $type => $field) {
        foreach ($field as $fieldName => $values) {
            if (is_array($values)) {
                foreach ($values as $key => $value) {
                    $data[$key][$type] = $value;
                }
            } else {
                $data[$i][$type] = $values;
            }
        }
    }
    return $data;
}

            
getImageResolution() public static method

Get the image resolution of a given file path.

public static array getImageResolution ( $filePath, $throwException false )
$filePath string
$throwException boolean
throws luya\Exception

                public static function getImageResolution($filePath, $throwException = false)
{
    $dimensions = @getimagesize(Yii::getAlias($filePath));
    $width = 0;
    $height = 0;
    if (isset($dimensions[0]) && isset($dimensions[1])) {
        $width = (int)$dimensions[0];
        $height = (int)$dimensions[1];
    } elseif ($throwException) {
        throw new Exception("Unable to determine the resoltuions of the file $filePath.");
    }
    return [
        'width' => $width,
        'height' => $height,
    ];
}

            
getUploadErrorMessage() public static method

Get the upload error message from a given $_FILES error code id.

public static string getUploadErrorMessage ( $errorId )
$errorId integer

                public static function getUploadErrorMessage($errorId)
{
    $messagesArray = self::getUploadErrorMessages();
    return $messagesArray[$errorId] ?? 'Unknown upload error.';
}

            
getUploadErrorMessages() public static method

Get the file upload error messages.

public static array getUploadErrorMessages ( )
return array

All possible error codes when uploading files with its given message and meaning.

                public static function getUploadErrorMessages()
{
    return [
        UPLOAD_ERR_OK => Module::t('upload_err_message_0'),
        UPLOAD_ERR_INI_SIZE => Module::t('upload_err_message_1'),
        UPLOAD_ERR_FORM_SIZE =>  Module::t('upload_err_message_2'),
        UPLOAD_ERR_PARTIAL =>  Module::t('upload_err_message_3'),
        UPLOAD_ERR_NO_FILE =>  Module::t('upload_err_message_4'),
        UPLOAD_ERR_NO_TMP_DIR =>  Module::t('upload_err_message_6'),
        UPLOAD_ERR_CANT_WRITE =>  Module::t('upload_err_message_7'),
        UPLOAD_ERR_EXTENSION =>  Module::t('upload_err_message_8'),
    ];
}

            
moveFileToFolder() public static method

Move a storage file to another folder.

public static boolean moveFileToFolder ( $fileId, $folderId )
$fileId string|integer
$folderId string|integer

                public static function moveFileToFolder($fileId, $folderId)
{
    $file = StorageFile::findOne($fileId);
    if ($file) {
        $file->updateAttributes(['folder_id' => $folderId]);
        Yii::$app->storage->flushArrays();
        return true;
    }
    return false;
}

            
moveFilesToFolder() public static method

Move an array of storage fileIds to another folder.

public static void moveFilesToFolder ( array $fileIds, $folderId )
$fileIds array
$folderId integer

                public static function moveFilesToFolder(array $fileIds, $folderId)
{
    foreach ($fileIds as $fileId) {
        static::moveFileToFolder($fileId, $folderId);
    }
}

            
refreshFile() public static method

Update the hash file sum, file size and remove image filter version from this file.

public static boolean refreshFile ( $fileId, $filePath )
$fileId integer
$filePath

                public static function refreshFile($fileId, $filePath)
{
    foreach (StorageImage::find()->where(['file_id' => $fileId])->all() as $img) {
        // remove the source
        if ($img->deleteSource()) {
            // recreate image filters
            $img->imageFilter($img->filter_id, false);
        }
    }
    $file = StorageFile::findOne($fileId);
    if (!$file) {
        throw new InvalidArgumentException("Unable to find the given file.");
    }
    $fileHash = FileHelper::md5sum($filePath);
    $fileSize = @filesize($filePath);
    $file->updateAttributes([
        'hash_file' => $fileHash,
        'file_size' => $fileSize,
        'upload_timestamp' => time(),
    ]);
    return true;
}

            
removeFile() public static method

Remove a file from the storage system.

public static boolean removeFile ( $fileId, $cleanup false )
$fileId integer

The file id to delete

$cleanup boolean

If cleanup is enabled, also all images will be deleted, this is by default turned off because casual you want to remove the large source file but not the images where used in several tables and situations.

                public static function removeFile($fileId, $cleanup = false)
{
    $model = StorageFile::find()->where(['id' => $fileId, 'is_deleted' => false])->one();
    if ($model) {
        if ($cleanup) {
            foreach (Yii::$app->storage->findImages(['file_id' => $fileId]) as $imageItem) {
                StorageImage::findOne($imageItem->id)->delete();
            }
        }
        $response = $model->delete();
        Yii::$app->storage->flushArrays();
        return $response;
    }
    return true;
}

            
removeImage() public static method

Remove an image from the storage system and database.

public static boolean removeImage ( $imageId, $cleanup false )
$imageId integer

The corresponding imageId for the {{\luya\admin\models\StorageImage}} Model to remove.

$cleanup boolean

If cleanup is enabled, all other images will be deleted. Even the {{\luya\admin\models\StorageFile}} will be removed from the database and filesystem. By default cleanup is disabled and will only remove the provided $imageId itself from {{\luya\admin\models\StorageImage}}.

                public static function removeImage($imageId, $cleanup = false)
{
    Yii::$app->storage->flushArrays();
    $image = Yii::$app->storage->getImage($imageId);
    if ($cleanup && $image) {
        $fileId = $image->fileId;
        foreach (Yii::$app->storage->findImages(['file_id' => $fileId]) as $imageItem) {
            $storageImage = StorageImage::findOne($imageItem->id);
            if ($storageImage) {
                $storageImage->delete();
            }
        }
    }
    $file = StorageImage::findOne($imageId);
    if ($file) {
        return $file->delete();
    }
    return false;
}

            
replaceFile() public static method

Replace the source of a file on the webeserver based on new and old source path informations.

The replaced file will have the name of the $oldFileSource but the file will be the content of the $newFileSource.

public static boolean replaceFile ( $fileName, $newFileSource, $newFileName )
$fileName string

The filename identifier key in order to find the file based on the locale files system.

$newFileSource string

The path to the new file which is going to have the same name as the old file e.g. path/of/new.jpg. $_FILES['tmp_name']

$newFileName string

The new name of the file which is uploaded, mostly given from $_FILES['name']

return boolean

Whether moving was successful or not.

                public static function replaceFile($fileName, $newFileSource, $newFileName)
{
    try {
        Yii::$app->storage->ensureFileUpload($newFileSource, $newFileName);
    } catch (\Exception $e) {
        return false;
    }
    return Yii::$app->storage->fileSystemReplaceFile($fileName, $newFileSource);
}

            
replaceFileFromContent() public static method (available since version 3.1.0)

Replace the current file based on image data

public static boolean replaceFileFromContent ( $fileName, $newFileContent )
$fileName string
$newFileContent string

                public static function replaceFileFromContent($fileName, $newFileContent)
{
    $newFileSource = @tempnam(sys_get_temp_dir(), 'replaceFromFromContent');
    FileHelper::writeFile($newFileSource, $newFileContent);
    try {
        Yii::$app->storage->ensureFileUpload($newFileSource, $fileName);
    } catch (\Exception $e) {
        return false;
    }
    return Yii::$app->storage->fileSystemReplaceFile($fileName, $newFileSource);
}

            
uploadFromContent() public static method (available since version 3.1.0)

Upload a file with content

public static luya\admin\file\Item uploadFromContent ( $content, $fileName, $folderId 0, $isHidden false )
$content string
$fileName string
$folderId
$isHidden

                public static function uploadFromContent($content, $fileName, $folderId = 0, $isHidden = false)
{
    $fromTempFile = @tempnam(sys_get_temp_dir(), 'uploadFromContent');
    FileHelper::writeFile($fromTempFile, $content);
    return Yii::$app->storage->addFile($fromTempFile, $fileName, $folderId, $isHidden);
}

            
uploadFromFileArray() public static method

Add File to the storage container by providing the $_FILES array name.

Example usage:

$return = Storage::uploadFromFileArray($_FILES['image'], 0, true);
``

Example response

```php
['upload' => false, 'message' => 'file uploaded succesfully', 'file_id' => 123], // success response example
['upload' => true, 'message' => 'No file was uploaded.', 'file_id' => 0], // error response example
public static array uploadFromFileArray ( array $fileArray, $toFolder 0, $isHidden false )
$fileArray array

Its an entry of the files array like $_FILES['logo_image'].

$toFolder integer

The id of the folder the file should be uploaded to, see {{luya\admin\storage\BaseFileSystemStorage::findFolders}}

$isHidden string

Whether the file should be hidden or not.

return array

An array with key upload, message and file_id. When upload is false, an error occured otherwise true. The message key contains the error messages. If no error happend file_id will contain the new uploaded file id.

                public static function uploadFromFileArray(array $fileArray, $toFolder = 0, $isHidden = false)
{
    $files = self::extractFilesDataFromFilesArray($fileArray);
    if (count($files) !== 1) {
        return ['upload' => false, 'message' => 'no image found', 'file_id' => 0];
    }
    return self::verifyAndSaveFile($files[0], $toFolder, $isHidden);
}

            
uploadFromFiles() public static method

Add Files to storage component by just providing $_FILES array, used for multi file storage.

Example usage:

$return = Storage::uploadFromFiles($_FILES, 0, true);

Example response

['upload' => false, 'message' => 'file uploaded succesfully', 'file_id' => 123], // success response example
['upload' => true, 'message' => 'No file was uploaded.', 'file_id' => 0], // error response example
public static array uploadFromFiles ( array $filesArray, $toFolder 0, $isHidden false )
$filesArray array

Use $_FILES array.

$toFolder integer

The id of the folder the file should be uploaded to, see {{luya\admin\storage\BaseFileSystemStorage::findFolders}}

$isHidden string

Whether the file should be hidden or not.

return array

An array with key upload, message and file_id. When upload is false, an error occured otherwise true. The message key contains the error messages. If no error happend file_id will contain the new uploaded file id.

                public static function uploadFromFiles(array $filesArray, $toFolder = 0, $isHidden = false)
{
    $files = [];
    foreach ($filesArray as $fileArrayKey => $file) {
        $files = array_merge($files, self::extractFilesDataFromFilesArray($file));
    }
    foreach ($files as $file) {
        return self::verifyAndSaveFile($file, $toFolder, $isHidden);
    }
    return ['upload' => false, 'message' => 'no files selected or empty files list.', 'file_id' => 0];
}

            
verifyAndSaveFile() protected static method

protected static array verifyAndSaveFile ( array $file, $toFolder 0, $isHidden false )
$file array

An array with the following keys available:

  • name:
  • type:
  • tmp_name:
  • error:
  • size:
$toFolder \luya\admin\helpers\number
$isHidden string

                protected static function verifyAndSaveFile(array $file, $toFolder = 0, $isHidden = false)
{
    try {
        if ($file['error'] !== UPLOAD_ERR_OK) {
            return ['upload' => false, 'message' => static::getUploadErrorMessage($file['error']), 'file_id' => 0];
        }
        $file = Yii::$app->storage->addFile($file['tmp_name'], $file['name'], $toFolder, $isHidden);
        if ($file) {
            return ['upload' => true, 'message' => 'file uploaded succesfully', 'file_id' => $file->id];
        }
    } catch (Exception $err) {
        return ['upload' => false, 'message' => $err->getMessage(), 'file_id' => 0];
    }
    return ['upload' => false, 'message' => 'no files selected or empty files list.', 'file_id' => 0];
}