ModuleFs
Package | framework.modules |
---|---|
Inheritance | class ModuleFs » Module » LsObject |
Since | 2.0 |
Source Code | /framework/classes/modules/fs/Fs.class.php |
Protected Properties
Property | Type | Description | Defined By |
---|---|---|---|
_aBehaviors | Список поведений в виде готовых объектов, формируется автоматически | LsObject | |
aBehaviors | array | Список поведений | LsObject |
bIsInit | bool | Указывает на то, была ли проведенна инициализация модуля | Module |
sPathTypeDefault | string|null | Дефолтный тип пути, используется если префикс не указан | ModuleFs |
Public Methods
Method | Description | Defined By |
---|---|---|
AddBehaviorHook() | Добавляет хук поведения | LsObject |
AttachBehavior() | Присоединяет поведение к объекту | LsObject |
CreateDirectoryLocal() | Создает каталог на локальном(текущем) сервере | ModuleFs |
CreateDirectoryLocalSmart() | Создает каталог на локальном(текущем) сервере | ModuleFs |
CreateLock() | Создает блокировку | ModuleFs |
DetachBehavior() | Отсоединяет поведение от объекта | LsObject |
GetBehavior() | Возвращает объект поведения по его имени | LsObject |
GetBehaviors() | Возвращает все объекты поведения | LsObject |
GetParsedPath() | Парсит путь и возвращет его составляющие - массив вида array(0=>'relative', 1=>'/image.jpg') | ModuleFs |
GetPathRelative() | Возвращает относительный путь | ModuleFs |
GetPathRelativeFromServer() | Возвращает относительный путь из серверного | ModuleFs |
GetPathRelativeFromWeb() | Возвращает относительный путь из веб | ModuleFs |
GetPathServer() | Возвращает серверный путь | ModuleFs |
GetPathServerFromRelative() | Возвращает серверный путь из относительного | ModuleFs |
GetPathServerFromWeb() | Возвращает серверный путь из веб | ModuleFs |
GetPathType() | Возвращает тип из пути | ModuleFs |
GetPathWeb() | Возвращает веб путь (URL) | ModuleFs |
GetPathWebFromRelative() | Возвращает веб путь из относительного | ModuleFs |
GetPathWebFromServer() | Возвращает веб путь из серверного | ModuleFs |
Init() | ModuleFs | |
IsExistsFileLocal() | Проверяет на существование локальный файл | ModuleFs |
IsLock() | Проверяет наличие блокировки | ModuleFs |
IsPathType() | Проверяет принадлежность пути нужному типу | ModuleFs |
MakePath() | Формирует полный путь с учетом типа | ModuleFs |
RemoveBehaviorHook() | Удаляет хук поведения | LsObject |
RemoveFileLocal() | Удаляет локальный файл | ModuleFs |
RemoveLock() | Удаляет блокировку | ModuleFs |
RunBehaviorHook() | Запускает хук поведения на выполнение | LsObject |
SaveFileLocal() | Сохраняет(копирует) файл на локальном(текущем) сервере | ModuleFs |
SaveFileLocalSmart() | Сохраняет(копирует) файл на локальном(текущем) сервере | ModuleFs |
SetInit() | Помечает модуль как инициализированный | Module |
Shutdown() | Метод срабатывает при завершении работы ядра | Module |
__call() | Ставим хук на вызов неизвестного метода и считаем что хотели вызвать метод какого либо модуля | LsObject |
__clone() | Блокируем копирование/клонирование объекта | Module |
__construct() | Конструктор, запускается автоматически при создании объекта | LsObject |
__get() | Обработка доступа к объекты поведения | LsObject |
isInit() | Возвращает значение флага инициализации модуля | Module |
Protected Methods
Method | Description | Defined By |
---|---|---|
PrepareBehaviors() | Инициализация поведений | LsObject |
Property Details
Дефолтный тип пути, используется если префикс не указан
Method Details
public void CreateDirectoryLocal(string $sDirDest)
| ||
$sDirDest | string | Полный путь до каталога |
public function CreateDirectoryLocal($sDirDest)
{
if (!is_dir($sDirDest)) {
@mkdir($sDirDest, 0755, true);
}
}
Создает каталог на локальном(текущем) сервере
public void CreateDirectoryLocalSmart(string $sDirDest)
| ||
$sDirDest | string | Каталог относительно корня сайта |
public function CreateDirectoryLocalSmart($sDirDest)
{
$this->CreateDirectoryLocal(rtrim(Config::Get('path.root.server'), '/') . '/' . ltrim($sDirDest, '/'));
}
Создает каталог на локальном(текущем) сервере Отличие от CreateDirectoryLocal() в том, что здесь используется каталог относительно корня сайта
public bool CreateLock(resource $hDescriptor)
| ||
$hDescriptor | resource | Дексриптор открытого файла для блокировки |
{return} | bool |
public function CreateLock($hDescriptor)
{
return flock($hDescriptor, LOCK_EX | LOCK_NB);
}
Создает блокировку
public array GetParsedPath(string $sPath)
| ||
$sPath | string | Исходный путь с префиксом, например, [relative]/image.jpg |
{return} | array |
public function GetParsedPath($sPath)
{
if (preg_match("#^\[([a-z_0-9]*)\](.*)$#i", $sPath, $aMatch)) {
return array($aMatch[1] ? $aMatch[1] : self::PATH_TYPE_SERVER, $aMatch[2]);
}
return array(self::PATH_TYPE_SERVER, $sPath);
}
Парсит путь и возвращет его составляющие - массив вида array(0=>'relative', 1=>'/image.jpg')
public string GetPathRelative(string $sPath, bool $bWithType=false)
| ||
$sPath | string | Исходный путь с префиксом, например, [server]/home/webmaster/site.com/image.jpg |
$bWithType | bool | |
{return} | string |
public function GetPathRelative($sPath, $bWithType = false)
{
list($sType, $sPath) = $this->GetParsedPath($sPath);
if ($sType != self::PATH_TYPE_RELATIVE) {
/**
* Пробуем вызвать метод GetPathRelativeFrom[Type]()
*/
$sMethod = 'GetPathRelativeFrom' . func_camelize($sType);
if (method_exists($this, $sMethod)) {
$sPath = $this->$sMethod($sPath);
}
}
if ($bWithType) {
$sPath = $this->MakePath($sPath, self::PATH_TYPE_RELATIVE);
}
return $sPath;
}
Возвращает относительный путь
public string GetPathRelativeFromServer(string $sPath)
| ||
$sPath | string | |
{return} | string |
public function GetPathRelativeFromServer($sPath)
{
$sServerPath = rtrim(str_replace(DIRECTORY_SEPARATOR, '/', Config::Get('path.root.server')), '/');
return str_replace($sServerPath, '', str_replace(DIRECTORY_SEPARATOR, '/', $sPath));
}
Возвращает относительный путь из серверного
public string GetPathRelativeFromWeb(string $sPath)
| ||
$sPath | string | |
{return} | string |
public function GetPathRelativeFromWeb($sPath)
{
$sPath = ltrim(parse_url($sPath, PHP_URL_PATH), '/');
if ($iOffset = Config::Get('path.offset_request_url')) {
$sPath = preg_replace('#^([^/]+/*){' . $iOffset . '}#msi', '', $sPath);
}
return '/' . $sPath;
}
Возвращает относительный путь из веб
public string GetPathServer(string $sPath, bool $bWithType=false)
| ||
$sPath | string | Исходный путь с префиксом, например, [relative]/image.jpg |
$bWithType | bool | |
{return} | string |
public function GetPathServer($sPath, $bWithType = false)
{
list($sType, $sPath) = $this->GetParsedPath($sPath);
if ($sType != self::PATH_TYPE_SERVER) {
/**
* Пробуем вызвать метод GetPathServerFrom[Type]()
*/
$sMethod = 'GetPathServerFrom' . func_camelize($sType);
if (method_exists($this, $sMethod)) {
$sPath = $this->$sMethod($sPath);
}
}
if ($bWithType) {
$sPath = $this->MakePath($sPath, self::PATH_TYPE_SERVER);
}
return $sPath;
}
Возвращает серверный путь
public string GetPathServerFromRelative(string $sPath)
| ||
$sPath | string | |
{return} | string |
public function GetPathServerFromRelative($sPath)
{
return rtrim(Config::Get('path.root.server'), '/') . '/' . ltrim($sPath, '/');
}
Возвращает серверный путь из относительного
public string GetPathServerFromWeb(string $sPath)
| ||
$sPath | string | |
{return} | string |
public function GetPathServerFromWeb($sPath)
{
/**
* Определяем, принадлежит ли этот адрес основному домену
*/
if (parse_url($sPath, PHP_URL_HOST) != parse_url(Router::GetPathRootWeb(), PHP_URL_HOST)) {
return $sPath;
}
/**
* Выделяем адрес пути
*/
$sPath = ltrim(parse_url($sPath, PHP_URL_PATH), '/');
if ($iOffset = Config::Get('path.offset_request_url')) {
$sPath = preg_replace('#^([^/]+/*){' . $iOffset . '}#msi', '', $sPath);
}
return rtrim(Config::Get('path.root.server'), '/') . '/' . $sPath;
}
Возвращает серверный путь из веб
public mixed GetPathType(string $sPath)
| ||
$sPath | string | Исходный путь с префиксом, например, [relative]/image.jpg |
{return} | mixed |
public function GetPathType($sPath)
{
list($sType,) = $this->GetParsedPath($sPath);
return $sType;
}
Возвращает тип из пути
public string GetPathWeb(string $sPath, bool $bWithType=false)
| ||
$sPath | string | Исходный путь с префиксом, например, [relative]/image.jpg |
$bWithType | bool | |
{return} | string |
public function GetPathWeb($sPath, $bWithType = false)
{
list($sType, $sPath) = $this->GetParsedPath($sPath);
if ($sType != self::PATH_TYPE_WEB) {
/**
* Пробуем вызвать метод GetPathWebFrom[Type]()
*/
$sMethod = 'GetPathWebFrom' . func_camelize($sType);
if (method_exists($this, $sMethod)) {
$sPath = $this->$sMethod($sPath);
}
}
if ($bWithType) {
$sPath = $this->MakePath($sPath, self::PATH_TYPE_WEB);
}
return $sPath;
}
Возвращает веб путь (URL)
public string GetPathWebFromRelative(string $sPath)
| ||
$sPath | string | |
{return} | string |
public function GetPathWebFromRelative($sPath)
{
return Router::GetPathRootWeb() . '/' . ltrim($sPath, '/');
}
Возвращает веб путь из относительного
public string GetPathWebFromServer(string $sPath)
| ||
$sPath | string | |
{return} | string |
public function GetPathWebFromServer($sPath)
{
$sServerPath = rtrim(str_replace(DIRECTORY_SEPARATOR, '/', Config::Get('path.root.server')), '/');
$sWebPath = Router::GetPathRootWeb();
return str_replace($sServerPath, $sWebPath, str_replace(DIRECTORY_SEPARATOR, '/', $sPath));
}
Возвращает веб путь из серверного
public void Init()
|
public function Init()
{
/**
* Определяем дефолтный тип
*/
$this->sPathTypeDefault = self::PATH_TYPE_SERVER;
}
public bool IsExistsFileLocal(string $sFile)
| ||
$sFile | string | |
{return} | bool |
public function IsExistsFileLocal($sFile)
{
return file_exists($sFile);
}
Проверяет на существование локальный файл
public bool IsLock(resource $hDescriptor)
| ||
$hDescriptor | resource | Дексриптор открытого файла для блокировки |
{return} | bool |
public function IsLock($hDescriptor)
{
if (!$hDescriptor) {
return false;
}
return !$this->CreateLock($hDescriptor);
}
Проверяет наличие блокировки
public bool IsPathType(string $sPath, string $sType)
| ||
$sPath | string | Исходный путь с префиксом, например, [relative]/image.jpg |
$sType | string | |
{return} | bool |
public function IsPathType($sPath, $sType)
{
return $this->GetPathType($sPath) == $sType;
}
Проверяет принадлежность пути нужному типу
public string MakePath(string $sPath, string $sType)
| ||
$sPath | string | |
$sType | string | |
{return} | string |
public function MakePath($sPath, $sType)
{
return '[' . $sType . ']' . $sPath;
}
Формирует полный путь с учетом типа
public bool RemoveFileLocal(string $sFile)
| ||
$sFile | string | |
{return} | bool |
public function RemoveFileLocal($sFile)
{
if (file_exists($sFile)) {
return @unlink($sFile);
}
return false;
}
Удаляет локальный файл
public bool RemoveLock(resource $hDescriptor)
| ||
$hDescriptor | resource | Дексриптор открытого файла для блокировки |
{return} | bool |
public function RemoveLock($hDescriptor)
{
return ($hDescriptor && @flock($hDescriptor, LOCK_UN));
}
Удаляет блокировку
public bool SaveFileLocal(string $sFileSource, string $sFileDest, int|null $iMode=NULL, bool $bRemoveSource=false)
| ||
$sFileSource | string | Полный путь до исходного файла |
$sFileDest | string | Полный путь до файла для сохранения |
$iMode | int|null | Права chmod для файла, например, 0777 |
$bRemoveSource | bool | Удалять исходный файл или нет |
{return} | bool |
public function SaveFileLocal($sFileSource, $sFileDest, $iMode = null, $bRemoveSource = false)
{
$bResult = copy($sFileSource, $sFileDest);
if ($bResult and !is_null($iMode)) {
chmod($sFileDest, $iMode);
}
if ($bRemoveSource) {
unlink($sFileSource);
}
return $bResult;
}
Сохраняет(копирует) файл на локальном(текущем) сервере
public bool SaveFileLocalSmart(string $sFileSource, string $sDirDest, string $sFileDest, int|null $iMode=NULL, bool $bRemoveSource=false)
| ||
$sFileSource | string | Полный путь до исходного файла |
$sDirDest | string | Каталог для сохранения файла относительно корня сайта |
$sFileDest | string | Имя файла для сохранения |
$iMode | int|null | Права chmod для файла, например, 0777 |
$bRemoveSource | bool | Удалять исходный файл или нет |
{return} | bool | | string При успешном сохранении возвращает полный серверный путь до файла |
public function SaveFileLocalSmart($sFileSource, $sDirDest, $sFileDest, $iMode = null, $bRemoveSource = false)
{
$sFileDestFullPath = rtrim(Config::Get('path.root.server'), "/") . '/' . trim($sDirDest,
"/") . '/' . $sFileDest;
$this->CreateDirectoryLocalSmart($sDirDest);
if ($this->SaveFileLocal($sFileSource, $sFileDestFullPath, $iMode, $bRemoveSource)) {
return $sFileDestFullPath;
}
return false;
}
Сохраняет(копирует) файл на локальном(текущем) сервере Основное отличие от SaveLocal() в том, что здесь для указания целевого файла используется относительный каталог (если он не существует, то создается автоматически) И в случае успешного копирования метод возвращает путь до целевого файла