ModuleProperty

Package application.modules.property
Inheritance class ModuleProperty » ModuleORM » Module » LsObject
Since 2.0
Source Code /application/classes/modules/property/Property.class.php
Модуль управления дополнительными полями

Protected Properties

Hide inherited properties

PropertyTypeDescriptionDefined By
_aBehaviors Список поведений в виде готовых объектов, формируется автоматически LsObject
aBehaviors array Список поведений LsObject
aPropertyTypes array Список доступных типов полей ModuleProperty
aTargetTypes array Список разрешенных типов ModuleProperty
bIsInit bool Указывает на то, была ли проведенна инициализация модуля Module
oMapper ModuleProperty
oMapperORM MapperORM Объект маппера ORM ModuleORM

Public Methods

Hide inherited methods

MethodDescriptionDefined By
AddBehaviorHook() Добавляет хук поведения LsObject
AddTargetType() Добавляет в разрешенные новый тип ModuleProperty
AttachBehavior() Присоединяет поведение к объекту LsObject
AttachPropertiesForTarget() Служебный метод для аттача свойст к сущности ModuleProperty
AttachValueForProperties() Для каждого из свойств получает значение ModuleProperty
ChangeTargetType() Производит изменение названия типа объекта, например "article" меняем на "news" ModuleProperty
CheckAllowTargetObject() ModuleProperty
CreateDefaultTargetPropertyFromPlugin() Используется для создания дефолтных дополнительных полей при активации плагина ModuleProperty
CreateTargetProperty() Автоматическое создание дополнительного поля ModuleProperty
CreateTargetType() Создает новый тип объекта в БД для дополнительных полей ModuleProperty
DeleteItemsByFilter() Удаляет сущности по фильтру ModuleORM
DetachBehavior() Отсоединяет поведение от объекта LsObject
GetAggregateFunctionByFilter() Получить значение агрегирующей функции ModuleORM
GetBehavior() Возвращает объект поведения по его имени LsObject
GetBehaviors() Возвращает все объекты поведения LsObject
GetByFilter() Получить сущность по фильтру ModuleORM
GetCountItemsByFilter() Получить количество сущностей по фильтру ModuleORM
GetCountItemsByJoinEntity() ModuleORM
GetEntityProperty() Возвращает объект свойства сущности ModuleProperty
GetEntityPropertyList() Возвращает список свойств сущности ModuleProperty
GetEntityPropertyValue() Возвращает значение свойсва у объекта ModuleProperty
GetEntityPropertyValueObject() Возвращает объект свойства ModuleProperty
GetItemsByArray() Возвращает список сущностей по фильтру ModuleORM
GetItemsByFilter() Получить список сущностей по фильтру ModuleORM
GetItemsByJoinEntity() ModuleORM
GetPropertiesForUpdate() Возвращает набор полей/свойств для показа их на форме редактирования ModuleProperty
GetPropertyTagsByLike() Возвращает список тегов/знаяений свойства. Используется для авкомплиттера тегов. ModuleProperty
GetPropertyTagsCloud() Формирует и возвращает облако тегов необходимого свойства ModuleProperty
GetPropertyTagsGroup() Возвращет список группированных тегов с их количеством для необходимого свойства ModuleProperty
GetTargetTypeParams() Возвращает парметры нужного типа ModuleProperty
GetTargetTypes() Возвращает список типов объектов ModuleProperty
GetTargetsByTag() Список ID сущностей по тегу конкретного свойства ModuleProperty
Init() ModuleProperty
IsAllowPropertyType() Проверяет разрешен ли тип поля ModuleProperty
IsAllowTargetType() Проверяет разрешен ли данный тип ModuleProperty
LoadTree() Для сущностей со связью RELATION_TYPE_TREE возвращает список сущностей в виде дерева ModuleORM
RemoveBehaviorHook() Удаляет хук поведения LsObject
RemovePropertiesValue() Удаление всех свойств у конкретного объекта/сущности ModuleProperty
RemoveSelectByPropertyId() ModuleProperty
RemoveTargetType() Отключает тип объекта для дополнительных полей ModuleProperty
RemoveValueByPropertyId() ModuleProperty
RemoveValueSelectByPropertyId() ModuleProperty
RemoveValueSelectsByTarget() Удаляет значения типа select ModuleProperty
RemoveValueTagByPropertyId() ModuleProperty
RemoveValueTagsByTarget() Удаляет теги свойства у сущности ModuleProperty
RewriteFilter() Обработка фильтра ORM запросов ModuleProperty
RewriteGetItemsByFilter() Переопределяем метод для возможности цеплять свои кастомные данные при ORM запросах - свойства ModuleProperty
RunBehaviorHook() Запускает хук поведения на выполнение LsObject
SetInit() Помечает модуль как инициализированный Module
Shutdown() Метод срабатывает при завершении работы ядра Module
UpdatePropertiesValue() Сохраняет текущие значения свойств ModuleProperty
ValidateEntityPropertiesCheck() Валидирует значение свойств у объекта ModuleProperty
__call() Ставим хук на вызов неизвестного метода и считаем что хотели вызвать метод какого либо модуля. ModuleORM
__clone() Блокируем копирование/клонирование объекта Module
__construct() Конструктор, запускается автоматически при создании объекта LsObject
__get() Обработка доступа к объекты поведения LsObject
buildTree() Построение дерева ModuleORM
isInit() Возвращает значение флага инициализации модуля Module

Protected Methods

Hide inherited methods

MethodDescriptionDefined By
ArrayReplaceKey() Служебный метод для замены ключа в массиве ModuleProperty
PrepareBehaviors() Инициализация поведений LsObject
_AddEntity() Добавление сущности в БД ModuleORM
_DeleteEntity() Удаление сущности из БД ModuleORM
_GetAncestorsOfEntity() Для сущности со связью RELATION_TYPE_TREE возвращает список всех предков ModuleORM
_GetChildrenOfEntity() Для сущности со связью RELATION_TYPE_TREE возвращает список прямых потомков ModuleORM
_GetDescendantsOfEntity() Для сущности со связью RELATION_TYPE_TREE возвращает список всех потомков ModuleORM
_GetParentOfEntity() Для сущности со связью RELATION_TYPE_TREE возвращает предка ModuleORM
_LoadMapperORM() Загрузка маппера ORM ModuleORM
_NormalizeEntityRootName() Приводит название сущности к единому формату полного имени класса ModuleORM
_ReloadEntity() Обновляет данные сущности из БД ModuleORM
_SaveEntity() Сохранение сущности в БД ModuleORM
_ShowColumnsFrom() Список полей сущности ModuleORM
_ShowPrimaryIndexFrom() Primary индекс сущности ModuleORM
_UpdateEntity() Обновление сущности в БД ModuleORM
_deleteManyToManyRelation() Выполняет удаление всех связей many_to_many сущности ModuleORM
_setIndexesFromField() Returns assotiative array, indexed by PRIMARY KEY or another field. ModuleORM
_setIndexesGroupField() Возвращает сгруппированный массив по нужному полю ModuleORM
_setIndexesGroupJoinField() Возвращает сгруппированный массив по нужному полю из данных таблицы связей ModuleORM
_updateManyToManyRelation() Выполняет обновление связи many_to_many у сущности ModuleORM

Property Details

aPropertyTypes property
protected array $aPropertyTypes;

Список доступных типов полей

aTargetTypes property
protected array $aTargetTypes;

Список разрешенных типов На данный момент допустимы параметры entity=>ModuleTest_EntityTest - указывает на класс сущности name=>Статьи

oMapper property
protected $oMapper;

Method Details

AddTargetType() method
public bool AddTargetType(string $sTargetType, array $aParams=array ( ))
$sTargetType string Тип
$aParams array Параметры
{return} bool
Source Code: /application/classes/modules/property/Property.class.php#111 (show)
public function AddTargetType($sTargetType$aParams = array())
{
    if (!
array_key_exists($sTargetType$this->aTargetTypes)) {
        
$this->aTargetTypes[$sTargetType] = $aParams;
        return 
true;
    }
    return 
false;
}

Добавляет в разрешенные новый тип

ArrayReplaceKey() method
protected array|bool ArrayReplaceKey(array $aArray, string $sKeyOld, string $sKeyNew)
$aArray array
$sKeyOld string
$sKeyNew string
{return} array|bool
Source Code: /application/classes/modules/property/Property.class.php#629 (show)
protected function ArrayReplaceKey($aArray$sKeyOld$sKeyNew)
{
    
$aKeys array_keys($aArray);
    if (
false === $iIndex array_search($sKeyOld$aKeys)) {
        return 
false;
    }
    
$aKeys[$iIndex] = $sKeyNew;
    return 
array_combine($aKeysarray_values($aArray));
}

Служебный метод для замены ключа в массиве

AttachPropertiesForTarget() method
public void AttachPropertiesForTarget(Entity $oTarget, array $aProperties)
$oTarget Entity Объект сущности
$aProperties array Список свойств
Source Code: /application/classes/modules/property/Property.class.php#354 (show)
public function AttachPropertiesForTarget($oTarget$aProperties)
{
    
$oTarget->setPropertyList($aProperties);
    
$oTarget->setPropertyIsLoadAll(true);
    
$aMapperCode = array();
    foreach (
$aProperties as $oProperty) {
        
$aMapperCode[$oProperty->getCode()] = $oProperty->getId();
    }
    
$oTarget->setPropertyMapperCode($aMapperCode);
}

Служебный метод для аттача свойст к сущности

AttachValueForProperties() method
public bool AttachValueForProperties(array $aProperties, string $sTargetType, int $iTargetId)
$aProperties array Список свойств
$sTargetType string Тип объекта
$iTargetId int ID объекта
{return} bool
Source Code: /application/classes/modules/property/Property.class.php#166 (show)
public function AttachValueForProperties($aProperties$sTargetType$iTargetId)
{
    if (!
$aProperties) {
        return 
false;
    }
    
/**
     * Формируем список ID свойств
     */
    
$aPropertyIds = array();
    foreach (
$aProperties as $oProperty) {
        
$aPropertyIds[] = $oProperty->getId();
    }
    
/**
     * Получаем список значений
     */
    
$aValues $this->Property_GetValueItemsByFilter(array(
            
'target_id'      => $iTargetId,
            
'target_type'    => $sTargetType,
            
'property_id in' => $aPropertyIds,
            
'#index-from'    => 'property_id'
        
));
    
/**
     * Аттачим значения к свойствам
     */
    
foreach ($aProperties as $oProperty) {
        if (isset(
$aValues[$oProperty->getId()])) {
            
$oProperty->setValue($aValues[$oProperty->getId()]);
        } else {
            
$oProperty->setValue(Engine::GetEntity('ModuleProperty_EntityValue', array(
                        
'property_id'   => $oProperty->getId(),
                        
'property_type' => $oProperty->getType(),
                        
'target_type'   => $sTargetType,
                        
'target_id'     => $iTargetId
                    
)));
        }
        
$oProperty->getValue()->setProperty($oProperty);
    }
    return 
true;
}

Для каждого из свойств получает значение

ChangeTargetType() method
public void ChangeTargetType($sType $sType, $sTypeNew $sTypeNew)
$sType $sType
$sTypeNew $sTypeNew
Source Code: /application/classes/modules/property/Property.class.php#739 (show)
public function ChangeTargetType($sType$sTypeNew)
{
    
$this->oMapper->UpdatePropertyByTargetType($sType$sTypeNew);
    
$this->oMapper->UpdatePropertyTargetByTargetType($sType$sTypeNew);
    
$this->oMapper->UpdatePropertySelectByTargetType($sType$sTypeNew);
    
$this->oMapper->UpdatePropertyValueByTargetType($sType$sTypeNew);
    
$this->oMapper->UpdatePropertyValueSelectByTargetType($sType$sTypeNew);
    
$this->oMapper->UpdatePropertyValueTagByTargetType($sType$sTypeNew);
    
/**
     * Сбрасываем кеши
     */
    
$this->Cache_Clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG, array(
        
'ModuleProperty_EntityProperty_save',
        
'ModuleProperty_EntityTarget_save',
        
'ModuleProperty_EntitySelect_save',
        
'ModuleProperty_EntityValue_save',
        
'ModuleProperty_EntityValueSelect_save',
        
'ModuleProperty_EntityValueTag_save',
    ));
}

Производит изменение названия типа объекта, например "article" меняем на "news"

CheckAllowTargetObject() method
public void CheckAllowTargetObject($sTargetType, $iTargetId, $aParams=array ( ))
$sTargetType
$iTargetId
$aParams
Source Code: /application/classes/modules/property/Property.class.php#951 (show)
public function CheckAllowTargetObject($sTargetType$iTargetId$aParams = array())
{
    
$sMethod 'CheckAllowTargetObject' func_camelize($sTargetType);
    if (
method_exists($this$sMethod)) {
        if (!
array_key_exists('user'$aParams)) {
            
$aParams['user'] = $this->oUserCurrent;
        }
        return 
$this->$sMethod($iTargetId$aParams);
    }
    
/**
     * По умолчанию считаем доступ разрешен
     */
    
return true;
}

CreateDefaultTargetPropertyFromPlugin() method
public bool CreateDefaultTargetPropertyFromPlugin(array $aProperties, string $sTargetType)
$aProperties array Список полей
array(
   array(
       'data'=>array(
       'type'=>ModuleProperty::PROPERTY_TYPE_INT,
       'title'=>'Номер',
       'code'=>'number',
       'sort'=>100
   ),
   'validate_rule'=>array(
       'min'=>10
   ),
   'params'=>array(),
   'additional'=>array()
   )
);
$sTargetType string Тип объекта
{return} bool
Source Code: /application/classes/modules/property/Property.class.php#904 (show)
public function CreateDefaultTargetPropertyFromPlugin($aProperties$sTargetType)
{
    foreach (
$aProperties as $aProperty) {
        
$sResultMsg $this->CreateTargetProperty($sTargetType$aProperty['data'], true,
            
$aProperty['validate_rule'], $aProperty['params'], $aProperty['additional']);
        if (
$sResultMsg !== true and !is_object($sResultMsg)) {
            if (
is_string($sResultMsg)) {
                
$this->Message_AddErrorSingle($sResultMsg$this->Lang_Get('error'), true);
            }
            
/**
             * Отменяем добавление типа
             */
            
$this->RemoveTargetType($sTargetTypeModuleProperty::TARGET_STATE_NOT_ACTIVE);
            return 
false;
        }
    }
    return 
true;
}

Используется для создания дефолтных дополнительных полей при активации плагина

CreateTargetProperty() method
public bool|ModuleProperty_EntityProperty CreateTargetProperty(string $sTargetType, array $aData, bool $bSkipErrorUniqueCode=true, array $aValidateRules=array ( ), array $aParams=array ( ), array $aAdditional=array ( ))
$sTargetType string Тип объекта дял которого добавляем поле
$aData array Данные поля: array('type'=>'int','title'=>'Название','code'=>'newfield','description'=>'Описание поля','sort'=>100);
$bSkipErrorUniqueCode bool Пропускать ошибку при дублировании кода поля (такое поле уже существует)
$aValidateRules array Данные валидатора поля, зависят от конкретного типа поля: array('allowEmpty'=>true,'max'=>1000)
$aParams array Дополнительные параметры поля, зависят от типа поля
$aAdditional array Дополнительные данные, которые нужно учитывать при создании поля, зависят от типа поля
{return} bool|ModuleProperty_EntityProperty
Source Code: /application/classes/modules/property/Property.class.php#844 (show)
public function CreateTargetProperty(
    
$sTargetType,
    
$aData,
    
$bSkipErrorUniqueCode true,
    
$aValidateRules = array(),
    
$aParams = array(),
    
$aAdditional = array()
) {
    
/**
     * Если необходимо и поле уже существует, то пропускаем создание
     */
    
if ($bSkipErrorUniqueCode and isset($aData['code']) and $this->GetPropertyByTargetTypeAndCode($sTargetType,
            
$aData['code'])
    ) {
        return 
true;
    }

    
$oProperty Engine::GetEntity('ModuleProperty_EntityProperty');
    
$oProperty->_setValidateScenario('auto');
    
$oProperty->_setDataSafe($aData);
    
$oProperty->setValidateRulesRaw($aValidateRules);
    
$oProperty->setParamsRaw($aParams);
    
$oProperty->setTargetType($sTargetType);
    if (
$oProperty->_Validate()) {
        if (
$oProperty->Add()) {
            return 
$oProperty;
        } else {
            return 
'Возникла ошибка при добавлении поля';
        }
    } else {
        return 
$oProperty->_getValidateError();
    }
    return 
false;
}

Автоматическое создание дополнительного поля TODO: учитывать $aAdditional для создание вариантов в типе select

CreateTargetType() method
public bool|ModuleProperty_EntityTarget CreateTargetType(string $sType, array $aParams, bool $bRewrite=false)
$sType string
$aParams array
$bRewrite bool
{return} bool|ModuleProperty_EntityTarget
Source Code: /application/classes/modules/property/Property.class.php#769 (show)
public function CreateTargetType($sType$aParams$bRewrite false)
{
    
/**
     * Проверяем есть ли уже такой тип
     */
    
if ($oTarget $this->GetTargetByType($sType)) {
        if (!
$bRewrite) {
            return 
false;
        }
    } else {
        
$oTarget Engine::GetEntity('ModuleProperty_EntityTarget');
        
$oTarget->setType($sType);
    }
    
$oTarget->setState(self::TARGET_STATE_ACTIVE);
    
$oTarget->setParams($aParams);
    if (
$oTarget->Save()) {
        return 
$oTarget;
    }
    return 
false;
}

Создает новый тип объекта в БД для дополнительных полей

GetEntityProperty() method
public null|ModuleProperty_EntityProperty GetEntityProperty(Entity $oTarget, int $sPropertyId)
$oTarget Entity Объект сущности
$sPropertyId int ID свойства
{return} null|ModuleProperty_EntityProperty
Source Code: /application/classes/modules/property/Property.class.php#316 (show)
public function GetEntityProperty($oTarget$sPropertyId)
{
    if (
$oProperty $this->GetEntityPropertyValueObject($oTarget$sPropertyId)) {
        return 
$oProperty;
    }
    return 
null;
}

Возвращает объект свойства сущности

GetEntityPropertyList() method
public array GetEntityPropertyList(Entity $oTarget)
$oTarget Entity Объект сущности
{return} array
Source Code: /application/classes/modules/property/Property.class.php#331 (show)
public function GetEntityPropertyList($oTarget)
{
    
$sTargetType $oTarget->property->getPropertyTargetType();
    
/**
     * Проверяем зарегистрирован ли такой тип
     */
    
if (!$this->IsAllowTargetType($sTargetType)) {
        return array();
    }
    if (!
$oTarget->getPropertyIsLoadAll()) {
        
$aProperties $this->oMapper->GetPropertiesValueByTarget($oTarget->property->getPropertyTargetType(),
            
$oTarget->getId());
        
$this->AttachPropertiesForTarget($oTarget$aProperties);
    }
    return 
$oTarget->_getDataOne('property_list');
}

Возвращает список свойств сущности

GetEntityPropertyValue() method
public null|mixed GetEntityPropertyValue(Entity $oTarget, int $sPropertyId)
$oTarget Entity Объект сущности
$sPropertyId int ID свойства
{return} null|mixed
Source Code: /application/classes/modules/property/Property.class.php#300 (show)
public function GetEntityPropertyValue($oTarget$sPropertyId)
{
    if (
$oProperty $this->GetEntityPropertyValueObject($oTarget$sPropertyId)) {
        return 
$oProperty->getValue()->getValueForDisplay();
    }
    return 
null;
}

Возвращает значение свойсва у объекта

GetEntityPropertyValueObject() method
public null GetEntityPropertyValueObject(Entity $oTarget, array $sPropertyId)
$oTarget Entity Объект сущности
$sPropertyId array ID свойства
{return} null
Source Code: /application/classes/modules/property/Property.class.php#373 (show)
public function GetEntityPropertyValueObject($oTarget$sPropertyId)
{
    if (!
$oTarget->getPropertyIsLoadAll()) {
        
/**
         * Загружаем все свойства
         */
        
$aProperties $this->oMapper->GetPropertiesValueByTarget($oTarget->property->getPropertyTargetType(),
            
$oTarget->getId());
        
$this->AttachPropertiesForTarget($oTarget$aProperties);
    }

    if (!
is_numeric($sPropertyId)) {
        
$aMapperCode $oTarget->getPropertyMapperCode();
        if (isset(
$aMapperCode[$sPropertyId])) {
            
$sPropertyId $aMapperCode[$sPropertyId];
        } else {
            return 
null;
        }
    }
    
$aProperties $oTarget->property->getPropertyList();
    if (isset(
$aProperties[$sPropertyId])) {
        return 
$aProperties[$sPropertyId];
    }
    return 
null;
}

Возвращает объект свойства

GetPropertiesForUpdate() method
public mixed GetPropertiesForUpdate($sTargetType $sTargetType, $iTargetId $iTargetId)
$sTargetType $sTargetType
$iTargetId $iTargetId
{return} mixed
Source Code: /application/classes/modules/property/Property.class.php#812 (show)
public function GetPropertiesForUpdate($sTargetType$iTargetId)
{
    
/**
     * Проверяем зарегистрирован ли такой тип
     */
    
if (!$this->IsAllowTargetType($sTargetType)) {
        return array();
    }
    
/**
     * Получаем набор свойств
     */
    
$aProperties $this->Property_GetPropertyItemsByFilter(array(
            
'target_type' => $sTargetType,
            
'#order'      => array('sort' => 'desc')
        ));
    
$this->Property_AttachValueForProperties($aProperties$sTargetType$iTargetId);
    return 
$aProperties;
}

Возвращает набор полей/свойств для показа их на форме редактирования

GetPropertyTagsByLike() method
public mixed GetPropertyTagsByLike(string $sTag, int $iPropertyId, int $iLimit)
$sTag string
$iPropertyId int
$iLimit int
{return} mixed
Source Code: /application/classes/modules/property/Property.class.php#680 (show)
public function GetPropertyTagsByLike($sTag$iPropertyId$iLimit)
{
    return 
$this->oMapper->GetPropertyTagsByLike($sTag$iPropertyId$iLimit);
}

Возвращает список тегов/знаяений свойства. Используется для авкомплиттера тегов.

GetPropertyTagsCloud() method
public mixed GetPropertyTagsCloud(int $iPropertyId, int $iLimit)
$iPropertyId int
$iLimit int
{return} mixed
Source Code: /application/classes/modules/property/Property.class.php#706 (show)
public function GetPropertyTagsCloud($iPropertyId$iLimit)
{
    
$aTags $this->Property_GetPropertyTagsGroup($iPropertyId$iLimit);
    if (
$aTags) {
        
$this->Tools_MakeCloud($aTags);
    }
    return 
$aTags;
}

Формирует и возвращает облако тегов необходимого свойства

GetPropertyTagsGroup() method
public mixed GetPropertyTagsGroup(int $iPropertyId, int $iLimit)
$iPropertyId int
$iLimit int
{return} mixed
Source Code: /application/classes/modules/property/Property.class.php#693 (show)
public function GetPropertyTagsGroup($iPropertyId$iLimit)
{
    return 
$this->oMapper->GetPropertyTagsGroup($iPropertyId$iLimit);
}

Возвращет список группированных тегов с их количеством для необходимого свойства

GetTargetTypeParams() method
public mixed GetTargetTypeParams(string $sTargetType)
$sTargetType string
{return} mixed
Source Code: /application/classes/modules/property/Property.class.php#138 (show)
public function GetTargetTypeParams($sTargetType)
{
    if (
$this->IsAllowTargetType($sTargetType)) {
        return 
$this->aTargetTypes[$sTargetType];
    }
}

Возвращает парметры нужного типа

GetTargetTypes() method
public array GetTargetTypes()
{return} array
Source Code: /application/classes/modules/property/Property.class.php#99 (show)
public function GetTargetTypes()
{
    return 
$this->aTargetTypes;
}

Возвращает список типов объектов

GetTargetsByTag() method
public array GetTargetsByTag(int $iPropertyId, string $sTag, int $iCurrPage, int $iPerPage)
$iPropertyId int
$sTag string
$iCurrPage int
$iPerPage int
{return} array
Source Code: /application/classes/modules/property/Property.class.php#725 (show)
public function GetTargetsByTag($iPropertyId$sTag$iCurrPage$iPerPage)
{
    return array(
        
'collection' => $this->oMapper->GetTargetsByTag($iPropertyId$sTag$iCount$iCurrPage$iPerPage),
        
'count'      => $iCount
    
);
}

Список ID сущностей по тегу конкретного свойства

Init() method
public void Init()
Source Code: /application/classes/modules/property/Property.class.php#79 (show)
public function Init()
{
    
parent::Init();
    
$this->oMapper Engine::GetMapper(__CLASS__);

    
/**
     * Получаем типы из БД и активируем их
     */
    
if ($aTargetItems $this->GetTargetItemsByFilter(array('state' => self::TARGET_STATE_ACTIVE))) {
        foreach (
$aTargetItems as $oTarget) {
            
$this->Property_AddTargetType($oTarget->getType(), $oTarget->getParams());
        }
    }
}

IsAllowPropertyType() method
public bool IsAllowPropertyType(string $sType)
$sType string
{return} bool
Source Code: /application/classes/modules/property/Property.class.php#152 (show)
public function IsAllowPropertyType($sType)
{
    return 
in_array($sType$this->aPropertyTypes);
}

Проверяет разрешен ли тип поля

IsAllowTargetType() method
public bool IsAllowTargetType(string $sTargetType)
$sTargetType string Тип
{return} bool
Source Code: /application/classes/modules/property/Property.class.php#126 (show)
public function IsAllowTargetType($sTargetType)
{
    return 
in_array($sTargetTypearray_keys($this->aTargetTypes));
}

Проверяет разрешен ли данный тип

RemovePropertiesValue() method
public void RemovePropertiesValue(Entity $oTarget)
$oTarget Entity
Source Code: /application/classes/modules/property/Property.class.php#229 (show)
public function RemovePropertiesValue($oTarget)
{
    
$aProperties $this->Property_GetPropertyItemsByFilter(array('target_type' => $oTarget->property->getPropertyTargetType()));
    if (
$aProperties) {
        
$this->AttachValueForProperties($aProperties$oTarget->property->getPropertyTargetType(),
            
$oTarget->getId());
        foreach (
$aProperties as $oProperty) {
            
$oValue $oProperty->getValue();
            if (
$oValue and $oValue->getId()) {
                
$oValueType $oValue->getValueTypeObject();
                
/**
                 * Кастомное удаление
                 */
                
$oValueType->removeValue();
                
/**
                 * Удаляем основные данные
                 */
                
$oValue->Delete();
            }
        }
    }
}

Удаление всех свойств у конкретного объекта/сущности

RemoveSelectByPropertyId() method
public void RemoveSelectByPropertyId($iPropertyId)
$iPropertyId
Source Code: /application/classes/modules/property/Property.class.php#944 (show)
public function RemoveSelectByPropertyId($iPropertyId)
{
    
$bRes $this->oMapper->RemoveSelectByPropertyId($iPropertyId);
    
$this->Cache_Clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG, array('ModuleProperty_EntitySelect_delete'));
    return 
$bRes;
}

RemoveTargetType() method
public void RemoveTargetType(string $sType, int $iState=2)
$sType string
$iState int self::TARGET_STATE_NOT_ACTIVE или self::TARGET_STATE_REMOVE
Source Code: /application/classes/modules/property/Property.class.php#796 (show)
public function RemoveTargetType($sType$iState self::TARGET_STATE_NOT_ACTIVE)
{
    if (
$oTarget $this->GetTargetByType($sType)) {
        
$oTarget->setState($iState);
        
$oTarget->Save();
    }
}

Отключает тип объекта для дополнительных полей

RemoveValueByPropertyId() method
public void RemoveValueByPropertyId($iPropertyId)
$iPropertyId
Source Code: /application/classes/modules/property/Property.class.php#923 (show)
public function RemoveValueByPropertyId($iPropertyId)
{
    
$bRes $this->oMapper->RemoveValueByPropertyId($iPropertyId);
    
$this->Cache_Clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG, array('ModuleProperty_EntityValue_delete'));
    return 
$bRes;
}

RemoveValueSelectByPropertyId() method
public void RemoveValueSelectByPropertyId($iPropertyId)
$iPropertyId
Source Code: /application/classes/modules/property/Property.class.php#937 (show)
public function RemoveValueSelectByPropertyId($iPropertyId)
{
    
$bRes $this->oMapper->RemoveValueSelectByPropertyId($iPropertyId);
    
$this->Cache_Clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG, array('ModuleProperty_EntityValueSelect_delete'));
    return 
$bRes;
}

RemoveValueSelectsByTarget() method
public mixed RemoveValueSelectsByTarget(string $sTargetType, int $iTargetId, int $iPropertyId)
$sTargetType string Тип объекта сущности
$iTargetId int ID объекта сущности
$iPropertyId int ID свойства
{return} mixed
Source Code: /application/classes/modules/property/Property.class.php#664 (show)
public function RemoveValueSelectsByTarget($sTargetType$iTargetId$iPropertyId)
{
    
// сбрасываем кеш
    
$this->Cache_Clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG, array('ModuleProperty_EntityValueSelect_delete'));
    return 
$this->oMapper->RemoveValueSelectsByTarget($sTargetType$iTargetId$iPropertyId);
}

Удаляет значения типа select

RemoveValueTagByPropertyId() method
public void RemoveValueTagByPropertyId($iPropertyId)
$iPropertyId
Source Code: /application/classes/modules/property/Property.class.php#930 (show)
public function RemoveValueTagByPropertyId($iPropertyId)
{
    
$bRes $this->oMapper->RemoveValueTagByPropertyId($iPropertyId);
    
$this->Cache_Clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG, array('ModuleProperty_EntityValueTag_delete'));
    return 
$bRes;
}

RemoveValueTagsByTarget() method
public mixed RemoveValueTagsByTarget(string $sTargetType, int $iTargetId, int $iPropertyId)
$sTargetType string Тип объекта сущности
$iTargetId int ID объекта сущности
$iPropertyId int ID свойства
{return} mixed
Source Code: /application/classes/modules/property/Property.class.php#648 (show)
public function RemoveValueTagsByTarget($sTargetType$iTargetId$iPropertyId)
{
    
// сбрасываем кеш
    
$this->Cache_Clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG, array('ModuleProperty_EntityValueTag_delete'));
    return 
$this->oMapper->RemoveValueTagsByTarget($sTargetType$iTargetId$iPropertyId);
}

Удаляет теги свойства у сущности

RewriteFilter() method
public array RewriteFilter(array $aFilter, array $sEntityFull)
$aFilter array
$sEntityFull array
{return} array
Source Code: /application/classes/modules/property/Property.class.php#517 (show)
public function RewriteFilter($aFilter$sEntityFull)
{
    
$oEntitySample Engine::GetEntity($sEntityFull);
    if (!
$oEntitySample->property) {
        return 
$aFilter;
    }

    if (!isset(
$aFilter['#join'])) {
        
$aFilter['#join'] = array();
    }
    
$aPropFields = array();
    foreach (
$aFilter as $k => $v) {
        if (
preg_match('@^#prop:(.+)$@i'$k$aMatch)) {
            
/**
             * Сначала формируем список полей с операндами
             */
            
$aK explode(' 'trim($aMatch[1]), 2);
            
$sPropCurrent $aK[0];
            
$sConditionCurrent ' = ';
            if (
count($aK) > 1) {
                
$sConditionCurrent strtolower($aK[1]);
            }
            
$aPropFields[$sPropCurrent] = array('value' => $v'condition' => $sConditionCurrent);
        }
    }
    
/**
     * Проверяем на наличие сортировки по полям
     */
    
$aOrders = array();
    if (isset(
$aFilter['#order'])) {
        if (!
is_array($aFilter['#order'])) {
            
$aFilter['#order'] = array($aFilter['#order']);
        }
        foreach (
$aFilter['#order'] as $key => $value) {
            
$aKeys explode(':'$key);
            if (
count($aKeys) == and strtolower($aKeys[0]) == 'prop') {
                
$aOrders[$aKeys[1]] = array('way' => $value'replace' => $key);
            }
        }
    }
    
/**
     * Получаем данные по полям
     */
    
if ($aPropFields) {
        
$sTargetType $oEntitySample->property->getPropertyTargetType();
        
$aProperties $this->Property_GetPropertyItemsByFilter(array(
                
'code in'     => array_keys($aPropFields),
                
'target_type' => $sTargetType
            
));
        
$iPropNum 0;
        foreach (
$aProperties as $oProperty) {
            
/**
             * По каждому полю строим JOIN запрос
             */
            
$sCondition $aPropFields[$oProperty->getCode()]['condition'];
            
$bIsArray in_array(strtolower($sCondition), array('in''not in')) ? true false;
            if (
in_array($oProperty->getType(),
                array(
ModuleProperty::PROPERTY_TYPE_INTModuleProperty::PROPERTY_TYPE_CHECKBOX))) {
                
$sFieldValue "value_int";
                
$sConditionFull $sCondition . ($bIsArray ' (?a) ' ' ?d ');
            } elseif (
$oProperty->getType() == ModuleProperty::PROPERTY_TYPE_FLOAT) {
                
$sFieldValue "value_float";
                
$sConditionFull $sCondition . ($bIsArray ' (?a) ' ' ?f ');
            } elseif (
in_array($oProperty->getType(), array(
                    
ModuleProperty::PROPERTY_TYPE_VARCHAR,
                    
ModuleProperty::PROPERTY_TYPE_TAGS,
                    
ModuleProperty::PROPERTY_TYPE_VIDEO_LINK
                
))) {
                
$sFieldValue "value_varchar";
                
$sConditionFull $sCondition . ($bIsArray ' (?a) ' ' ? ');
            } elseif (
$oProperty->getType() == ModuleProperty::PROPERTY_TYPE_TEXT) {
                
$sFieldValue "value_text";
                
$sConditionFull $sCondition . ($bIsArray ' (?a) ' ' ? ');
            } else {
                
$sFieldValue "value_varchar";
                
$sConditionFull $sCondition . ($bIsArray ' (?a) ' ' ? ');
            }
            
$iPropNum++;
            
$sJoin "JOIN " Config::Get('db.table.property_value') . " propv{$iPropNum} ON
                t.`
{$oEntitySample->_getPrimaryKey()}` = propv{$iPropNum}.target_id and
                propv
{$iPropNum}.target_type = '{$sTargetType}' and
                propv
{$iPropNum}.property_id = {$oProperty->getId()} and
                propv
{$iPropNum}.{$sFieldValue} {$sConditionFull}";
            
$aFilter['#join'][$sJoin] = array($aPropFields[$oProperty->getCode()]['value']);
            
/**
             * Проверяем на сортировку по текущему полю
             */
            
if (isset($aOrders[$oProperty->getCode()])) {
                
$aOrders[$oProperty->getCode()]['field'] = "propv{$iPropNum}.{$sFieldValue}";
            }
        }
    }
    
/**
     * Подменяем сортировку
     */
    
foreach ($aOrders as $aItem) {
        if (isset(
$aFilter['#order'][$aItem['replace']])) {
            
$aFilter['#order'] = $this->ArrayReplaceKey($aFilter['#order'], $aItem['replace'], $aItem['field']);
        }
    }
    return 
$aFilter;
}

Обработка фильтра ORM запросов

RewriteGetItemsByFilter() method
public void RewriteGetItemsByFilter(array $aResult, array $aFilter=array ( ), null|string $sEntityFull=NULL)
$aResult array
$aFilter array
$sEntityFull null|string
Source Code: /application/classes/modules/property/Property.class.php#406 (show)
public function RewriteGetItemsByFilter($aResult$aFilter = array(), $sEntityFull null)
{
    if (!
$aResult) {
        return;
    }
    
/**
     * Список на входе может быть двух видом:
     * 1 - одномерный массив
     * 2 - двумерный, если применялась группировка (использование '#index-group')
     *
     * Поэтому сначала сформируем линейный список
     */
    
if (isset($aFilter['#index-group']) and $aFilter['#index-group']) {
        
$aEntitiesWork = array();
        foreach (
$aResult as $aItems) {
            foreach (
$aItems as $oItem) {
                
$aEntitiesWork[] = $oItem;
            }
        }
    } else {
        
$aEntitiesWork $aResult;
    }

    if (!
$aEntitiesWork) {
        return;
    }
    
$oEntityFirst reset($aEntitiesWork);
    if (!
$oEntityFirst->property) {
        return;
    }
    
$sTargetType $oEntityFirst->property->getPropertyTargetType();
    
/**
     * Проверяем зарегистрирован ли такой тип
     */
    
if (!$this->IsAllowTargetType($sTargetType)) {
        return;
    }
    
/**
     * Проверяем необходимость цеплять свойства
     */
    
if (isset($aFilter['#properties']) and $aFilter['#properties']) {
        
$aEntitiesId = array();
        foreach (
$aEntitiesWork as $oEntity) {
            
$aEntitiesId[] = $oEntity->getId();
        }
        
/**
         * Получаем все свойства со значениями для всех объектов
         */
        
$aResult $this->oMapper->GetPropertiesValueByTargetArray($sTargetType$aEntitiesId);
        if (
$aResult) {
            
/**
             * Формируем список свойств и значений
             */
            
$aProperties = array();
            
$aValues = array();
            foreach (
$aResult as $aRow) {
                
$aPropertyData = array();
                
$aValueData = array();
                foreach (
$aRow as $k => $v) {
                    if (
strpos($k'prop_') === 0) {
                        
$aPropertyData[str_replace('prop_'''$k)] = $v;
                    } else {
                        
$aValueData[$k] = $v;
                    }
                }

                if (!isset(
$aProperties[$aRow['prop_id']])) {
                    
$oProperty Engine::GetEntity('ModuleProperty_EntityProperty'$aPropertyData);
                    
$aProperties[$aRow['prop_id']] = $oProperty;
                }
                if (
$aRow['target_id']) {
                    
$sKey $aRow['property_id'] . '_' $aRow['target_id'];
                    
$aValues[$sKey] = Engine::GetEntity('ModuleProperty_EntityValue'$aValueData);
                }
            }
            
/**
             * Собираем данные
             */
            
foreach ($aEntitiesWork as $oEntity) {
                
$aPropertiesClone = array();
                foreach (
$aProperties as $oProperty) {
                    
$oPropertyNew = clone $oProperty;
                    
$sKey $oProperty->getId() . '_' $oEntity->getId();
                    if (isset(
$aValues[$sKey])) {
                        
$oValue $aValues[$sKey];
                    } else {
                        
$oValue Engine::GetEntity('ModuleProperty_EntityValue', array(
                                
'property_type' => $oProperty->getType(),
                                
'property_id'   => $oProperty->getId(),
                                
'target_type'   => $oProperty->getTargetType(),
                                
'target_id'     => $oEntity->getId()
                            ));
                    }
                    
$oPropertyNew->setValue($oValue);
                    
$oValue->setProperty($oPropertyNew);
                    
$aPropertiesClone[$oPropertyNew->getId()] = $oPropertyNew;
                }
                
$this->AttachPropertiesForTarget($oEntity$aPropertiesClone);
            }
        }
    }
}

Переопределяем метод для возможности цеплять свои кастомные данные при ORM запросах - свойства

UpdatePropertiesValue() method
public void UpdatePropertiesValue(array $aProperties, Entity|int $oTarget)
$aProperties array
$oTarget Entity|int Объект сущности или ID сущности
Source Code: /application/classes/modules/property/Property.class.php#212 (show)
public function UpdatePropertiesValue($aProperties$oTarget)
{
    if (
$aProperties) {
        foreach (
$aProperties as $oProperty) {
            
$oValue $oProperty->getValue();
            
$oValue->setTargetId(is_object($oTarget) ? $oTarget->getId() : $oTarget);
            
$oValue->setPropertyType($oProperty->getType());
            
$oValue->Save();
        }
    }
}

Сохраняет текущие значения свойств

ValidateEntityPropertiesCheck() method
public bool|string ValidateEntityPropertiesCheck(Entity $oTarget)
$oTarget Entity
{return} bool|string
Source Code: /application/classes/modules/property/Property.class.php#259 (show)
public function ValidateEntityPropertiesCheck($oTarget)
{
    
/**
     * Пробуем получить свойства из реквеста
     */
    
$oTarget->setProperties($oTarget->getProperties() ? $oTarget->getProperties() : getRequest('property'));
    
$aPropertiesValue $oTarget->getProperties();
    
$aPropertiesResult = array();
    
/**
     * Получаем весь список свойств у объекта
     */
    
$aPropertiesObject $this->Property_GetPropertyItemsByFilter(array('target_type' => $oTarget->property->getPropertyTargetType()));
    
$this->Property_AttachValueForProperties($aPropertiesObject$oTarget->property->getPropertyTargetType(),
        
$oTarget->getId());
    foreach (
$aPropertiesObject as $oProperty) {
        
$oValue $oProperty->getValue();
        
$sValue = isset($aPropertiesValue[$oProperty->getId()]) ? $aPropertiesValue[$oProperty->getId()] : null;
        
/**
         * Валидируем значение
         */
        
$oValueType $oValue->getValueTypeObject();
        
$oValueType->setValueForValidate($sValue);
        if (
true === ($sRes $oValueType->validate())) {
            
$oValueType->setValue($oValueType->getValueForValidate());
            
$aPropertiesResult[$oProperty->getId()] = $oProperty;
        } else {
            return 
$sRes $sRes 'Неверное значение аттрибута: ' $oProperty->getTitle();
        }
    }
    
$oTarget->setPropertiesObject($aPropertiesResult);
    return 
true;
}

Валидирует значение свойств у объекта