ModuleSearch

Package application.modules.search
Inheritance class ModuleSearch » Module » LsObject
Since 2.0
Source Code /application/classes/modules/search/Search.class.php
Модуль поиска

Protected Properties

Hide inherited properties

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

Public Methods

Hide inherited methods

MethodDescriptionDefined By
AddBehaviorHook() Добавляет хук поведения LsObject
AttachBehavior() Присоединяет поведение к объекту LsObject
BuildExcerpts() Выделяет отрывки из текста с необходимыми словами (делает сниппеты) ModuleSearch
DetachBehavior() Отсоединяет поведение от объекта LsObject
GetBehavior() Возвращает объект поведения по его имени LsObject
GetBehaviors() Возвращает все объекты поведения LsObject
GetRegexpForWords() Возвращает регулярное выражение для поиска в БД по словам ModuleSearch
GetWordsForSearch() Возвращает массив слов из поискового запроса ModuleSearch
Init() Инициализация модуля ModuleSearch
RemoveBehaviorHook() Удаляет хук поведения LsObject
RunBehaviorHook() Запускает хук поведения на выполнение LsObject
SearchComments() Выполняет поиск комментариев по регулярному выражению ModuleSearch
SearchTopics() Выполняет поиск топиков по регулярному выражению ModuleSearch
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

oMapper property
protected $oMapper;

Method Details

BuildExcerpts() method
public string BuildExcerpts(string $sText, array|string $aWords, array $aParams=array ( ))
$sText string Исходный текст
$aWords array|string Список слов
$aParams array Список параметром
{return} string
Source Code: /application/classes/modules/search/Search.class.php#101 (show)
public function BuildExcerpts($sText$aWords$aParams = array())
{
    
$iMaxLengthBetweenWords = isset($aParams['iMaxLengthBetweenWords']) ? $aParams['iMaxLengthBetweenWords'] : 200;
    
$iLengthIndentSection = isset($aParams['iLengthIndentSection']) ? $aParams['iLengthIndentSection'] : 100;
    
$iMaxCountSections = isset($aParams['iMaxCountSections']) ? $aParams['iMaxCountSections'] : 3;
    
$sWordWrapBegin = isset($aParams['sWordWrapBegin']) ? $aParams['sWordWrapBegin'] : '<span class="searched-item">';
    
$sWordWrapEnd = isset($aParams['sWordWrapEnd']) ? $aParams['sWordWrapEnd'] : '</span>';
    
$sGlueSections = isset($aParams['sGlueSections']) ? $aParams['sGlueSections'] : "\r\n";

    
$sText strip_tags($sText);
    
$sText trim($sText);
    if (
is_string($aWords)) {
        
$aWords preg_split('#[\W]+#u'$aWords);
    }
    
$sPregWords join('|'array_filter($aWords'preg_quote'));
    
$aSections = array();
    if (
preg_match_all("#{$sPregWords}#i"$sText$aMatchAllPREG_OFFSET_CAPTURE)) {
        
$aSectionItems = array();
        
$iCountDiff = -1;
        foreach (
$aMatchAll[0] as $aMatch) {
            if (
$iCountDiff == -or $aMatch[1] - $iCountDiff <= $iMaxLengthBetweenWords) {
                
$aSectionItems[] = $aMatch;
                
$iCountDiff $aMatch[1];
            } else {
                
$aSections[] = array('items' => $aSectionItems);
                
$aSectionItems = array();
                
$aSectionItems[] = $aMatch;
                
$iCountDiff $aMatch[1];
            }
        }
        if (
count($aSectionItems)) {
            
$aSections[] = array('items' => $aSectionItems);
        }
    }

    
$aSections array_slice($aSections0$iMaxCountSections);

    
$sTextResult '';
    if (
$aSections) {
        foreach (
$aSections as $aSection) {
            
/**
             * Расчитываем дополнительные данные: начало и конец фрагмента, уникальный список слов
             */
            
$aItem reset($aSection['items']);
            
$aSection['begin'] = $aItem[1];
            
$aItem end($aSection['items']);
            
$aSection['end'] = $aItem[1] + mb_strlen($aItem[0], 'utf-8');
            
$aSection['words'] = array();

            foreach (
$aSection['items'] as $aItem) {
                
$sKey mb_strtolower($aItem[0], 'utf-8');
                
$aSection['words'][$sKey] = $aItem[0];
            }

            
/**
             * Формируем фрагменты текста
             */

            /**
             * Определям правую границу текста по слову
             */
            
$iEnd $aSection['end'];
            for (
$i $iEnd; ($i <= $aSection['end'] + $iLengthIndentSection) and $i mb_strlen($sText,
                
'utf-8'); $i++) {
                if (
preg_match('#^\s$#'mb_substr($sText$i1'utf-8'))) {
                    
$iEnd $i;
                }
            }
            
/**
             * Определям левую границу текста по слову
             */
            
$iBegin $aSection['begin'];
            for (
$i $iBegin; ($i >= $aSection['begin'] - $iLengthIndentSection) and $i >= 0$i--) {
                if (
preg_match('#^\s$#'mb_substr($sText$i1'utf-8'))) {
                    
$iBegin $i;
                }
            }
            
/**
             * Вырезаем фрагмент текста
             */
            
$sTextSection trim(mb_substr($sText$iBegin$iEnd $iBegin'utf-8'));
            if (
$iBegin 0) {
                
$sTextSection '...' $sTextSection;
            }
            if (
$iEnd mb_strlen($sText'utf-8')) {
                
$sTextSection .= '...';
            }
            
$sTextSection preg_replace("#{$sPregWords}#i"$sWordWrapBegin '\\0' $sWordWrapEnd,
                
$sTextSection);
            
$sTextResult .= $sTextSection $sGlueSections;
        }
    } else {
        
$iLength $iMaxLengthBetweenWords 2;
        if (
$iLength mb_strlen($sText'utf-8')) {
            
$iLength mb_strlen($sText'utf-8');
        }
        
$sTextResult trim(mb_substr($sText0$iLength 1'utf-8'));
    }
    return 
$sTextResult;
}

Выделяет отрывки из текста с необходимыми словами (делает сниппеты)

GetRegexpForWords() method
public string GetRegexpForWords($aWords $aWords)
$aWords $aWords
{return} string
Source Code: /application/classes/modules/search/Search.class.php#237 (show)
public function GetRegexpForWords($aWords)
{
    return 
join('|'$aWords);
}

Возвращает регулярное выражение для поиска в БД по словам

GetWordsForSearch() method
public array GetWordsForSearch($sQuery $sQuery)
$sQuery $sQuery
{return} array
Source Code: /application/classes/modules/search/Search.class.php#209 (show)
public function GetWordsForSearch($sQuery)
{
    
/**
     * Удаляем запрещенные символы
     */
    
$sQuery preg_replace('#[^\w\sа-я\-]+#iu'' '$sQuery);
    
/**
     * Разбиваем фразу на слова
     */
    
$aWords preg_split('#[\s]+#u'$sQuery);
    foreach (
$aWords as $k => $sWord) {
        
/**
         * Короткие слова удаляем
         */
        
if (mb_strlen($sWord'utf-8') < 3) {
            unset(
$aWords[$k]);
        }
    }
    return 
$aWords;
}

Возвращает массив слов из поискового запроса

Init() method
public void Init()
Source Code: /application/classes/modules/search/Search.class.php#36 (show)
public function Init()
{
    
$this->oMapper Engine::GetMapper(__CLASS__);
}

Инициализация модуля

SearchComments() method
public array SearchComments($sRegexp $sRegexp, $iCurrPage $iCurrPage, $iPerPage $iPerPage, $sTargetType $sTargetType)
$sRegexp $sRegexp
$iCurrPage $iCurrPage
$iPerPage $iPerPage
$sTargetType $sTargetType
{return} array
Source Code: /application/classes/modules/search/Search.class.php#76 (show)
public function SearchComments($sRegexp$iCurrPage$iPerPage$sTargetType)
{
    
$sCacheKey "search_comments_{$sRegexp}_{$iCurrPage}_{$iPerPage}_" serialize($sTargetType);
    if (
false === ($data $this->Cache_Get($sCacheKey))) {
        
$data = array(
            
'collection' => $this->oMapper->SearchComments($sRegexp$iCount$iCurrPage$iPerPage$sTargetType),
            
'count'      => $iCount
        
);
        
$this->Cache_Set($data$sCacheKey, array('comment_new'), 60 60 24 1);
    }
    if (
$data['collection']) {
        
$data['collection'] = $this->Comment_GetCommentsAdditionalData($data['collection']);
    }
    return 
$data;
}

Выполняет поиск комментариев по регулярному выражению

SearchTopics() method
public array SearchTopics($sRegexp $sRegexp, $iCurrPage $iCurrPage, $iPerPage $iPerPage)
$sRegexp $sRegexp
$iCurrPage $iCurrPage
$iPerPage $iPerPage
{return} array
Source Code: /application/classes/modules/search/Search.class.php#50 (show)
public function SearchTopics($sRegexp$iCurrPage$iPerPage)
{
    
$sCacheKey "search_topics_{$sRegexp}_{$iCurrPage}_{$iPerPage}";
    if (
false === ($data $this->Cache_Get($sCacheKey))) {
        
$data = array(
            
'collection' => $this->oMapper->SearchTopics($sRegexp$iCount$iCurrPage$iPerPage),
            
'count'      => $iCount
        
);
        
$this->Cache_Set($data$sCacheKey, array('topic_update''topic_new'), 60 60 24 1);
    }
    if (
$data['collection']) {
        
$data['collection'] = $this->Topic_GetTopicsAdditionalData($data['collection']);
    }
    return 
$data;
}

Выполняет поиск топиков по регулярному выражению