Abstract Class luya\admin\storage\BaseFileSystemStorage
Inheritance | luya\admin\storage\BaseFileSystemStorage » yii\base\Component » yii\base\BaseObject |
---|---|
Implements | yii\base\Configurable |
Uses Traits | luya\traits\CacheableTrait |
Subclasses | luya\admin\filesystem\DummyFileSystem, luya\admin\filesystem\LocalFileSystem, luya\testsuite\components\DummyFileSystem |
Available since version | 1.0.0 |
Source Code | https://github.com/luyadev/luya-module-admin/blob/master/src/storage/BaseFileSystemStorage.php |
Storage Container for reading, saving and holding files.
Create images, files, manipulate, foreach and get details. The storage container will be the singleton similar instance containing all the loaded images and files.
The base storage system is implemented by filesystems:
- {{luya\admin\filesystem\LocalStorage}} (Default system for the admin module)
- {{luya\admin\filesystem\S3}}
As files, images and folders implement the same traits you can also read more about enhanced usage:
- Querying Data with {{\luya\admin\storage\QueryTrait}}
- Where conditions {{\luya\admin\storage\QueryTrait::where()}}
Handling Files ¶
First adding a new file to the Storage system using the {{\luya\admin\storage\BaseFileSystemStorage::addFile()}} method.
Yii::$app->storage->addFile('/the/path/to/File.jpg', 'File.jpg', 0, 1);
The response of the add file method is an {{\luya\admin\file\Item}} Object.
Get an array of files based on search parameters (When not passing any arguments all files would be returned.):
Yii::$app->storage->findFiles(['is_hidden' => 0, 'is_deleted' => 0]);
In order to get a single file object based on its ID use:
Yii::$app->storage->getFile(5);
To find a file based on other where arguments instead of the id use findFile:
Yii::$app->storage->findFile(['name' => 'MyFile.jpg']);
Handling Images ¶
An image object is always based on the {{\luya\admin\file\Item}} object and a {{luya\admin\base\Filter}}. In order to add an image you already need a fileId and filterId. If the filterId is 0, it means no additional filter will be applied.
Yii::$app->storage->addImage(123, 0); // create an image from file object id 123 without filter.
The newly created image will return a {{luya\admin\image\Item}} object.
In order to find one image:
Yii::$app->storage->findImage(['id' => 123]);
or find one image by its ID:
Yii::$app->storage->getImage(123);
To get an array of images based on where conditions use:
Yii::$app->storage->findImages(['file_id' => 1, 'filter_id' => 0]);
Public Properties
Property | Type | Description | Defined By |
---|---|---|---|
$autoFixMissingImageSources | boolean | When enabled the storage component will try to recreated missing images when {{luya\admin\image\Item::getSource()}} of an image is called but the getFileExists() does return false, which means that the source file has been deleted. |
luya\admin\storage\BaseFileSystemStorage |
$behaviors | yii\base\Behavior[] | List of behaviors attached to this component. | yii\base\Component |
$dangerousExtensions | array | The extension which will be rejected. | luya\admin\storage\BaseFileSystemStorage |
$dangerousMimeTypes | array | The mime types which will be rejected. | luya\admin\storage\BaseFileSystemStorage |
$filesArray | array | An array containing all files | luya\admin\storage\BaseFileSystemStorage |
$filtersArray | array | An array with all filters | luya\admin\storage\BaseFileSystemStorage |
$foldersArray | array | An array containing all folders | luya\admin\storage\BaseFileSystemStorage |
$imageMimeTypes | array | A list of mime types which are indicating images | luya\admin\storage\BaseFileSystemStorage |
$imagesArray | array | An array containg all images | luya\admin\storage\BaseFileSystemStorage |
$queueFilters | boolean | When enabled, the filters in the {{luya\admin\storage\BaseFileSystemStorage::$queueFiltersList}} will be applied to the uploaded file if the file is an image. | luya\admin\storage\BaseFileSystemStorage |
$queueFiltersList | array | If {{luya\admin\storage\BaseFileSystemStorage::$queueFilters}} is enabled, the following image filters will be processed. | luya\admin\storage\BaseFileSystemStorage |
$queueJobIds | array | If the storage system pushed any jobs into the queue, this array holds the queue job ids. | luya\admin\storage\BaseFileSystemStorage |
$request | luya\web\Request | Request object resolved by the Dependency Injector. | luya\admin\storage\BaseFileSystemStorage |
$secureFileUpload | boolean | Whether secure file upload is enabled or not. | luya\admin\storage\BaseFileSystemStorage |
$serverPath | string | Get the server path (for php) to the storage folder. | luya\admin\storage\BaseFileSystemStorage |
$whitelistExtensions | array | An array with extensions which are whitelisted. | luya\admin\storage\BaseFileSystemStorage |
$whitelistMimeTypes | array | The mime types inside this array are whitelistet and will be stored whether validation failes or not. | luya\admin\storage\BaseFileSystemStorage |
Public Methods
Method | Description | Defined By |
---|---|---|
__call() | Calls the named method which is not a class method. | yii\base\Component |
__clone() | This method is called after the object is created by cloning an existing one. | yii\base\Component |
__construct() | Consturctor resolveds Request component from DI container | luya\admin\storage\BaseFileSystemStorage |
__get() | Returns the value of a component property. | yii\base\Component |
__isset() | Checks if a property is set, i.e. defined and not null. | yii\base\Component |
__set() | Sets the value of a component property. | yii\base\Component |
__unset() | Sets a component property to be null. | yii\base\Component |
addFile() | Add a new file based on the source to the storage system. | luya\admin\storage\BaseFileSystemStorage |
addFolder() | Add new folder to the storage system. | luya\admin\storage\BaseFileSystemStorage |
addImage() | Add a new image based an existing file Id. | luya\admin\storage\BaseFileSystemStorage |
attachBehavior() | Attaches a behavior to this component. | yii\base\Component |
attachBehaviors() | Attaches a list of behaviors to the component. | yii\base\Component |
behaviors() | Returns a list of behaviors that this component should behave as. | yii\base\Component |
canGetProperty() | Returns a value indicating whether a property can be read. | yii\base\Component |
canSetProperty() | Returns a value indicating whether a property can be set. | yii\base\Component |
className() | Returns the fully qualified name of this class. | yii\base\BaseObject |
createImage() | Just creating the image based on input informations without usage of storage files or images list. | luya\admin\storage\BaseFileSystemStorage |
deleteHasCache() | Remove a value from the cache if caching is enabled. | luya\traits\CacheableTrait |
detachBehavior() | Detaches a behavior from the component. | yii\base\Component |
detachBehaviors() | Detaches all behaviors from the component. | yii\base\Component |
ensureBehaviors() | Makes sure that the behaviors declared in behaviors() are attached to this component. | yii\base\Component |
ensureFileUpload() | Ensure a file uploads and return relevant file infos. | luya\admin\storage\BaseFileSystemStorage |
fileAbsoluteHttpPath() | Return the absolute http path for a given file on the file system. | luya\admin\storage\BaseFileSystemStorage |
fileHttpPath() | Return the http path for a given file on the file system. | luya\admin\storage\BaseFileSystemStorage |
fileServerPath() | Returns the path internal server path to the given file on the file system. | luya\admin\storage\BaseFileSystemStorage |
fileSystemContent() | Get the content of the file on the given file system. | luya\admin\storage\BaseFileSystemStorage |
fileSystemDeleteFile() | Delete a given file source on the filesystem. | luya\admin\storage\BaseFileSystemStorage |
fileSystemExists() | Check if the file exists on the given file system. | luya\admin\storage\BaseFileSystemStorage |
fileSystemReplaceFile() | Replace an existing file source with a new one on the filesystem. | luya\admin\storage\BaseFileSystemStorage |
fileSystemSaveFile() | Save the given file source as a new file with the given fileName on the filesystem. | luya\admin\storage\BaseFileSystemStorage |
fileSystemStream() | Generate a stream/resource for the file to download | luya\admin\storage\BaseFileSystemStorage |
findFile() | Get a single file based on a where condition. | luya\admin\storage\BaseFileSystemStorage |
findFiles() | Get an array with all files based on a where condition. | luya\admin\storage\BaseFileSystemStorage |
findFolder() | Get a single folder based on a where condition. | luya\admin\storage\BaseFileSystemStorage |
findFolders() | Get an array with all folders based on a where condition. | luya\admin\storage\BaseFileSystemStorage |
findImage() | Get a single image based on a where condition. | luya\admin\storage\BaseFileSystemStorage |
findImages() | Get an array with all images based on a where condition. | luya\admin\storage\BaseFileSystemStorage |
flushArrays() | Will force to refresh all container arrays and clean up the cache | luya\admin\storage\BaseFileSystemStorage |
flushHasCache() | Deletes all values from cache. | luya\traits\CacheableTrait |
flushImageArray() | Flush only images array and image cache. | luya\admin\storage\BaseFileSystemStorage |
getBehavior() | Returns the named behavior object. | yii\base\Component |
getBehaviors() | Returns all behaviors attached to this component. | yii\base\Component |
getFile() | Get a single file based on the ID. | luya\admin\storage\BaseFileSystemStorage |
getFilesArray() | Get all storage files as an array from database. | luya\admin\storage\BaseFileSystemStorage |
getFilesArrayItem() | Get a single file by file id from the files array. | luya\admin\storage\BaseFileSystemStorage |
getFilterId() | Get the filter id based on the identifier. | luya\admin\storage\BaseFileSystemStorage |
getFiltersArray() | Get all storage filters as an array from database. | luya\admin\storage\BaseFileSystemStorage |
getFiltersArrayItem() | Get a single filter by filter identifier from the filters array. | luya\admin\storage\BaseFileSystemStorage |
getFolder() | Get a single folder based on the ID. | luya\admin\storage\BaseFileSystemStorage |
getFoldersArray() | Get all storage folders as an array from database. | luya\admin\storage\BaseFileSystemStorage |
getFoldersArrayItem() | Get a single folder by folder id from the folders array. | luya\admin\storage\BaseFileSystemStorage |
getHasCache() | Get the caching data if caching is allowed and there is any data stored for this key. | luya\traits\CacheableTrait |
getImage() | Get a single image based on the ID. | luya\admin\storage\BaseFileSystemStorage |
getImagesArray() | Get all storage images as an array from database. | luya\admin\storage\BaseFileSystemStorage |
getImagesArrayItem() | Get a single image by image id from the files array. | luya\admin\storage\BaseFileSystemStorage |
getOrSetHasCache() | Method combines both setHasCache() and getHasCache() methods to retrieve value identified by a $key, or to store the result of $closure execution if there is no cache available for the $key. | luya\traits\CacheableTrait |
hasEventHandlers() | Returns a value indicating whether there is any handler attached to the named event. | yii\base\Component |
hasMethod() | Returns a value indicating whether a method is defined. | yii\base\Component |
hasProperty() | Returns a value indicating whether a property is defined for this component. | yii\base\Component |
init() | Initializes the object. | yii\base\BaseObject |
isCachable() | Check if the current configuration of the application and the property allows a caching of the language container data. | luya\traits\CacheableTrait |
off() | Detaches an existing event handler from this component. | yii\base\Component |
on() | Attaches an event handler to an event. | yii\base\Component |
processThumbnails() | This method allwos you to generate all thumbnails for the file manager, you can trigger this process when importing or creating several images at once, so the user does not have to create the thumbnails | luya\admin\storage\BaseFileSystemStorage |
setFilesArray() | Setter method for fiels array. | luya\admin\storage\BaseFileSystemStorage |
setFiltersArray() | Setter method for filters array. | luya\admin\storage\BaseFileSystemStorage |
setHasCache() | Store cache data for a specific key if caching is enabled in this application. | luya\traits\CacheableTrait |
setImagesArray() | Setter method for images array. | luya\admin\storage\BaseFileSystemStorage |
trigger() | Triggers an event. | yii\base\Component |
Constants
Constant | Value | Description | Defined By |
---|---|---|---|
CACHE_KEY_FILE | 'storage_fileCacheKey' | luya\admin\storage\BaseFileSystemStorage | |
CACHE_KEY_FILTER | 'storage_filterCacheKey' | luya\admin\storage\BaseFileSystemStorage | |
CACHE_KEY_FOLDER | 'storage_folderCacheKey' | luya\admin\storage\BaseFileSystemStorage | |
CACHE_KEY_IMAGE | 'storage_imageCacheKey' | luya\admin\storage\BaseFileSystemStorage | |
FILE_SAVE_EVENT | 'onFileSave' | luya\admin\storage\BaseFileSystemStorage | |
FILE_UPDATE_EVENT | 'onFileUpdate' | luya\admin\storage\BaseFileSystemStorage |
Property Details
When enabled the storage component will try to recreated missing images when {{luya\admin\image\Item::getSource()}} of an
image is called but the getFileExists()
does return false, which means that the source file has been deleted.
So in those cases the storage component will automatiaccly try to recreated this image based on the filterId and
fileId.
The extension which will be rejected.
The mime types which will be rejected.
'application/x-msdownload',
'application/x-msdos-program',
'application/x-msdos-windows',
'application/x-download',
'application/bat',
'application/x-bat',
'application/com',
'application/x-com',
'application/exe',
'application/x-exe',
'application/x-winexe',
'application/x-winhlp',
'application/x-winhelp',
'application/x-javascript',
'application/hta',
'application/x-ms-shortcut',
'application/octet-stream',
'vms/exe',
'text/javascript',
'text/scriptlet',
'text/x-php',
'text/plain',
'application/x-spss',
'image/svg+xml',
]
A list of mime types which are indicating images
When enabled, the filters in the {{luya\admin\storage\BaseFileSystemStorage::$queueFiltersList}} will be applied to the uploaded file if the file is an image. We
recommend you turn this on, only when using the queue/listen
command see [[app-queue.md]], because the user needs to wait until the queue job is processed
in the admin ui.
If {{luya\admin\storage\BaseFileSystemStorage::$queueFilters}} is enabled, the following image filters will be processed. We recommend
to add the default filters which are used in the admin ui (for file manager thumbnails). Therefore those are default values ['tiny-crop', 'medium-thumbnail']
.
If the storage system pushed any jobs into the queue, this array holds the queue job ids.
Request object resolved by the Dependency Injector.
Whether secure file upload is enabled or not. If enabled dangerous mime types and extensions will
be rejected and the file mime type needs to be verified by phps fileinfo
extension.
Get the server path (for php) to the storage folder.
An array with extensions which are whitelisted. This can be very dangerous as it will skip the check whether the mime type is matching the extension types. If an extensions in {{$dangerousExtensions}} and {{$whitelistExtensions}} it will still throw an exception as {{$dangerousExtensions}} take precedence over {{$$whitelistExtensions}}.
The mime types inside this array are whitelistet and will be stored whether validation failes or not. For example if mime type 'text/plain' is given for a 'csv' extension, the valid extensions would be 'txt' or 'log', this would throw an exception, therefore you can whitelist the 'text/plain' mime type. This can be usefull when uploading csv files.
Method Details
Defined in: yii\base\Component::__call()
Calls the named method which is not a class method.
This method will check if any attached behavior has the named method and will execute it if available.
Do not call this method directly as it is a PHP magic method that will be implicitly called when an unknown method is being invoked.
public mixed __call ( $name, $params ) | ||
$name | string |
The method name |
$params | array |
Method parameters |
return | mixed |
The method return value |
---|---|---|
throws | yii\base\UnknownMethodException |
when calling unknown method |
public function __call($name, $params)
{
$this->ensureBehaviors();
foreach ($this->_behaviors as $object) {
if ($object->hasMethod($name)) {
return call_user_func_array([$object, $name], $params);
}
}
throw new UnknownMethodException('Calling unknown method: ' . get_class($this) . "::$name()");
}
Defined in: yii\base\Component::__clone()
This method is called after the object is created by cloning an existing one.
It removes all behaviors because they are attached to the old object.
public void __clone ( ) |
public function __clone()
{
$this->_events = [];
$this->_eventWildcards = [];
$this->_behaviors = null;
}
Consturctor resolveds Request component from DI container
public void __construct ( luya\web\Request $request, array $config = [] ) | ||
$request | luya\web\Request |
The request component class resolved by the Dependency Injector. |
$config | array |
public function __construct(Request $request, array $config = [])
{
$this->request = $request;
parent::__construct($config);
}
Defined in: yii\base\Component::__get()
Returns the value of a component property.
This method will check in the following order and act accordingly:
- a property defined by a getter: return the getter result
- a property of a behavior: return the behavior property value
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing $value = $component->property;
.
See also __set().
public mixed __get ( $name ) | ||
$name | string |
The property name |
return | mixed |
The property value or the value of a behavior's property |
---|---|---|
throws | yii\base\UnknownPropertyException |
if the property is not defined |
throws | yii\base\InvalidCallException |
if the property is write-only. |
public function __get($name)
{
$getter = 'get' . $name;
if (method_exists($this, $getter)) {
// read property, e.g. getName()
return $this->$getter();
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canGetProperty($name)) {
return $behavior->$name;
}
}
if (method_exists($this, 'set' . $name)) {
throw new InvalidCallException('Getting write-only property: ' . get_class($this) . '::' . $name);
}
throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name);
}
Defined in: yii\base\Component::__isset()
Checks if a property is set, i.e. defined and not null.
This method will check in the following order and act accordingly:
- a property defined by a setter: return whether the property is set
- a property of a behavior: return whether the property is set
- return
false
for non existing properties
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing isset($component->property)
.
public boolean __isset ( $name ) | ||
$name | string |
The property name or the event name |
return | boolean |
Whether the named property is set |
---|
public function __isset($name)
{
$getter = 'get' . $name;
if (method_exists($this, $getter)) {
return $this->$getter() !== null;
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canGetProperty($name)) {
return $behavior->$name !== null;
}
}
return false;
}
Defined in: yii\base\Component::__set()
Sets the value of a component property.
This method will check in the following order and act accordingly:
- a property defined by a setter: set the property value
- an event in the format of "on xyz": attach the handler to the event "xyz"
- a behavior in the format of "as xyz": attach the behavior named as "xyz"
- a property of a behavior: set the behavior property value
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing $component->property = $value;
.
See also __get().
public void __set ( $name, $value ) | ||
$name | string |
The property name or the event name |
$value | mixed |
The property value |
throws | yii\base\UnknownPropertyException |
if the property is not defined |
---|---|---|
throws | yii\base\InvalidCallException |
if the property is read-only. |
public function __set($name, $value)
{
$setter = 'set' . $name;
if (method_exists($this, $setter)) {
// set property
$this->$setter($value);
return;
} elseif (strncmp($name, 'on ', 3) === 0) {
// on event: attach event handler
$this->on(trim(substr($name, 3)), $value);
return;
} elseif (strncmp($name, 'as ', 3) === 0) {
// as behavior: attach behavior
$name = trim(substr($name, 3));
$this->attachBehavior($name, $value instanceof Behavior ? $value : Yii::createObject($value));
return;
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canSetProperty($name)) {
$behavior->$name = $value;
return;
}
}
if (method_exists($this, 'get' . $name)) {
throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '::' . $name);
}
throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '::' . $name);
}
Defined in: yii\base\Component::__unset()
Sets a component property to be null.
This method will check in the following order and act accordingly:
- a property defined by a setter: set the property value to be null
- a property of a behavior: set the property value to be null
Do not call this method directly as it is a PHP magic method that
will be implicitly called when executing unset($component->property)
.
public void __unset ( $name ) | ||
$name | string |
The property name |
throws | yii\base\InvalidCallException |
if the property is read only. |
---|
public function __unset($name)
{
$setter = 'set' . $name;
if (method_exists($this, $setter)) {
$this->$setter(null);
return;
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canSetProperty($name)) {
$behavior->$name = null;
return;
}
}
throw new InvalidCallException('Unsetting an unknown or read-only property: ' . get_class($this) . '::' . $name);
}
Add a new file based on the source to the storage system.
When using the $_FILES array you can also make usage of the file helper methods:
- {{luya\admin\helpers\Storage::uploadFromFiles}}
- {{luya\admin\helpers\Storage::uploadFromFileArray}}
When not using the $_FILES array:
Yii::$app->storage->addFile('/the/path/to/File.jpg', 'File.jpg', 0, 1);
public boolean|luya\admin\file\Item|luya\Exception addFile ( $fileSource, $fileName, $folderId = 0, $isHidden = false ) | ||
$fileSource | string |
Path to the file source where the file should be created from |
$fileName | string |
The name of this file (must contain data type suffix). |
$folderId | integer |
The id of the folder where the file should be stored in. |
$isHidden | boolean |
Should the file visible in the filemanager or not. |
return | boolean|luya\admin\file\Item|luya\Exception |
Returns the item object, if an error happens an exception is thrown. |
---|---|---|
throws | luya\Exception |
public function addFile($fileSource, $fileName, $folderId = 0, $isHidden = false)
{
$fileData = $this->ensureFileUpload($fileSource, $fileName);
$fileHash = FileHelper::md5sum($fileSource);
$newName = implode('.', [$fileData['secureFileName'].'_'.$fileData['hashName'], $fileData['extension']]);
if (!$this->fileSystemSaveFile($fileSource, $newName)) {
return false;
}
$model = new StorageFile();
$model->setAttributes([
'name_original' => $fileName,
'name_new' => $fileData['secureFileName'],
'name_new_compound' => $newName,
'mime_type' => $fileData['mimeType'],
'extension' => $fileData['extension'],
'folder_id' => (int) $folderId,
'hash_file' => $fileHash,
'hash_name' => $fileData['hashName'],
'is_hidden' => $isHidden ? true : false,
'is_deleted' => false,
'file_size' => $fileData['fileSize'],
'caption' => null,
'inline_disposition' => (int) Module::getInstance()->fileDefaultInlineDisposition,
]);
if ($model->validate()) {
if ($model->save()) {
if ($model->isImage && $this->queueFilters) {
$this->queueJobIds[] = Yii::$app->adminqueue->push(new ImageFilterJob(['fileId' => $model->id, 'filterIdentifiers' => $this->queueFiltersList]));
}
$this->trigger(self::FILE_SAVE_EVENT, new FileEvent(['file' => $model]));
$this->deleteHasCache(self::CACHE_KEY_FILE);
$this->_filesArray[$model->id] = $model->toArray();
return $this->getFile($model->id);
}
}
return false;
}
Add new folder to the storage system.
public boolean|integer addFolder ( $folderName, $parentFolderId = 0 ) | ||
$folderName | string |
The name of the new folder |
$parentFolderId | integer |
If its a subfolder the id of the parent folder must be provided. |
return | boolean|integer |
Returns the folder id or false if something went wrong. |
---|
public function addFolder($folderName, $parentFolderId = 0)
{
$model = new StorageFolder();
$model->name = $folderName;
$model->parent_id = $parentFolderId;
$model->timestamp_create = time();
$this->deleteHasCache(self::CACHE_KEY_FOLDER);
if ($model->save(false)) {
return $model->id;
}
return false;
}
Add a new image based an existing file Id.
The storage system uses the same file base, for images and files. The difference between a file and an image is the filter which is applied.
Only files of the type image can be used (or added) as an image.
An image object is always based on the {{\luya\admin\file\Item}} object and a {{luya\admin\base\Filter}}.
Yii::$app->storage->addImage(123, 0); // create an image from file object id 123 without filter.
public boolean|luya\admin\image\Item|luya\Exception addImage ( $fileId, $filterId = 0, $throwException = false ) | ||
$fileId | integer |
The id of the file where image should be created from. |
$filterId | integer |
The id of the filter which should be applied to, if filter is 0, no filter will be added. Filter can new also be the string name of the filter like |
$throwException | boolean |
Whether the addImage should throw an exception or just return boolean |
return | boolean|luya\admin\image\Item|luya\Exception |
Returns the item object, if an error happens and $throwException is off |
---|---|---|
throws | luya\Exception |
public function addImage($fileId, $filterId = 0, $throwException = false)
{
try {
// if the filterId is provded as a string the filter will be looked up by its name in the get filters array list.
if (is_string($filterId) && !is_numeric($filterId)) {
$filterLookup = $this->getFiltersArrayItem($filterId);
if (!$filterLookup) {
throw new Exception("The provided filter name " . $filterId . " does not exist.");
}
$filterId = $filterLookup['id'];
}
$query = (new \luya\admin\image\Query())->where(['file_id' => $fileId, 'filter_id' => $filterId])->one();
if ($query && $query->fileExists) {
return $query;
}
$fileQuery = $this->getFile($fileId);
if (!$fileQuery || !$fileQuery->fileExists) {
if ($fileQuery !== false) {
throw new Exception("Unable to create image, the base file server source '{$fileQuery->serverSource}' does not exist.");
}
throw new Exception("Unable to find the file with id '{$fileId}', image can not be created.");
}
$model = $this->createImage($fileId, $filterId);
if (!$model) {
throw new Exception("Unable to create the image on the filesystem.");
}
$this->_imagesArray[$model->id] = $model->toArray();
$this->deleteHasCache(self::CACHE_KEY_IMAGE);
return $this->getImage($model->id);
} catch (\Exception $err) {
if ($throwException) {
throw $err;
}
}
return false;
}
Defined in: yii\base\Component::attachBehavior()
Attaches a behavior to this component.
This method will create the behavior object based on the given configuration. After that, the behavior object will be attached to this component by calling the yii\base\Behavior::attach() method.
See also detachBehavior().
public yii\base\Behavior attachBehavior ( $name, $behavior ) | ||
$name | string |
The name of the behavior. |
$behavior | string|array|yii\base\Behavior |
The behavior configuration. This can be one of the following:
|
return | yii\base\Behavior |
The behavior object |
---|
public function attachBehavior($name, $behavior)
{
$this->ensureBehaviors();
return $this->attachBehaviorInternal($name, $behavior);
}
Defined in: yii\base\Component::attachBehaviors()
Attaches a list of behaviors to the component.
Each behavior is indexed by its name and should be a yii\base\Behavior object, a string specifying the behavior class, or an configuration array for creating the behavior.
See also attachBehavior().
public void attachBehaviors ( $behaviors ) | ||
$behaviors | array |
List of behaviors to be attached to the component |
public function attachBehaviors($behaviors)
{
$this->ensureBehaviors();
foreach ($behaviors as $name => $behavior) {
$this->attachBehaviorInternal($name, $behavior);
}
}
Defined in: yii\base\Component::behaviors()
Returns a list of behaviors that this component should behave as.
Child classes may override this method to specify the behaviors they want to behave as.
The return value of this method should be an array of behavior objects or configurations indexed by behavior names. A behavior configuration can be either a string specifying the behavior class or an array of the following structure:
'behaviorName' => [
'class' => 'BehaviorClass',
'property1' => 'value1',
'property2' => 'value2',
]
Note that a behavior class must extend from yii\base\Behavior. Behaviors can be attached using a name or anonymously. When a name is used as the array key, using this name, the behavior can later be retrieved using getBehavior() or be detached using detachBehavior(). Anonymous behaviors can not be retrieved or detached.
Behaviors declared in this method will be attached to the component automatically (on demand).
public array behaviors ( ) | ||
return | array |
The behavior configurations. |
---|
public function behaviors()
{
return [];
}
Defined in: yii\base\Component::canGetProperty()
Returns a value indicating whether a property can be read.
A property can be read if:
- the class has a getter method associated with the specified name (in this case, property name is case-insensitive);
- the class has a member variable with the specified name (when
$checkVars
is true); - an attached behavior has a readable property of the given name (when
$checkBehaviors
is true).
See also canSetProperty().
public boolean canGetProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | string |
The property name |
$checkVars | boolean |
Whether to treat member variables as properties |
$checkBehaviors | boolean |
Whether to treat behaviors' properties as properties of this component |
return | boolean |
Whether the property can be read |
---|
public function canGetProperty($name, $checkVars = true, $checkBehaviors = true)
{
if (method_exists($this, 'get' . $name) || $checkVars && property_exists($this, $name)) {
return true;
} elseif ($checkBehaviors) {
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canGetProperty($name, $checkVars)) {
return true;
}
}
}
return false;
}
Defined in: yii\base\Component::canSetProperty()
Returns a value indicating whether a property can be set.
A property can be written if:
- the class has a setter method associated with the specified name (in this case, property name is case-insensitive);
- the class has a member variable with the specified name (when
$checkVars
is true); - an attached behavior has a writable property of the given name (when
$checkBehaviors
is true).
See also canGetProperty().
public boolean canSetProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | string |
The property name |
$checkVars | boolean |
Whether to treat member variables as properties |
$checkBehaviors | boolean |
Whether to treat behaviors' properties as properties of this component |
return | boolean |
Whether the property can be written |
---|
public function canSetProperty($name, $checkVars = true, $checkBehaviors = true)
{
if (method_exists($this, 'set' . $name) || $checkVars && property_exists($this, $name)) {
return true;
} elseif ($checkBehaviors) {
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canSetProperty($name, $checkVars)) {
return true;
}
}
}
return false;
}
::class
instead.
Defined in: yii\base\BaseObject::className()
Returns the fully qualified name of this class.
public static string className ( ) | ||
return | string |
The fully qualified name of this class. |
---|
public static function className()
{
return get_called_class();
}
Just creating the image based on input informations without usage of storage files or images list.
public luya\admin\models\StorageImage|false createImage ( $fileId, $filterId ) | ||
$fileId | integer |
The id of the file to create filter of |
$filterId | integer |
The filter id to apply on the given file. |
return | luya\admin\models\StorageImage|false |
Returns the storage image model on success, otherwise false. |
---|
public function createImage($fileId, $filterId)
{
gc_collect_cycles();
$image = StorageImage::find()->where(['file_id' => $fileId, 'filter_id' => $filterId])->one();
// the image exists already in the database and the file system
if ($image && $image->fileExists) {
return $image;
}
$file = StorageFile::findOne($fileId);
// https://github.com/luyadev/luya-module-admin/issues/415
if (!$file && !$file->isImage) {
return false;
}
// create the new image name
$fileName = $filterId.'_'.$file->name_new_compound;
$fromTempFile = @tempnam(sys_get_temp_dir(), 'fromFile'); // @see https://www.php.net/manual/de/function.tempnam.php#120451 & https://github.com/luyadev/luya-module-admin/issues/316
$fromTempFile.= $fileName;
$content = $file->getContent();
// it seems the content can not be found.
if ($content === false) {
return false;
}
$writeFile = FileHelper::writeFile($fromTempFile, $content);
// unable to write the temp file
if (!$writeFile) {
return false;
}
// create a temp file
$tempFile = @tempnam(sys_get_temp_dir(), 'destFile'); // @see https://www.php.net/manual/de/function.tempnam.php#120451 & https://github.com/luyadev/luya-module-admin/issues/316
$tempFile.= $fileName;
// there is no filter, which means we create an image version for a given file.
if (empty($filterId)) {
@copy($fromTempFile, $tempFile);
} else {
$filter = StorageFilter::findOne($filterId);
if (!$filter || !$filter->applyFilterChain($fromTempFile, $tempFile)) {
return false;
}
}
$resolution = Storage::getImageResolution($tempFile);
// now copy the file to the storage system
$this->fileSystemSaveFile($tempFile, $fileName);
FileHelper::unlink($tempFile);
FileHelper::unlink($fromTempFile);
$this->flushImageArray();
// ensure the existing of the model
if ($image) {
$image->resolution_height = $resolution['height'];
$image->resolution_width = $resolution['width'];
$image->save();
return $image;
}
$image = new StorageImage();
$image->file_id = $fileId;
$image->filter_id = $filterId;
$image->resolution_height = $resolution['height'];
$image->resolution_width = $resolution['width'];
if (!$image->save()) {
return false;
}
return $image;
}
Defined in: luya\traits\CacheableTrait::deleteHasCache()
Remove a value from the cache if caching is enabled.
public boolean deleteHasCache ( $key ) | ||
$key | string|array |
The cache identifier |
return | boolean |
Whether delete of key has been success or not |
---|
public function deleteHasCache($key)
{
if ($this->isCachable()) {
return Yii::$app->cache->delete($key);
}
return false;
}
Defined in: yii\base\Component::detachBehavior()
Detaches a behavior from the component.
The behavior's yii\base\Behavior::detach() method will be invoked.
public yii\base\Behavior|null detachBehavior ( $name ) | ||
$name | string |
The behavior's name. |
return | yii\base\Behavior|null |
The detached behavior. Null if the behavior does not exist. |
---|
public function detachBehavior($name)
{
$this->ensureBehaviors();
if (isset($this->_behaviors[$name])) {
$behavior = $this->_behaviors[$name];
unset($this->_behaviors[$name]);
$behavior->detach();
return $behavior;
}
return null;
}
Defined in: yii\base\Component::detachBehaviors()
Detaches all behaviors from the component.
public void detachBehaviors ( ) |
public function detachBehaviors()
{
$this->ensureBehaviors();
foreach ($this->_behaviors as $name => $behavior) {
$this->detachBehavior($name);
}
}
Defined in: yii\base\Component::ensureBehaviors()
Makes sure that the behaviors declared in behaviors() are attached to this component.
public void ensureBehaviors ( ) |
public function ensureBehaviors()
{
if ($this->_behaviors === null) {
$this->_behaviors = [];
foreach ($this->behaviors() as $name => $behavior) {
$this->attachBehaviorInternal($name, $behavior);
}
}
}
Ensure a file uploads and return relevant file infos.
public array ensureFileUpload ( $fileSource, $fileName ) | ||
$fileSource | string |
The file on the server ($_FILES['tmp']) |
$fileName | string |
Original upload name of the file ($_FILES['name']) |
return | array |
Returns an array with the following KeywordPatch
|
---|---|---|
throws | luya\Exception |
public function ensureFileUpload($fileSource, $fileName)
{
// throw exception if source or name is empty
if (empty($fileSource) || empty($fileName)) {
throw new Exception("Filename and source can not be empty.");
}
// if filename is blob, its a paste event from the browser, therefore generate the filename from the file source.
// @TODO: move out of ensureFileUpload
if ($fileName == 'blob') {
$ext = FileHelper::getExtensionsByMimeType(FileHelper::getMimeType($fileSource));
$fileName = 'paste-'.date("Y-m-d-H-i").'.'.$ext[0];
}
// get file informations from the name
$fileInfo = FileHelper::getFileInfo($fileName);
// get the mimeType from the fileSource, if $secureFileUpload is disabled, the mime type will be extracted from the file extensions
// instead of using the fileinfo extension, therefore this is not recommend.
$mimeType = FileHelper::getMimeType($fileSource, null, !$this->secureFileUpload);
// empty mime type indicates a wrong file upload.
if (empty($mimeType)) {
throw new Exception("Unable to find mimeType for the given file, make sure the php extension 'fileinfo' is installed.");
}
$extensionsFromMimeType = FileHelper::getExtensionsByMimeType($mimeType);
if (empty($extensionsFromMimeType) && empty($this->whitelistExtensions)) {
throw new Exception("Unable to find extension for given mimeType \"{$mimeType}\" or it contains insecure data.");
}
if (!empty($this->whitelistExtensions)) {
$extensionsFromMimeType = array_merge($extensionsFromMimeType, $this->whitelistExtensions);
}
// check if the file extension is matching the entries from FileHelper::getExtensionsByMimeType array.
if (!in_array($fileInfo->extension, $extensionsFromMimeType) && !in_array($mimeType, $this->whitelistMimeTypes)) {
throw new Exception("The given file extension \"{$fileInfo->extension}\" for file with mimeType \"{$mimeType}\" is not matching any valid extension: ".VarDumper::dumpAsString($extensionsFromMimeType).".");
}
foreach ($extensionsFromMimeType as $extension) {
if (in_array($extension, $this->dangerousExtensions)) {
throw new Exception("The file extension '{$extension}' seems to be dangerous and can not be stored.");
}
}
// check whether a mimetype is in the dangerousMimeTypes list and not whitelisted in whitelistMimeTypes.
if (in_array($mimeType, $this->dangerousMimeTypes) && !in_array($mimeType, $this->whitelistMimeTypes)) {
throw new Exception("The file mimeType '{$mimeType}' seems to be dangerous and can not be stored.");
}
return [
'fileInfo' => $fileInfo,
'mimeType' => $mimeType,
'fileName' => $fileName,
'secureFileName' => Inflector::slug(str_replace('_', '-', $fileInfo->name), '-'),
'fileSource' => $fileSource,
'fileSize' => filesize($fileSource),
'extension' => $fileInfo->extension,
'hashName' => FileHelper::hashName($fileName),
];
}
Return the absolute http path for a given file on the file system.
public abstract void fileAbsoluteHttpPath ( $fileName ) | ||
$fileName | string |
The name of the file on the filesystem (like: my_example_1234.jpg without path infos), the $fileName is used as identifier on the filesystem. |
abstract public function fileAbsoluteHttpPath($fileName);
Return the http path for a given file on the file system.
public abstract void fileHttpPath ( $fileName ) | ||
$fileName | string |
The name of the file on the filesystem (like: my_example_1234.jpg without path infos), the $fileName is used as identifier on the filesystem. |
abstract public function fileHttpPath($fileName);
Returns the path internal server path to the given file on the file system.
public abstract void fileServerPath ( $fileName ) | ||
$fileName | string |
The name of the file on the filesystem (like: my_example_1234.jpg without path infos), the $fileName is used as identifier on the filesystem. |
abstract public function fileServerPath($fileName);
Get the content of the file on the given file system.
public abstract void fileSystemContent ( $fileName ) | ||
$fileName | string |
The name of the file on the filesystem (like: my_example_1234.jpg without path infos), the $fileName is used as identifier on the filesystem. |
abstract public function fileSystemContent($fileName);
Delete a given file source on the filesystem.
public abstract boolean fileSystemDeleteFile ( $fileName ) | ||
$fileName | string |
The name of the file on the filesystem (like: my_example_1234.jpg without path infos), the $fileName is used as identifier on the filesystem. |
return | boolean |
Whether the file has been deleted or not. |
---|
abstract public function fileSystemDeleteFile($fileName);
Check if the file exists on the given file system.
public abstract void fileSystemExists ( $fileName ) | ||
$fileName | string |
The name of the file on the filesystem (like: my_example_1234.jpg without path infos), the $fileName is used as identifier on the filesystem. |
abstract public function fileSystemExists($fileName);
Replace an existing file source with a new one on the filesystem.
public abstract boolean fileSystemReplaceFile ( $fileName, $newSource ) | ||
$fileName | string |
The name of the file on the filesystem (like: my_example_1234.jpg without path infos), the $fileName is used as identifier on the filesystem. |
$newSource | string |
The absolute file source path and filename, like |
return | boolean |
Whether the file has replaced stored or not. |
---|
abstract public function fileSystemReplaceFile($fileName, $newSource);
Save the given file source as a new file with the given fileName on the filesystem.
public abstract boolean fileSystemSaveFile ( $source, $fileName ) | ||
$source | string |
The absolute file source path and filename, like |
$fileName | string |
The name of the file on the filesystem (like: my_example_1234.jpg without path infos), the $fileName is used as identifier on the filesystem. |
return | boolean |
Whether the file has been stored or not. |
---|
abstract public function fileSystemSaveFile($source, $fileName);
Generate a stream/resource for the file to download
public abstract resource fileSystemStream ( $fileName ) | ||
$fileName | string |
abstract public function fileSystemStream($fileName);
Get a single file based on a where condition.
This method returns a single file matching the where condition, if the multiple results match the condition the first one will be picked.
See {{\luya\admin\storage\QueryTrait::where}} for condition informations.
public luya\admin\file\Item findFile ( array $args ) | ||
$args | array |
An array with conditions to match e.g. |
return | luya\admin\file\Item |
The file item object. |
---|
public function findFile(array $args)
{
return (new \luya\admin\file\Query())->where($args)->one();
}
Get an array with all files based on a where condition.
This method returns an array with files matching there $args array condition. If no argument is provided all files will be returned.
See {{\luya\admin\storage\QueryTrait::where}} for condition informations.
public luya\admin\file\Iterator findFiles ( array $args = [] ) | ||
$args | array |
An array with conditions to match e.g. |
return | luya\admin\file\Iterator |
An iterator object containing all files found for the condition provided. |
---|
public function findFiles(array $args = [])
{
return (new \luya\admin\file\Query())->where($args)->all();
}
Get a single folder based on a where condition.
This method returns a single fpöder matching the where condition, if the multiple results match the condition the first one will be picked.
See {{\luya\admin\storage\QueryTrait::where()}} for condition informations.
public luya\admin\folder\Item findFolder ( array $args = [] ) | ||
$args | array |
An array with conditions to match e.g. |
return | luya\admin\folder\Item |
The folder item object. |
---|
public function findFolder(array $args = [])
{
return (new \luya\admin\folder\Query())->where($args)->one();
}
Get an array with all folders based on a where condition.
If no argument is provided all images will be returned.
See {{\luya\admin\storage\QueryTrait::where()}} for condition informations.
public luya\admin\folder\Iterator findFolders ( array $args = [] ) | ||
$args | array |
An array with conditions to match e.g. |
return | luya\admin\folder\Iterator |
An iterator object containing all image found for the condition provided. |
---|
public function findFolders(array $args = [])
{
return (new \luya\admin\folder\Query())->where($args)->all();
}
Get a single image based on a where condition.
This method returns a single image matching the where condition, if the multiple results match the condition the first one will be picked.
See {{\luya\admin\storage\QueryTrait::where()}} for condition informations.
public luya\admin\image\Item findImage ( array $args = [] ) | ||
$args | array |
An array with conditions to match e.g. |
return | luya\admin\image\Item |
The file item object. |
---|
public function findImage(array $args = [])
{
return (new \luya\admin\image\Query())->where($args)->one();
}
Get an array with all images based on a where condition.
This method returns an array with images matching there $args array condition. If no argument is provided all images will be returned.
See {{\luya\admin\storage\QueryTrait::where()}} for condition informations.
public luya\admin\image\Iterator findImages ( array $args = [] ) | ||
$args | array |
An array with conditions to match e.g. |
return | luya\admin\image\Iterator |
An iterator object containing all image found for the condition provided. |
---|
public function findImages(array $args = [])
{
return (new \luya\admin\image\Query())->where($args)->all();
}
Will force to refresh all container arrays and clean up the cache
public void flushArrays ( ) |
public function flushArrays()
{
$this->_filesArray = null;
$this->_imagesArray = null;
$this->_foldersArray = null;
$this->_filtersArray = null;
$this->deleteHasCache(self::CACHE_KEY_FILE);
$this->deleteHasCache(self::CACHE_KEY_IMAGE);
$this->deleteHasCache(self::CACHE_KEY_FOLDER);
$this->deleteHasCache(self::CACHE_KEY_FILTER);
}
Defined in: luya\traits\CacheableTrait::flushHasCache()
Deletes all values from cache.
public boolean flushHasCache ( ) | ||
return | boolean |
Whether the flush operation was successful. |
---|
public function flushHasCache()
{
if ($this->isCachable()) {
return Yii::$app->cache->flush();
}
return false;
}
Flush only images array and image cache.
public void flushImageArray ( ) |
public function flushImageArray()
{
$this->deleteHasCache(self::CACHE_KEY_IMAGE);
}
Defined in: yii\base\Component::getBehavior()
Returns the named behavior object.
public yii\base\Behavior|null getBehavior ( $name ) | ||
$name | string |
The behavior name |
return | yii\base\Behavior|null |
The behavior object, or null if the behavior does not exist |
---|
public function getBehavior($name)
{
$this->ensureBehaviors();
return isset($this->_behaviors[$name]) ? $this->_behaviors[$name] : null;
}
Defined in: yii\base\Component::getBehaviors()
Returns all behaviors attached to this component.
public yii\base\Behavior[] getBehaviors ( ) | ||
return | yii\base\Behavior[] |
List of behaviors attached to this component |
---|
public function getBehaviors()
{
$this->ensureBehaviors();
return $this->_behaviors;
}
Get a single file based on the ID.
If not found false is returned.
public luya\admin\file\Item|boolean getFile ( $fileId ) | ||
$fileId | integer |
The requested storage file id. |
return | luya\admin\file\Item|boolean |
The file object or false if not found. |
---|
public function getFile($fileId)
{
return (new \luya\admin\file\Query())->findOne($fileId);
}
Get all storage files as an array from database.
This method is used to retrieve all files from the database and indexed by file key.
public array getFilesArray ( ) | ||
return | array |
An array with all storage files indexed by the file id. |
---|
public function getFilesArray()
{
if ($this->_filesArray === null) {
$this->_filesArray = $this->getQueryCacheHelper((new Query())->from('{{%admin_storage_file}}')->select(['id', 'is_hidden', 'is_deleted', 'folder_id', 'name_original', 'name_new', 'name_new_compound', 'mime_type', 'extension', 'hash_name', 'hash_file', 'upload_timestamp', 'file_size', 'upload_user_id', 'caption'])->indexBy('id'), self::CACHE_KEY_FILE);
}
return $this->_filesArray;
}
Get a single file by file id from the files array.
public boolean|array getFilesArrayItem ( $fileId ) | ||
$fileId | integer |
The file id to find. |
return | boolean|array |
The file array or false if not found. |
---|
public function getFilesArrayItem($fileId)
{
return $this->filesArray[$fileId] ?? false;
}
Get the filter id based on the identifier.
This is a short hand method as its used very often
public integer getFilterId ( $identifier ) | ||
$identifier | string |
public function getFilterId($identifier)
{
$filter = $this->getFiltersArrayItem($identifier);
return $filter ? (int) $filter['id'] : false;
}
Get all storage filters as an array from database.
This method is used to retrieve all filters from the database and indexed by filter identifier key.
public array getFiltersArray ( ) | ||
return | array |
An array with all storage filters indexed by the filter identifier. |
---|
public function getFiltersArray()
{
if ($this->_filtersArray === null) {
$this->_filtersArray = $this->getQueryCacheHelper((new Query())->from('{{%admin_storage_filter}}')->select(['id', 'identifier', 'name'])->indexBy('identifier')->orderBy(['name' => SORT_ASC]), self::CACHE_KEY_FILTER);
}
return $this->_filtersArray;
}
Get a single filter by filter identifier from the filters array.
public boolean|array getFiltersArrayItem ( $filterIdentifier ) | ||
$filterIdentifier | integer |
The filter identifier to find use {{luya\admin\base\Filter::identifier()}} method. |
return | boolean|array |
The filter array or false if not found. |
---|
public function getFiltersArrayItem($filterIdentifier)
{
return $this->filtersArray[$filterIdentifier] ?? false;
}
Get a single folder based on the ID.
If not found false is returned.
public luya\admin\folder\Item|boolean getFolder ( $folderId ) | ||
$folderId | integer |
The requested storage folder id. |
return | luya\admin\folder\Item|boolean |
The folder object or false if not found. |
---|
public function getFolder($folderId)
{
return (new \luya\admin\folder\Query())->where(['id' => $folderId])->one();
}
Get all storage folders as an array from database.
This method is used to retrieve all folders from the database and indexed by folder key.
public array getFoldersArray ( ) | ||
return | array |
An array with all storage folders indexed by the folder id. |
---|
public function getFoldersArray()
{
if ($this->_foldersArray === null) {
$query = (new Query())
->from('{{%admin_storage_folder}} as folder')
->select(['folder.id', 'name', 'parent_id', 'timestamp_create', 'COUNT(file.id) filesCount'])
->where(['folder.is_deleted' => false])
->orderBy(['name' => SORT_ASC, 'parent_id' => SORT_ASC])
->leftJoin('{{%admin_storage_file}} as file', 'folder.id=file.folder_id AND file.is_deleted = :deleted', [':deleted' => false])
->groupBy(['folder.id'])
->indexBy(['id']);
$this->_foldersArray = $this->getQueryCacheHelper($query, self::CACHE_KEY_FOLDER);
}
return $this->_foldersArray;
}
Get a single folder by folder id from the folders array.
public boolean|array getFoldersArrayItem ( $folderId ) | ||
$folderId | integer |
The folder id to find. |
return | boolean|array |
The folder array or false if not found. |
---|
public function getFoldersArrayItem($folderId)
{
return $this->foldersArray[$folderId] ?? false;
}
Defined in: luya\traits\CacheableTrait::getHasCache()
Get the caching data if caching is allowed and there is any data stored for this key.
public mixed|boolean getHasCache ( $key ) | ||
$key | string|array |
The identifiere key, can be a string or an array which will be calculated. |
return | mixed|boolean |
Returns the data, if not found returns false. |
---|
public function getHasCache($key)
{
if ($this->isCachable()) {
$data = Yii::$app->cache->get($key);
$enumKey = (is_array($key)) ? implode(",", $key) : $key;
if ($data) {
Yii::debug("Cacheable trait key '$enumKey' successfully loaded from cache.", __METHOD__);
return $data;
}
Yii::debug("Cacheable trait key '$enumKey' has not been found in cache.", __METHOD__);
}
return false;
}
Get a single image based on the ID.
If not found false is returned.
public luya\admin\image\Item|boolean getImage ( $imageId ) | ||
$imageId | integer |
The requested storage image id. |
return | luya\admin\image\Item|boolean |
The image object or false if not found. |
---|
public function getImage($imageId)
{
return (new \luya\admin\image\Query())->findOne($imageId);
}
Get all storage images as an array from database.
This method is used to retrieve all images from the database and indexed by image key.
public array getImagesArray ( ) | ||
return | array |
An array with all storage images indexed by the image id. |
---|
public function getImagesArray()
{
if ($this->_imagesArray === null) {
$this->_imagesArray = $this->getQueryCacheHelper((new Query())->from('{{%admin_storage_image}}')->select(['id', 'file_id', 'filter_id', 'resolution_width', 'resolution_height'])->indexBy('id'), self::CACHE_KEY_IMAGE);
}
return $this->_imagesArray;
}
Get a single image by image id from the files array.
public boolean|array getImagesArrayItem ( $imageId ) | ||
$imageId | integer |
The image id to find. |
return | boolean|array |
The image array or false if not found. |
---|
public function getImagesArrayItem($imageId)
{
return $this->imagesArray[$imageId] ?? false;
}
Defined in: luya\traits\CacheableTrait::getOrSetHasCache()
Method combines both setHasCache() and getHasCache() methods to retrieve value identified by a $key, or to store the result of $closure execution if there is no cache available for the $key.
Usage example:
use CacheableTrait;
public function getTopProducts($count = 10)
{
return $this->getOrSetHasCache(['top-n-products', 'n' => $count], function ($cache) use ($count) {
return Products::find()->mostPopular()->limit(10)->all();
}, 1000);
}
public mixed getOrSetHasCache ( $key, Closure $closure, $duration = null, $dependency = null ) | ||
$key | mixed |
A key identifying the value to be cached. This can be a simple string or a complex data structure consisting of factors representing the key. |
$closure | Closure |
The closure that will be used to generate a value to be cached.
In case $closure returns |
$duration | integer |
Default duration in seconds before the cache will expire. If not set, defaultDuration value will be used. 0 means never expire. |
$dependency | yii\caching\Dependency |
Dependency of the cached item. If the dependency changes,
the corresponding value in the cache will be invalidated when it is fetched via get().
This parameter is ignored if serializer is |
return | mixed |
Result of $closure execution |
---|
public function getOrSetHasCache($key, \Closure $closure, $duration = null, $dependency = null)
{
if (($value = $this->getHasCache($key)) !== false) {
return $value;
}
$value = call_user_func($closure, $this);
$this->setHasCache($key, $value, $dependency, $duration);
return $value;
}
Defined in: yii\base\Component::hasEventHandlers()
Returns a value indicating whether there is any handler attached to the named event.
public boolean hasEventHandlers ( $name ) | ||
$name | string |
The event name |
return | boolean |
Whether there is any handler attached to the event. |
---|
public function hasEventHandlers($name)
{
$this->ensureBehaviors();
if (!empty($this->_events[$name])) {
return true;
}
foreach ($this->_eventWildcards as $wildcard => $handlers) {
if (!empty($handlers) && StringHelper::matchWildcard($wildcard, $name)) {
return true;
}
}
return Event::hasHandlers($this, $name);
}
Defined in: yii\base\Component::hasMethod()
Returns a value indicating whether a method is defined.
A method is defined if:
- the class has a method with the specified name
- an attached behavior has a method with the given name (when
$checkBehaviors
is true).
public boolean hasMethod ( $name, $checkBehaviors = true ) | ||
$name | string |
The property name |
$checkBehaviors | boolean |
Whether to treat behaviors' methods as methods of this component |
return | boolean |
Whether the method is defined |
---|
public function hasMethod($name, $checkBehaviors = true)
{
if (method_exists($this, $name)) {
return true;
} elseif ($checkBehaviors) {
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->hasMethod($name)) {
return true;
}
}
}
return false;
}
Defined in: yii\base\Component::hasProperty()
Returns a value indicating whether a property is defined for this component.
A property is defined if:
- the class has a getter or setter method associated with the specified name (in this case, property name is case-insensitive);
- the class has a member variable with the specified name (when
$checkVars
is true); - an attached behavior has a property of the given name (when
$checkBehaviors
is true).
See also:
public boolean hasProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | string |
The property name |
$checkVars | boolean |
Whether to treat member variables as properties |
$checkBehaviors | boolean |
Whether to treat behaviors' properties as properties of this component |
return | boolean |
Whether the property is defined |
---|
public function hasProperty($name, $checkVars = true, $checkBehaviors = true)
{
return $this->canGetProperty($name, $checkVars, $checkBehaviors) || $this->canSetProperty($name, false, $checkBehaviors);
}
Defined in: yii\base\BaseObject::init()
Initializes the object.
This method is invoked at the end of the constructor after the object is initialized with the given configuration.
public void init ( ) |
public function init()
{
}
Defined in: luya\traits\CacheableTrait::isCachable()
Check if the current configuration of the application and the property allows a caching of the language container data.
public boolean isCachable ( ) |
public function isCachable()
{
if ($this->_cachable === null) {
$this->_cachable = Yii::$app->has('cache') ? true : false;
}
return $this->_cachable;
}
Defined in: yii\base\Component::off()
Detaches an existing event handler from this component.
This method is the opposite of on().
Note: in case wildcard pattern is passed for event name, only the handlers registered with this wildcard will be removed, while handlers registered with plain names matching this wildcard will remain.
See also on().
public boolean off ( $name, $handler = null ) | ||
$name | string |
Event name |
$handler | callable|null |
The event handler to be removed. If it is null, all handlers attached to the named event will be removed. |
return | boolean |
If a handler is found and detached |
---|
public function off($name, $handler = null)
{
$this->ensureBehaviors();
if (empty($this->_events[$name]) && empty($this->_eventWildcards[$name])) {
return false;
}
if ($handler === null) {
unset($this->_events[$name], $this->_eventWildcards[$name]);
return true;
}
$removed = false;
// plain event names
if (isset($this->_events[$name])) {
foreach ($this->_events[$name] as $i => $event) {
if ($event[0] === $handler) {
unset($this->_events[$name][$i]);
$removed = true;
}
}
if ($removed) {
$this->_events[$name] = array_values($this->_events[$name]);
return true;
}
}
// wildcard event names
if (isset($this->_eventWildcards[$name])) {
foreach ($this->_eventWildcards[$name] as $i => $event) {
if ($event[0] === $handler) {
unset($this->_eventWildcards[$name][$i]);
$removed = true;
}
}
if ($removed) {
$this->_eventWildcards[$name] = array_values($this->_eventWildcards[$name]);
// remove empty wildcards to save future redundant regex checks:
if (empty($this->_eventWildcards[$name])) {
unset($this->_eventWildcards[$name]);
}
}
}
return $removed;
}
Defined in: yii\base\Component::on()
Attaches an event handler to an event.
The event handler must be a valid PHP callback. The following are some examples:
function ($event) { ... } // anonymous function
[$object, 'handleClick'] // $object->handleClick()
['Page', 'handleClick'] // Page::handleClick()
'handleClick' // global function handleClick()
The event handler must be defined with the following signature,
function ($event)
where $event
is an yii\base\Event object which includes parameters associated with the event.
Since 2.0.14 you can specify event name as a wildcard pattern:
$component->on('event.group.*', function ($event) {
Yii::trace($event->name . ' is triggered.');
});
See also off().
public void on ( $name, $handler, $data = null, $append = true ) | ||
$name | string |
The event name |
$handler | callable |
The event handler |
$data | mixed |
The data to be passed to the event handler when the event is triggered. When the event handler is invoked, this data can be accessed via yii\base\Event::$data. |
$append | boolean |
Whether to append new event handler to the end of the existing handler list. If false, the new handler will be inserted at the beginning of the existing handler list. |
public function on($name, $handler, $data = null, $append = true)
{
$this->ensureBehaviors();
if (strpos($name, '*') !== false) {
if ($append || empty($this->_eventWildcards[$name])) {
$this->_eventWildcards[$name][] = [$handler, $data];
} else {
array_unshift($this->_eventWildcards[$name], [$handler, $data]);
}
return;
}
if ($append || empty($this->_events[$name])) {
$this->_events[$name][] = [$handler, $data];
} else {
array_unshift($this->_events[$name], [$handler, $data]);
}
}
This method allwos you to generate all thumbnails for the file manager, you can trigger this process when importing or creating several images at once, so the user does not have to create the thumbnails
public boolean processThumbnails ( ) |
public function processThumbnails()
{
foreach ($this->findFiles(['is_hidden' => false, 'is_deleted' => false]) as $file) {
if ($file->isImage) {
// create tiny thumbnail
$this->createImage($file->id, $this->getFilterId(TinyCrop::identifier()));
$this->createImage($file->id, $this->getFilterId(MediumThumbnail::identifier()));
}
}
// force auto fix
$this->autoFixMissingImageSources = true;
foreach ($this->findImages() as $image) {
if (!empty($image->file) && !$image->file->isHidden && !$image->file->isDeleted) {
$image->source; // which forces to recreate missing sources.
}
}
return true;
}
Setter method for fiels array.
This is mainly used when working with unit tests.
public void setFilesArray ( array $files ) | ||
$files | array |
public function setFilesArray(array $files)
{
$this->_filesArray = $files;
}
Setter method for filters array.
This is mainly used when working with unit tests.
public void setFiltersArray ( array $filters ) | ||
$filters | array |
public function setFiltersArray(array $filters)
{
$this->_filtersArray = $filters;
}
Defined in: luya\traits\CacheableTrait::setHasCache()
Store cache data for a specific key if caching is enabled in this application.
public boolean setHasCache ( $key, $value, $dependency = null, $cacheExpiration = null ) | ||
$key | string|array |
The identifier key or a array to store complex keys |
$value | mixed |
The value to store in the cache component. |
$dependency | yii\caching\Dependency|array |
Dependency of the cached item. If the dependency changes, the corresponding value in the cache will be invalidated when it is fetched via get(). This parameter is ignored if $serializer is false. You can also define an array with defintion which will generate the Object instead of object is provided. |
$cacheExpiration |
Integer The time in seconds before the cache data expires, 0 means never expire. |
|
return | boolean |
Whether set has been success or not |
---|
public function setHasCache($key, $value, $dependency = null, $cacheExpiration = null)
{
if ($this->isCachable()) {
if (is_array($dependency)) {
$dependency = Yii::createObject($dependency);
}
return Yii::$app->cache->set($key, $value, is_null($cacheExpiration) ? $this->_cacheExpiration : $cacheExpiration, $dependency);
}
return false;
}
Setter method for images array.
This is mainly used when working with unit tests.
public void setImagesArray ( array $images ) | ||
$images | array |
public function setImagesArray(array $images)
{
$this->_imagesArray = $images;
}
Defined in: yii\base\Component::trigger()
Triggers an event.
This method represents the happening of an event. It invokes all attached handlers for the event including class-level handlers.
public void trigger ( $name, yii\base\Event $event = null ) | ||
$name | string |
The event name |
$event | yii\base\Event|null |
The event instance. If not set, a default yii\base\Event object will be created. |
public function trigger($name, Event $event = null)
{
$this->ensureBehaviors();
$eventHandlers = [];
foreach ($this->_eventWildcards as $wildcard => $handlers) {
if (StringHelper::matchWildcard($wildcard, $name)) {
$eventHandlers[] = $handlers;
}
}
if (!empty($this->_events[$name])) {
$eventHandlers[] = $this->_events[$name];
}
if (!empty($eventHandlers)) {
$eventHandlers = call_user_func_array('array_merge', $eventHandlers);
if ($event === null) {
$event = new Event();
}
if ($event->sender === null) {
$event->sender = $this;
}
$event->handled = false;
$event->name = $name;
foreach ($eventHandlers as $handler) {
$event->data = $handler[1];
call_user_func($handler[0], $event);
// stop further handling if the event is handled
if ($event->handled) {
return;
}
}
}
// invoke class-level attached handlers
Event::trigger($this, $name, $event);
}