ModuleFs

Package framework.modules
Inheritance class ModuleFs » Module » LsObject
Since 2.0
Source Code /framework/classes/modules/fs/Fs.class.php
Модуль для работы с файловой системой TODO: проверить работу под Windows

Protected Properties

Hide inherited properties

PropertyTypeDescriptionDefined By
_aBehaviors Список поведений в виде готовых объектов, формируется автоматически LsObject
aBehaviors array Список поведений LsObject
bIsInit bool Указывает на то, была ли проведенна инициализация модуля Module
sPathTypeDefault string|null Дефолтный тип пути, используется если префикс не указан ModuleFs

Public Methods

Hide inherited methods

MethodDescriptionDefined 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

Hide inherited methods

MethodDescriptionDefined By
PrepareBehaviors() Инициализация поведений LsObject

Property Details

sPathTypeDefault property
protected string|null $sPathTypeDefault;

Дефолтный тип пути, используется если префикс не указан

Method Details

CreateDirectoryLocal() method
public void CreateDirectoryLocal(string $sDirDest)
$sDirDest string Полный путь до каталога
Source Code: /framework/classes/modules/fs/Fs.class.php#335 (show)
public function CreateDirectoryLocal($sDirDest)
{
    if (!
is_dir($sDirDest)) {
        @
mkdir($sDirDest0755true);
    }
}

Создает каталог на локальном(текущем) сервере

CreateDirectoryLocalSmart() method
public void CreateDirectoryLocalSmart(string $sDirDest)
$sDirDest string Каталог относительно корня сайта
Source Code: /framework/classes/modules/fs/Fs.class.php#348 (show)
public function CreateDirectoryLocalSmart($sDirDest)
{
    
$this->CreateDirectoryLocal(rtrim(Config::Get('path.root.server'), '/') . '/' ltrim($sDirDest'/'));
}

Создает каталог на локальном(текущем) сервере Отличие от CreateDirectoryLocal() в том, что здесь используется каталог относительно корня сайта

CreateLock() method
public bool CreateLock(resource $hDescriptor)
$hDescriptor resource Дексриптор открытого файла для блокировки
{return} bool
Source Code: /framework/classes/modules/fs/Fs.class.php#402 (show)
public function CreateLock($hDescriptor)
{
    return 
flock($hDescriptorLOCK_EX LOCK_NB);
}

Создает блокировку

GetParsedPath() method
public array GetParsedPath(string $sPath)
$sPath string Исходный путь с префиксом, например, [relative]/image.jpg
{return} array
Source Code: /framework/classes/modules/fs/Fs.class.php#277 (show)
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')

GetPathRelative() method
public string GetPathRelative(string $sPath, bool $bWithType=false)
$sPath string Исходный путь с префиксом, например, [server]/home/webmaster/site.com/image.jpg
$bWithType bool
{return} string
Source Code: /framework/classes/modules/fs/Fs.class.php#134 (show)
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($sPathself::PATH_TYPE_RELATIVE);
    }
    return 
$sPath;
}

Возвращает относительный путь

GetPathRelativeFromServer() method
public string GetPathRelativeFromServer(string $sPath)
$sPath string
{return} string
Source Code: /framework/classes/modules/fs/Fs.class.php#184 (show)
public function GetPathRelativeFromServer($sPath)
{
    
$sServerPath rtrim(str_replace(DIRECTORY_SEPARATOR'/'Config::Get('path.root.server')), '/');
    return 
str_replace($sServerPath''str_replace(DIRECTORY_SEPARATOR'/'$sPath));
}

Возвращает относительный путь из серверного

GetPathRelativeFromWeb() method
public string GetPathRelativeFromWeb(string $sPath)
$sPath string
{return} string
Source Code: /framework/classes/modules/fs/Fs.class.php#197 (show)
public function GetPathRelativeFromWeb($sPath)
{
    
$sPath ltrim(parse_url($sPathPHP_URL_PATH), '/');
    if (
$iOffset Config::Get('path.offset_request_url')) {
        
$sPath preg_replace('#^([^/]+/*){' $iOffset '}#msi'''$sPath);
    }
    return 
'/' $sPath;
}

Возвращает относительный путь из веб

GetPathServer() method
public string GetPathServer(string $sPath, bool $bWithType=false)
$sPath string Исходный путь с префиксом, например, [relative]/image.jpg
$bWithType bool
{return} string
Source Code: /framework/classes/modules/fs/Fs.class.php#82 (show)
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($sPathself::PATH_TYPE_SERVER);
    }
    return 
$sPath;
}

Возвращает серверный путь

GetPathServerFromRelative() method
public string GetPathServerFromRelative(string $sPath)
$sPath string
{return} string
Source Code: /framework/classes/modules/fs/Fs.class.php#227 (show)
public function GetPathServerFromRelative($sPath)
{
    return 
rtrim(Config::Get('path.root.server'), '/') . '/' ltrim($sPath'/');
}

Возвращает серверный путь из относительного

GetPathServerFromWeb() method
public string GetPathServerFromWeb(string $sPath)
$sPath string
{return} string
Source Code: /framework/classes/modules/fs/Fs.class.php#159 (show)
public function GetPathServerFromWeb($sPath)
{
    
/**
     * Определяем, принадлежит ли этот адрес основному домену
     */
    
if (parse_url($sPathPHP_URL_HOST) != parse_url(Router::GetPathRootWeb(), PHP_URL_HOST)) {
        return 
$sPath;
    }
    
/**
     * Выделяем адрес пути
     */
    
$sPath ltrim(parse_url($sPathPHP_URL_PATH), '/');
    if (
$iOffset Config::Get('path.offset_request_url')) {
        
$sPath preg_replace('#^([^/]+/*){' $iOffset '}#msi'''$sPath);
    }
    return 
rtrim(Config::Get('path.root.server'), '/') . '/' $sPath;
}

Возвращает серверный путь из веб

GetPathType() method
public mixed GetPathType(string $sPath)
$sPath string Исходный путь с префиксом, например, [relative]/image.jpg
{return} mixed
Source Code: /framework/classes/modules/fs/Fs.class.php#264 (show)
public function GetPathType($sPath)
{
    list(
$sType,) = $this->GetParsedPath($sPath);
    return 
$sType;
}

Возвращает тип из пути

GetPathWeb() method
public string GetPathWeb(string $sPath, bool $bWithType=false)
$sPath string Исходный путь с префиксом, например, [relative]/image.jpg
$bWithType bool
{return} string
Source Code: /framework/classes/modules/fs/Fs.class.php#108 (show)
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($sPathself::PATH_TYPE_WEB);
    }
    return 
$sPath;
}

Возвращает веб путь (URL)

GetPathWebFromRelative() method
public string GetPathWebFromRelative(string $sPath)
$sPath string
{return} string
Source Code: /framework/classes/modules/fs/Fs.class.php#239 (show)
public function GetPathWebFromRelative($sPath)
{
    return 
Router::GetPathRootWeb() . '/' ltrim($sPath'/');
}

Возвращает веб путь из относительного

GetPathWebFromServer() method
public string GetPathWebFromServer(string $sPath)
$sPath string
{return} string
Source Code: /framework/classes/modules/fs/Fs.class.php#213 (show)
public function GetPathWebFromServer($sPath)
{
    
$sServerPath rtrim(str_replace(DIRECTORY_SEPARATOR'/'Config::Get('path.root.server')), '/');
    
$sWebPath Router::GetPathRootWeb();
    return 
str_replace($sServerPath$sWebPathstr_replace(DIRECTORY_SEPARATOR'/'$sPath));
}

Возвращает веб путь из серверного

Init() method
public void Init()
Source Code: /framework/classes/modules/fs/Fs.class.php#53 (show)
public function Init()
{
    
/**
     * Определяем дефолтный тип
     */
    
$this->sPathTypeDefault self::PATH_TYPE_SERVER;
}

IsExistsFileLocal() method
public bool IsExistsFileLocal(string $sFile)
$sFile string
{return} bool
Source Code: /framework/classes/modules/fs/Fs.class.php#375 (show)
public function IsExistsFileLocal($sFile)
{
    return 
file_exists($sFile);
}

Проверяет на существование локальный файл

IsLock() method
public bool IsLock(resource $hDescriptor)
$hDescriptor resource Дексриптор открытого файла для блокировки
{return} bool
Source Code: /framework/classes/modules/fs/Fs.class.php#387 (show)
public function IsLock($hDescriptor)
{
    if (!
$hDescriptor) {
        return 
false;
    }
    return !
$this->CreateLock($hDescriptor);
}

Проверяет наличие блокировки

IsPathType() method
public bool IsPathType(string $sPath, string $sType)
$sPath string Исходный путь с префиксом, например, [relative]/image.jpg
$sType string
{return} bool
Source Code: /framework/classes/modules/fs/Fs.class.php#252 (show)
public function IsPathType($sPath$sType)
{
    return 
$this->GetPathType($sPath) == $sType;
}

Проверяет принадлежность пути нужному типу

MakePath() method
public string MakePath(string $sPath, string $sType)
$sPath string
$sType string
{return} string
Source Code: /framework/classes/modules/fs/Fs.class.php#69 (show)
public function MakePath($sPath$sType)
{
    return 
'[' $sType ']' $sPath;
}

Формирует полный путь с учетом типа

RemoveFileLocal() method
public bool RemoveFileLocal(string $sFile)
$sFile string
{return} bool
Source Code: /framework/classes/modules/fs/Fs.class.php#360 (show)
public function RemoveFileLocal($sFile)
{
    if (
file_exists($sFile)) {
        return @
unlink($sFile);
    }
    return 
false;
}

Удаляет локальный файл

RemoveLock() method
public bool RemoveLock(resource $hDescriptor)
$hDescriptor resource Дексриптор открытого файла для блокировки
{return} bool
Source Code: /framework/classes/modules/fs/Fs.class.php#414 (show)
public function RemoveLock($hDescriptor)
{
    return (
$hDescriptor && @flock($hDescriptorLOCK_UN));
}

Удаляет блокировку

SaveFileLocal() method
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
Source Code: /framework/classes/modules/fs/Fs.class.php#294 (show)
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;
}

Сохраняет(копирует) файл на локальном(текущем) сервере

SaveFileLocalSmart() method
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 При успешном сохранении возвращает полный серверный путь до файла
Source Code: /framework/classes/modules/fs/Fs.class.php#318 (show)
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() в том, что здесь для указания целевого файла используется относительный каталог (если он не существует, то создается автоматически) И в случае успешного копирования метод возвращает путь до целевого файла