Yii2 узнать расширение файла
В Yii2 есть возможность реализовать три варианта интернационализации:
Method Details
Changes the Unix user and/or group ownership of a file or directory, and optionally the mode.
Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem. Note: On Windows, this function fails silently when applied on a regular file.
The path to the file or directory.
The user and/or group ownership for the file or directory. When $ownership is a string, the format is 'user:group' where both are optional. E.g. 'user' or 'user:' will only change the user, ':group' will only change the group, 'user:group' will change both. When $owners is an index array the format is [0 => user, 1 => group], e.g. [$myUser, $myGroup] . It is also possible to pass an associative array, e.g. ['user' => $myUser, 'group' => $myGroup]. In case $owners is an integer it will be used as user id. If null , an empty array or an empty string is passed, the ownership will not be changed.
The permission to be set for the file or directory. If null is passed, the mode will not be changed.
Copies a whole directory as another one.
The files and sub-directories will also be copied over.
The source directory
The destination directory
- dirMode: integer, the permission to be set for newly copied directories. Defaults to 0775.
- fileMode: integer, the permission to be set for newly copied files. Defaults to the current environment setting.
filter: callback, a PHP callback that is called for each directory or file. The signature of the callback should be: function ($path) , where $path refers the full path to be filtered. The callback can return one of the following values:
- true: the directory or file will be copied (the "only" and "except" options will be ignored)
- false: the directory or file will NOT be copied (the "only" and "except" options will be ignored)
- null: the "only" and "except" options will determine whether the directory or file should be copied
if unable to open directory
Creates a new directory.
This method is similar to the PHP mkdir() function except that it uses chmod() to set the permission of the created directory in order to avoid the impact of the umask setting.
Path of the directory to be created.
The permission to be set for the created directory.
Whether to create parent directories if they do not exist.
Whether the directory is created successfully
if the directory could not be created (i.e. php error due to parallel changes)
Checks if the given file path satisfies the filtering options.
The path of the file or directory to be checked
The filtering options. See findFiles() for explanations of the supported options.
Whether the file or directory satisfies the filtering options.
Returns the directories found under the specified directory and subdirectories.
The directory under which the files will be looked for.
filter : callback, a PHP callback that is called for each directory or file. The signature of the callback should be: function (string $path): bool , where $path refers the full path to be filtered. The callback can return one of the following values:
- true : the directory will be returned
- false : the directory will NOT be returned
recursive : boolean, whether the files under the subdirectories should also be looked for. Defaults to true . See findFiles() for more options.
Directories found under the directory, in no particular order. Ordering depends on the files system used.
if the dir is invalid.
Returns the files found under the specified directory and subdirectories.
The directory under which the files will be looked for.
filter : callback, a PHP callback that is called for each directory or file. The signature of the callback should be: function ($path) , where $path refers the full path to be filtered. The callback can return one of the following values:
- true : the directory or file will be returned (the only and except options will be ignored)
- false : the directory or file will NOT be returned (the only and except options will be ignored)
- null : the only and except options will determine whether the directory or file should be returned
Files found under the directory, in no particular order. Ordering depends on the files system used.
if the dir is invalid.
Determines the extensions by given MIME type.
This method will use a local map between extension names and MIME types.
The path (or alias) of the file that contains all available MIME type information. If this is not set, the file specified by $mimeMagicFile will be used.
The extensions corresponding to the specified MIME type
Determines the MIME type of the specified file.
This method will first try to determine the MIME type based on finfo_open. If the fileinfo extension is not installed, it will fall back to getMimeTypeByExtension() when $checkExtension is true.
Name of the optional magic database file (or alias), usually something like /path/to/magic.mime . This will be passed as the second parameter to finfo_open() when the fileinfo extension is installed. If the MIME type is being determined based via getMimeTypeByExtension() and this is null, it will use the file specified by $mimeMagicFile.
Whether to use the file extension to determine the MIME type in case finfo_open() cannot determine it.
The MIME type (e.g. text/plain ). Null is returned if the MIME type cannot be determined.
when the fileinfo PHP extension is not installed and $checkExtension is false .
Determines the MIME type based on the extension name of the specified file.
This method will use a local map between extension names and MIME types.
The path (or alias) of the file that contains all available MIME type information. If this is not set, the file specified by $mimeMagicFile will be used.
The MIME type. Null is returned if the MIME type cannot be determined.
Loads MIME aliases from the specified file.
The path (or alias) of the file that contains MIME type aliases. If this is not set, the file specified by $mimeAliasesFile will be used.
The mapping from file extensions to MIME types
Loads MIME types from the specified file.
The path (or alias) of the file that contains all available MIME type information. If this is not set, the file specified by $mimeMagicFile will be used.
The mapping from file extensions to MIME types
Returns the localized version of a specified file.
The searching is based on the specified language code. In particular, a file with the same name will be looked for under the subdirectory whose name is the same as the language code. For example, given the file "path/to/view.php" and language code "zh-CN", the localized file will be looked for as "path/to/zh-CN/view.php". If the file is not found, it will try a fallback with just a language code that is "zh" i.e. "path/to/zh/view.php". If it is not found as well the original file will be returned.
If the target and the source language codes are the same, the original file will be returned.
The original file
The target language that the file should be localized to. If not set, the value of yii\base\Application::$language will be used.
The language that the original file is in. If not set, the value of yii\base\Application::$sourceLanguage will be used.
The matching localized file, or the original file if the localized version is not found. If the target and the source language codes are the same, the original file will be returned.
Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem. Note: On Windows, this function fails silently when applied on a regular file.
The path to the file or directory.
The user and/or group ownership for the file or directory. When $ownership is a string, the format is 'user:group' where both are optional. E.g. 'user' or 'user:' will only change the user, ':group' will only change the group, 'user:group' will change both. When $owners is an index array the format is [0 => user, 1 => group], e.g. [$myUser, $myGroup] . It is also possible to pass an associative array, e.g. ['user' => $myUser, 'group' => $myGroup]. In case $owners is an integer it will be used as user id. If null , an empty array or an empty string is passed, the ownership will not be changed.
The permission to be set for the file or directory. If null is passed, the mode will not be changed.
Copies a whole directory as another one.
The files and sub-directories will also be copied over.
The source directory
The destination directory
- dirMode: integer, the permission to be set for newly copied directories. Defaults to 0775.
- fileMode: integer, the permission to be set for newly copied files. Defaults to the current environment setting.
filter: callback, a PHP callback that is called for each directory or file. The signature of the callback should be: function ($path) , where $path refers the full path to be filtered. The callback can return one of the following values:
- true: the directory or file will be copied (the "only" and "except" options will be ignored)
- false: the directory or file will NOT be copied (the "only" and "except" options will be ignored)
- null: the "only" and "except" options will determine whether the directory or file should be copied
if unable to open directory
Creates a new directory.
This method is similar to the PHP mkdir() function except that it uses chmod() to set the permission of the created directory in order to avoid the impact of the umask setting.
Path of the directory to be created.
The permission to be set for the created directory.
Whether to create parent directories if they do not exist.
Whether the directory is created successfully
if the directory could not be created (i.e. php error due to parallel changes)
Checks if the given file path satisfies the filtering options.
The path of the file or directory to be checked
The filtering options. See findFiles() for explanations of the supported options.
Whether the file or directory satisfies the filtering options.
Returns the directories found under the specified directory and subdirectories.
The directory under which the files will be looked for.
filter : callback, a PHP callback that is called for each directory or file. The signature of the callback should be: function (string $path): bool , where $path refers the full path to be filtered. The callback can return one of the following values:
- true : the directory will be returned
- false : the directory will NOT be returned
recursive : boolean, whether the files under the subdirectories should also be looked for. Defaults to true . See findFiles() for more options.
Directories found under the directory, in no particular order. Ordering depends on the files system used.
if the dir is invalid.
Returns the files found under the specified directory and subdirectories.
The directory under which the files will be looked for.
filter : callback, a PHP callback that is called for each directory or file. The signature of the callback should be: function ($path) , where $path refers the full path to be filtered. The callback can return one of the following values:
- true : the directory or file will be returned (the only and except options will be ignored)
- false : the directory or file will NOT be returned (the only and except options will be ignored)
- null : the only and except options will determine whether the directory or file should be returned
Files found under the directory, in no particular order. Ordering depends on the files system used.
if the dir is invalid.
Determines the extensions by given MIME type.
This method will use a local map between extension names and MIME types.
The path (or alias) of the file that contains all available MIME type information. If this is not set, the file specified by $mimeMagicFile will be used.
The extensions corresponding to the specified MIME type
Determines the MIME type of the specified file.
This method will first try to determine the MIME type based on finfo_open. If the fileinfo extension is not installed, it will fall back to getMimeTypeByExtension() when $checkExtension is true.
Name of the optional magic database file (or alias), usually something like /path/to/magic.mime . This will be passed as the second parameter to finfo_open() when the fileinfo extension is installed. If the MIME type is being determined based via getMimeTypeByExtension() and this is null, it will use the file specified by $mimeMagicFile.
Whether to use the file extension to determine the MIME type in case finfo_open() cannot determine it.
The MIME type (e.g. text/plain ). Null is returned if the MIME type cannot be determined.
when the fileinfo PHP extension is not installed and $checkExtension is false .
Determines the MIME type based on the extension name of the specified file.
This method will use a local map between extension names and MIME types.
The path (or alias) of the file that contains all available MIME type information. If this is not set, the file specified by $mimeMagicFile will be used.
The MIME type. Null is returned if the MIME type cannot be determined.
Loads MIME aliases from the specified file.
The path (or alias) of the file that contains MIME type aliases. If this is not set, the file specified by $mimeAliasesFile will be used.
The mapping from file extensions to MIME types
Loads MIME types from the specified file.
The path (or alias) of the file that contains all available MIME type information. If this is not set, the file specified by $mimeMagicFile will be used.
The mapping from file extensions to MIME types
Returns the localized version of a specified file.
The searching is based on the specified language code. In particular, a file with the same name will be looked for under the subdirectory whose name is the same as the language code. For example, given the file "path/to/view.php" and language code "zh-CN", the localized file will be looked for as "path/to/zh-CN/view.php". If the file is not found, it will try a fallback with just a language code that is "zh" i.e. "path/to/zh/view.php". If it is not found as well the original file will be returned.
If the target and the source language codes are the same, the original file will be returned.
The original file
The target language that the file should be localized to. If not set, the value of yii\base\Application::$language will be used.
The language that the original file is in. If not set, the value of yii\base\Application::$sourceLanguage will be used.
The matching localized file, or the original file if the localized version is not found. If the target and the source language codes are the same, the original file will be returned.
Whether to check file type (extension) with mime-type. If extension produced by file mime-type check differs from uploaded file extension, the file will be considered as invalid.
A list of file name extensions that are allowed to be uploaded. This can be either an array or a string consisting of file extension names separated by space or comma (e.g. "gif, jpg"). Extension names are case-insensitive. Defaults to null, meaning all file name extensions are allowed.
See also $wrongExtension for the customized message for wrong file type.
The maximum file count the given attribute can hold. Defaults to 1, meaning single file upload. By defining a higher number, multiple uploads become possible. Setting it to 0 means there is no limit on the number of files that can be uploaded simultaneously.
Note: The maximum number of files allowed to be uploaded simultaneously is also limited with PHP directive max_file_uploads , which defaults to 20.
The maximum number of bytes required for the uploaded file. Defaults to null, meaning no limit. Note, the size limit is also affected by upload_max_filesize and post_max_size INI setting and the 'MAX_FILE_SIZE' hidden field value. See getSizeLimit() for details.
The error message used when a file is not uploaded correctly.
A list of file MIME types that are allowed to be uploaded. This can be either an array or a string consisting of file MIME types separated by space or comma (e.g. "text/plain, image/png"). The mask with the special character * can be used to match groups of mime types. For example image/* will pass all mime types, that begin with image/ (e.g. image/jpeg , image/png ). Mime type names are case-insensitive. Defaults to null, meaning all MIME types are allowed.
See also $wrongMimeType for the customized message for wrong MIME type.
The minimum file count the given attribute can hold. Defaults to 0. Higher value means at least that number of files should be uploaded.
See also $tooFew for the customized message when too few files are uploaded.
The minimum number of bytes required for the uploaded file. Defaults to null, meaning no limit.
See also $tooSmall for the customized message for a file that is too small.
The size limit for uploaded files.
The error message used when the uploaded file is too large. You may use the following tokens in the message:
- : the attribute name
- : the uploaded file name
- : the maximum size allowed (see getSizeLimit())
- : the maximum size formatted with Formatter::asShortSize()
The error message used if the count of multiple uploads less that minFiles. You may use the following tokens in the message:
The error message used if the count of multiple uploads exceeds limit. You may use the following tokens in the message:
The error message used when the uploaded file is too small. You may use the following tokens in the message:
- : the attribute name
- : the uploaded file name
- : the value of $minSize
- : the value of $minSize formatted with [[\yii\i18n\Formatter::asShortSize()|Formatter::asShortSize()]
The error message used when no file is uploaded. Note that this is the text of the validation error message. To make uploading files required, you have to set $skipOnEmpty to false .
The error message used when the uploaded file has an extension name that is not listed in $extensions. You may use the following tokens in the message:
- : the attribute name
- : the uploaded file name
- : the list of the allowed extensions.
The error message used when the file has an mime type that is not allowed by $mimeTypes property. You may use the following tokens in the message:
- : the attribute name
- : the uploaded file name
- : the value of $mimeTypes
Метод autorotate()
Автоматически поворачивает изображение на основе информации EXIF. (я так и не понял, как работает данный метод):
Добавляем components i18n
Далее добавляем в i18n component конфигурационного файла common\config\main.php:
-
Компонент Yii i18n будет срабатывать при вызовах Yii::$app->t().Класс отвечающий за это yii\i18n\DbMessageSource но мы его переопределим common\models\AltDbMessageSource.
Public Properties
Property | Type | Description | Defined By |
---|---|---|---|
$mimeAliasesFile | string | The path (or alias) of a PHP file containing MIME aliases. | yii\helpers\BaseFileHelper |
$mimeMagicFile | string | The path (or alias) of a PHP file containing MIME type information. | yii\helpers\BaseFileHelper |
Метод text()
Рисует текстовую строку на существующем изображении:
Более сложный пример:
Обработчик не найденных переводов
Метод thumbnail()
Создает уменьшенное изображение. Если для одного из миниатюрных размеров установлено значение null , другое вычисляется автоматически на основе соотношения сторон исходного изображения. Обратите внимание, что расчетный размер эскиза может варьироваться в зависимости от исходного изображения в этом случае. Если указаны оба размера, итоговая эскиз будет точно указанной ширины и высоты. Как это достигается, зависит от режима.
Protected Methods
Method | Description | Defined By |
---|---|---|
loadMimeAliases() | Loads MIME aliases from the specified file. | yii\helpers\BaseFileHelper |
loadMimeTypes() | Loads MIME types from the specified file. | yii\helpers\BaseFileHelper |
normalizeOptions() | yii\helpers\BaseFileHelper |
Что должно быть в представлениях
Примеры из документации Yii::t()
Лучше, если названия категории будут содержать название страницы на которой они будут использоваться. При поиске перевода Yii делает выборку всей категории.
Создание таблиц в MySQL
Далее создадим три таблицы для основного хранения всех языков с переводами:
Метод crop()
Обрезает изображение жёстко по заданным размерам. Пропорциональность не соблюдается (если явно не указать её в размерах), режет с левого верхнего угла.
Property Details
The path (or alias) of a PHP file containing MIME aliases.
The path (or alias) of a PHP file containing MIME type information.
Constants
Constant | Value | Description | Defined By |
---|---|---|---|
PATTERN_CASE_INSENSITIVE | 32 | yii\helpers\BaseFileHelper | |
PATTERN_ENDSWITH | 4 | yii\helpers\BaseFileHelper | |
PATTERN_MUSTBEDIR | 8 | yii\helpers\BaseFileHelper | |
PATTERN_NEGATIVE | 16 | yii\helpers\BaseFileHelper | |
PATTERN_NODIR | 1 | yii\helpers\BaseFileHelper |
Метод frame()
Добавляет рамку вокруг изображения. Размер изображения увеличится на ширину рамки, умноженную на 2 (по цирине картинки и высоте соответственно):
Основное
- Вызов перевода остается стандартным Yii::t();
- Хранить переводы с ключами будем в MySQL;
- Временное хранилище по языкам в Redis;
- Сбор ключей (категорий) остается прежним;
В чем плюсы:
Виджет смены языка
Вся суть виджета — это отобразить все доступные языки и установить COOKIE данные.
Далее, когда добавятся еще переводы или удалятся на страницах нашего приложения мы просто вызываем сбор ключей и вносим в MySQL их значения.
Do not use BaseFileHelper. Use yii\helpers\FileHelper instead.
Напишем компонент \common\components\LanguageExtension
Компонент нужен для получения перевода по ключу из Redis или массива если Redis отвалился.
Как он работает
При инициализации проверяем коннект Redis. Если его нет то заполняем буфер, если он есть то заполняем его, а источник в обоих случаях MySQL.
Важный момент, перед заполнением мы конечно проверяем загружен ли язык уже в систему, путем проверки дефолного ключа ru-RU:index который мы устанавливаем если его нет при загрузки.
И так, в MySQL есть 4 языка. Идут коннекты от пользователей на ru-RU язык, что мы делаем? Мы грузим Redis из MySQL весь ru-RU если его там нет и раздаем его, далее есть коннект на en-US, подгружаем в Redis и этот язык, теперь у нас два языка в системе загружено.
Жить конечно они могут вечно но у меня в компоненте устанавливается время на ключ
Эффекты
Более сложные пример. Изменим размер изображения методом resize() , применим водяной знак в нижнем правом углу загружаемой картинки:
Создадим конфигурационный файл для сборщика
Выполним консольную команду
p.s. Для windows окружения php yii….Работа с console должна быть настроена т.е. необходимые компоненты должны быть подключены.
Должен создаться файл /common/config/i18n.php:
Создайте папку common/messages для хранения переводов !
Выполним migrate
Для хранения переводов выполним скрипт создания таблиц
php yii migrate --migrationPath=@yii/i18n/migrations
Создадутся две таблицы:
Теперь можно выполнить консольную команду сбора всех категории с сохранением их в базу
php yii message/extract @common/config/i18n.php
Также имеется возможность хранить переводы в Mongo:
И при вызове перевода
echo \Yii::t('frontend/index', 'Hello');
echo \Yii::t('frontend/index', 'Hello world!');
отработает выборка из коллекции messages по языку 'language'=> 'uk-UA'
и категории "category": "frontend/index" .Получим все ключи категории сразу, имеет смысл определять категорию максимально использующую все переводы.
Или свой вариант, взяв за основу хранения переводов в базе но со своим управлением (формирования ключей, переводов и их хранения).
Метод getImagine()
Возвращает объект Imagine, который поддерживает различные манипуляции с изображениями (например, эффекты)
Переопределим yii\i18n\DbMessageSource
Класс отвечающий за перевод мы реализуем по своему
Метод translateMessage вызывается когда мы вызываем Yii::t('категория','значение'). Тут важно как мы собираемся организовать вид ключа. Можно через сепаратор : с помощью которого в Redis будут созданы папки с иерархией, что дает наглядность. К примеру: такие ключи
Yii::t('ru-RU:type:uniq_view','значение') будут выглядеть в RedisAdmin так:
- ru-RU:
- type:
- uniq_view: значение
- uniq_view: значение
- uniq_view: значение
Ключ языка ru-RU и др. будем добавлять в момент заполнения Redis в компоненте \common\components\LanguageExtension.
Method Details
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.
В Yii2 есть замечательное расширение yii\imagine\Image , с помощью которого можно совершать некоторые действия при работе с картинками.
Yii Framework Wiki здесь
Рассмотрим наиболее интересные публичные методы класса yii\imagine\Image :
Public Methods
Method Description Defined By changeOwnership() Changes the Unix user and/or group ownership of a file or directory, and optionally the mode. yii\helpers\BaseFileHelper copyDirectory() Copies a whole directory as another one. yii\helpers\BaseFileHelper createDirectory() Creates a new directory. yii\helpers\BaseFileHelper filterPath() Checks if the given file path satisfies the filtering options. yii\helpers\BaseFileHelper findDirectories() Returns the directories found under the specified directory and subdirectories. yii\helpers\BaseFileHelper findFiles() Returns the files found under the specified directory and subdirectories. yii\helpers\BaseFileHelper getExtensionsByMimeType() Determines the extensions by given MIME type. yii\helpers\BaseFileHelper getMimeType() Determines the MIME type of the specified file. yii\helpers\BaseFileHelper getMimeTypeByExtension() Determines the MIME type based on the extension name of the specified file. yii\helpers\BaseFileHelper localize() Returns the localized version of a specified file. yii\helpers\BaseFileHelper normalizePath() Normalizes a file/directory path. yii\helpers\BaseFileHelper removeDirectory() Removes a directory (and all its content) recursively. yii\helpers\BaseFileHelper unlink() Removes a file or symlink in a cross-platform way yii\helpers\BaseFileHelper Создание конфигурационного файла i18n.php
Начнем с того что создадим конфигурационный файл сборщика ключей такой консольной командой:
После этой консольной команды файл i18n.php появится в common/config/ или просто его создадим такого вида:Запуск построение ключей
- common\messages\ru-RU\frontend\home.php
- common\messages\uk-UA\frontend\home.php
- common\messages\en-US\frontend\home.php
- common\messages\ru-RU\frontend\login.php
- common\messages\uk-UA\frontend\login.php
- common\messages\en-US\frontend\login.php
- .
Файлы имею такой вид:
Переводить мы будем уже сами.
Если создать файл views/site/ru-RU/index.php и язык по умолчанию language=ru-RU то сначала рендерится эта вьюшка.
Создадим конфигурационный файл common/config/i18n.php
Выполнив команду
php yii message/config @common/config/i18n.php
Создаться такой файл common/config/i18n.php:Добавим компонент
Примеры компонента есть в варианте с php форматом
В файле конфигурации common/main.php
обработчик не найденных переводов common\components\TranslationEventHandler так же есть в примере с форматом phpВ представлениях должны быть вызовы метода компонента Yii::t() см.Help Link
К примеру:Создание конфигурационного файла
Командой php yii message/config @common/config/i18n.php
получим файл common/config/i18n.phpОн такой же как и в случае с форматом php. Отличается только форматом :) 'format' => 'po'
Создайте папку common/messages для хранения переводов !
Отличие этого формата от php формата только в том, что после сбора ключей с приложения командой php yii message/extract @common/config/i18n.php в папке common\messages создадутся файлы с расширением .so (frontend.so) которые следует компилировать программкой, к примеру poedit windows и простым сохранением она создаст бинарные файлы с расширением .so.
Метод watermark()
Добавляет водяной знак к существующему изображению:
Переместим водяной знак в правый нижний угол. Для этого вычислим размер загружаемой картинки, перенесём позиции водяного знака на ширину и высоту загружаемой картинки за минусом ширины и высоты самого водяного знака
Метод resize()
Изменение размера изображения. Если для одного из параметров установлено значение null , другое вычисляется автоматически на основе соотношения сторон исходного изображения. Если оба размера установлены, новые размеры вычисляются так, чтобы изображение сохраняло пропорции. Вы можете установить $keepAspectRatio в false , если вы хотите принудительно фиксировать ширину и высоту.
Добавим компонент i18n
В файле конфигурации common/main.php
Переопределим консольный контроллер
Теперь, до сбора ключей, переопределим консольный контроллер \yii\console\controllers\MessageController который отвечает за сбор всех ключей. Для этого создам свой контроллер который наследуются от него.
Создадим файл console\controllers\Message2Controller.php такого вида:
Суть тут в том, что нам нужен только один метод saveMessagesToDb, который заполняет таблицу gr_dictionary из конфигурационного файла common/config/i18n.php
собранными ключами с нашего сайта, которые мы предварительно вызвали через Yii::t() .Но можно и другую таблицу использовать, тут мы уже решаем как нам лучше. Добавил удаление ключей, а с ними и переводов по ссылке внешнего ключа если на сайте этот ключ больше не используется.Теперь можем вызвать сбор ключей командой к нашему контроллеру:
В результате должны заполнится две таблицы (gr_dictionary и gr_dictionary_keys). По каждому языку из таблицы gr_language будет создана запись для перевода.Читайте также:
- type: