/**
  * Возвращает имя таблицы для сущности
  *
  * @param EntityORM $oEntity Объект сущности
  * @return string
  */
 public static function GetTableName($oEntity)
 {
     /**
      * Варианты таблиц:
      *    prefix_user -> если модуль совпадает с сущностью
      *    prefix_user_invite -> если модуль не сопадает с сущностью
      * Если сущность плагина:
      *    prefix_pluginname_user
      *    prefix_pluginname_user_invite
      */
     $sClass = Engine::getInstance()->Plugin_GetDelegater('entity', is_object($oEntity) ? get_class($oEntity) : $oEntity);
     $sPluginName = func_underscore(Engine::GetPluginName($sClass));
     $sModuleName = func_underscore(Engine::GetModuleName($sClass));
     $sEntityName = func_underscore(Engine::GetEntityName($sClass));
     if (strpos($sEntityName, $sModuleName) === 0) {
         $sTable = func_underscore($sEntityName);
     } else {
         $sTable = func_underscore($sModuleName) . '_' . func_underscore($sEntityName);
     }
     if ($sPluginName) {
         $sTable = $sPluginName . '_' . $sTable;
     }
     /**
      * Если название таблиц переопределено в конфиге, то возвращаем его
      */
     if (Config::Get('db.table.' . $sTable)) {
         return Config::Get('db.table.' . $sTable);
     } else {
         return Config::Get('db.table.prefix') . $sTable;
     }
 }
 /**
  * Приводит название сущности к единому формату полного имени класса
  * Если используется наследование, то возвращается корневой класс
  * $sEntity может содержать как короткое имя сущности (без плагина и модуля), так и полное
  *
  * @param string|object|null $sEntity
  *
  * @return string
  */
 protected function _NormalizeEntityRootName($sEntity)
 {
     /**
      * Если передан объект сущности, то просто возвращаем ее корневой класс
      */
     if (is_object($sEntity)) {
         return $this->Plugin_GetRootDelegater('entity', get_class($sEntity));
     }
     /**
      * Разбиваем сущность на составляющие
      */
     if (is_null($sEntity)) {
         $sPluginPrefix = Engine::GetPluginPrefix($this);
         $sModuleName = Engine::GetModuleName($this);
         $sEntityName = Engine::GetEntityName($this) ?: $sModuleName;
     } elseif (substr_count($sEntity, '_')) {
         $sPluginPrefix = Engine::GetPluginPrefix($sEntity);
         $sModuleName = Engine::GetModuleName($sEntity);
         $sEntityName = Engine::GetEntityName($sEntity);
     } else {
         $sPluginPrefix = Engine::GetPluginPrefix($this);
         $sModuleName = Engine::GetModuleName($this);
         $sEntityName = $sEntity;
     }
     /**
      * Получаем корневой модуль
      */
     $sModuleRoot = $this->Plugin_GetRootDelegater('module', $sPluginPrefix . 'Module' . $sModuleName);
     /**
      * Возвращаем корневую сущность
      */
     return $this->Plugin_GetRootDelegater('entity', $sModuleRoot . '_Entity' . $sEntityName);
 }
Exemplo n.º 3
0
 /**
  * Вызов методов сущности
  *
  * @param unknown_type $sName
  * @param unknown_type $aArgs
  * @return unknown
  */
 public function __call($sName, $aArgs)
 {
     $sType = substr($sName, 0, strpos(func_underscore($sName), '_'));
     if (!strpos($sName, '_') and in_array($sType, array('get', 'set', 'reload'))) {
         $sKey = func_underscore(preg_replace('/' . $sType . '/', '', $sName, 1));
         if ($sType == 'get') {
             if (isset($this->_aData[$sKey])) {
                 return $this->_aData[$sKey];
             } else {
                 $sField = $this->_getField($sKey);
                 if ($sField != $sKey && isset($this->_aData[$sField])) {
                     return $this->_aData[$sField];
                 }
             }
             /**
              * Проверяем на связи
              */
             if (array_key_exists($sKey, $this->aRelations)) {
                 $sEntityRel = $this->aRelations[$sKey][1];
                 $sRelationType = $this->aRelations[$sKey][0];
                 $sRelationKey = $this->aRelations[$sKey][2];
                 $sRelationJoinTable = null;
                 $sRelationJoinTableKey = 0;
                 // foreign key в join-таблице для текущей сущности
                 if ($sRelationType == self::RELATION_TYPE_MANY_TO_MANY && array_key_exists(3, $this->aRelations[$sKey])) {
                     $sRelationJoinTable = $this->aRelations[$sKey][3];
                     $sRelationJoinTableKey = isset($this->aRelations[$sKey][4]) ? $this->aRelations[$sKey][4] : $this->_getPrimaryKey();
                 }
                 /**
                  * Если связь уже загруженна, то возвращаем сразу результат
                  */
                 if (array_key_exists($sKey, $this->aRelationsData)) {
                     return $this->aRelationsData[$sKey];
                 }
                 $sRelModuleName = Engine::GetModuleName($sEntityRel);
                 $sRelEntityName = Engine::GetEntityName($sEntityRel);
                 $sRelPluginPrefix = Engine::GetPluginPrefix($sEntityRel);
                 $sRelPrimaryKey = 'id';
                 if ($oRelEntity = Engine::GetEntity($sEntityRel)) {
                     $sRelPrimaryKey = $oRelEntity->_getPrimaryKey();
                 }
                 $iPrimaryKeyValue = $this->_getDataOne($this->_getPrimaryKey());
                 $sCmd = '';
                 $mCmdArgs = array();
                 switch ($sRelationType) {
                     case self::RELATION_TYPE_BELONGS_TO:
                         $sCmd = "{$sRelPluginPrefix}{$sRelModuleName}_get{$sRelEntityName}By" . func_camelize($sRelPrimaryKey);
                         $mCmdArgs = $this->_getDataOne($sRelationKey);
                         break;
                     case self::RELATION_TYPE_HAS_ONE:
                         $sCmd = "{$sRelPluginPrefix}{$sRelModuleName}_get{$sRelEntityName}By" . func_camelize($sRelationKey);
                         $mCmdArgs = $iPrimaryKeyValue;
                         break;
                     case self::RELATION_TYPE_HAS_MANY:
                         $sCmd = "{$sRelPluginPrefix}{$sRelModuleName}_get{$sRelEntityName}ItemsByFilter";
                         $mCmdArgs = array($sRelationKey => $iPrimaryKeyValue);
                         break;
                     case self::RELATION_TYPE_MANY_TO_MANY:
                         $sCmd = "{$sRelPluginPrefix}Module{$sRelModuleName}_get{$sRelEntityName}ItemsByJoinTable";
                         $mCmdArgs = array('#join_table' => Config::Get($sRelationJoinTable), '#relation_key' => $sRelationKey, '#by_key' => $sRelationJoinTableKey, '#by_value' => $iPrimaryKeyValue, '#index-from-primary' => true);
                         break;
                     default:
                         break;
                 }
                 // Нужно ли учитывать дополнительный фильтр
                 $bUseFilter = is_array($mCmdArgs) && array_key_exists(0, $aArgs) && is_array($aArgs[0]);
                 if ($bUseFilter) {
                     $mCmdArgs = array_merge($mCmdArgs, $aArgs[0]);
                 }
                 $res = Engine::GetInstance()->_CallModule($sCmd, array($mCmdArgs));
                 // Сохраняем данные только в случае "чистой" выборки
                 if (!$bUseFilter) {
                     $this->aRelationsData[$sKey] = $res;
                 }
                 // Создаём объекты-обёртки для связей MANY_TO_MANY
                 if ($sRelationType == self::RELATION_TYPE_MANY_TO_MANY) {
                     $this->_aManyToManyRelations[$sKey] = new LS_ManyToManyRelation($res);
                 }
                 return $res;
             }
             return null;
         } elseif ($sType == 'set' and array_key_exists(0, $aArgs)) {
             if (array_key_exists($sKey, $this->aRelations)) {
                 $this->aRelationsData[$sKey] = $aArgs[0];
             } else {
                 $this->_aData[$this->_getField($sKey)] = $aArgs[0];
             }
         } elseif ($sType == 'reload') {
             if (array_key_exists($sKey, $this->aRelationsData)) {
                 unset($this->aRelationsData[$sKey]);
                 return $this->__call('get' . func_camelize($sKey), $aArgs);
             }
         }
     } else {
         return Engine::getInstance()->_CallModule($sName, $aArgs);
     }
 }
Exemplo n.º 4
0
 /**
  * Получить список сущностей по фильтру
  *
  * @param unknown_type $aFilter
  * @param unknown_type $sEntityFull
  * @return unknown
  */
 public function GetItemsByFilter($aFilter = array(), $sEntityFull = null)
 {
     if (is_null($aFilter)) {
         $aFilter = array();
     }
     if (is_null($sEntityFull)) {
         $sEntityFull = Engine::GetPluginPrefix($this) . 'Module' . Engine::GetModuleName($this) . '_Entity' . Engine::GetModuleName(get_class($this));
     } elseif (!substr_count($sEntityFull, '_')) {
         $sEntityFull = Engine::GetPluginPrefix($this) . 'Module' . Engine::GetModuleName($this) . '_Entity' . $sEntityFull;
     }
     // Если параметр #cache указан и пуст, значит игнорируем кэширование для запроса
     if (array_key_exists('#cache', $aFilter) && !$aFilter['#cache']) {
         $aEntities = $this->oMapperORM->GetItemsByFilter($aFilter, $sEntityFull);
     } else {
         $sEntityFullRoot = $this->Plugin_GetRootDelegater('entity', $sEntityFull);
         $sCacheKey = $sEntityFullRoot . '_items_by_filter_' . serialize($aFilter);
         $aCacheTags = array($sEntityFullRoot . '_save', $sEntityFullRoot . '_delete');
         $iCacheTime = 60 * 60 * 24;
         // скорее лучше хранить в свойстве сущности, для возможности выборочного переопределения
         // переопределяем из параметров
         if (isset($aFilter['#cache'][0])) {
             $sCacheKey = $aFilter['#cache'][0];
         }
         if (isset($aFilter['#cache'][1])) {
             $aCacheTags = $aFilter['#cache'][1];
         }
         if (isset($aFilter['#cache'][2])) {
             $iCacheTime = $aFilter['#cache'][2];
         }
         if (false === ($aEntities = $this->Cache_Get($sCacheKey))) {
             $aEntities = $this->oMapperORM->GetItemsByFilter($aFilter, $sEntityFull);
             $this->Cache_Set($aEntities, $sCacheKey, $aCacheTags, $iCacheTime);
         }
     }
     /**
      * Если необходимо подцепить связанные данные
      */
     if (count($aEntities) and isset($aFilter['#with'])) {
         if (!is_array($aFilter['#with'])) {
             $aFilter['#with'] = array($aFilter['#with']);
         }
         $oEntityEmpty = Engine::GetEntity($sEntityFull);
         $aRelations = $oEntityEmpty->_getRelations();
         $aEntityKeys = array();
         foreach ($aFilter['#with'] as $sRelationName) {
             $sRelType = $aRelations[$sRelationName][0];
             $sRelEntity = $this->Plugin_GetRootDelegater('entity', $aRelations[$sRelationName][1]);
             // получаем корневую сущность, без учета наследников
             $sRelKey = $aRelations[$sRelationName][2];
             if (!array_key_exists($sRelationName, $aRelations) or !in_array($sRelType, array(EntityORM::RELATION_TYPE_BELONGS_TO, EntityORM::RELATION_TYPE_HAS_ONE))) {
                 throw new Exception("The entity <{$sEntityFull}> not have relation <{$sRelationName}>");
             }
             /**
              * Формируем список ключей
              */
             foreach ($aEntities as $oEntity) {
                 $aEntityKeys[$sRelKey][] = $oEntity->_getDataOne($sRelKey);
             }
             $aEntityKeys[$sRelKey] = array_unique($aEntityKeys[$sRelKey]);
             /**
              * Делаем общий запрос по всем ключам
              */
             $oRelEntityEmpty = Engine::GetEntity($sRelEntity);
             $sRelModuleName = Engine::GetModuleName($sRelEntity);
             $sRelEntityName = Engine::GetEntityName($sRelEntity);
             $sRelPluginPrefix = Engine::GetPluginPrefix($sRelEntity);
             $sRelPrimaryKey = method_exists($oRelEntityEmpty, '_getPrimaryKey') ? func_camelize($oRelEntityEmpty->_getPrimaryKey()) : 'Id';
             $aRelData = Engine::GetInstance()->_CallModule("{$sRelPluginPrefix}{$sRelModuleName}_get{$sRelEntityName}ItemsByArray{$sRelPrimaryKey}", array($aEntityKeys[$sRelKey]));
             /**
              * Собираем набор
              */
             foreach ($aEntities as $oEntity) {
                 if (isset($aRelData[$oEntity->_getDataOne($sRelKey)])) {
                     $oEntity->_setData(array($sRelationName => $aRelData[$oEntity->_getDataOne($sRelKey)]));
                 }
             }
         }
     }
     /**
      * Returns assotiative array, indexed by PRIMARY KEY or another field.
      */
     if (in_array('#index-from-primary', $aFilter) || !empty($aFilter['#index-from'])) {
         $aEntities = $this->_setIndexesFromField($aEntities, $aFilter);
     }
     /**
      * Если запрашиваем постраничный список, то возвращаем сам список и общее количество записей
      */
     if (isset($aFilter['#page'])) {
         return array('collection' => $aEntities, 'count' => $this->GetCountItemsByFilter($aFilter, $sEntityFull));
     }
     return $aEntities;
 }
Exemplo n.º 5
0
 /**
  * Возвращает имя таблицы для сущности
  *
  * @param unknown_type $oEntity
  * @return unknown
  */
 public static function GetTableName($oEntity)
 {
     /**
      * Варианты таблиц:
      * 	prefix_user -> если модуль совпадает с сущностью
      * 	prefix_user_invite -> если модуль не сопадает с сущностью
      */
     $sModuleName = func_underscore(Engine::GetModuleName($oEntity));
     $sEntityName = func_underscore(Engine::GetEntityName($oEntity));
     if (strpos($sEntityName, $sModuleName) === 0) {
         $sTable = func_underscore($sEntityName);
     } else {
         $sTable = func_underscore($sModuleName) . '_' . func_underscore($sEntityName);
     }
     if (Config::Get('db.table.' . $sTable)) {
         return Config::Get('db.table.' . $sTable);
     } else {
         return Config::Get('db.table.prefix') . $sTable;
     }
 }
 /**
  * Ставим хук на вызов неизвестного метода и считаем что хотели вызвать метод какого либо модуля
  * Также производит обработку методов set* и get*
  * Учитывает связи и может возвращать связанные данные
  * @see Engine::_CallModule
  *
  * @param string $sName Имя метода
  * @param array $aArgs Аргументы
  * @return mixed
  */
 public function __call($sName, $aArgs)
 {
     $sType = substr($sName, 0, strpos(func_underscore($sName), '_'));
     if (!strpos($sName, '_') and in_array($sType, array('get', 'set', 'reload'))) {
         $sKey = func_underscore(preg_replace('/' . $sType . '/', '', $sName, 1));
         if ($sType == 'get') {
             if (isset($this->_aData[$sKey])) {
                 return $this->_aData[$sKey];
             } else {
                 $sField = $this->_getField($sKey);
                 if ($sField != $sKey && isset($this->_aData[$sField])) {
                     return $this->_aData[$sField];
                 }
             }
             /**
              * Проверяем на связи
              */
             $aRelations = $this->_getRelations();
             if (array_key_exists($sKey, $aRelations)) {
                 $sEntityRel = $aRelations[$sKey]['rel_entity'];
                 $sRelationType = $aRelations[$sKey]['type'];
                 $sRelationKey = $aRelations[$sKey]['rel_key'];
                 $sRelModuleName = Engine::GetModuleName($sEntityRel);
                 $sRelEntityName = Engine::GetEntityName($sEntityRel);
                 $sRelPluginPrefix = Engine::GetPluginPrefix($sEntityRel);
                 $sRelPrimaryKey = 'id';
                 if ($oRelEntity = Engine::GetEntity($sEntityRel)) {
                     $sRelPrimaryKey = $oRelEntity->_getPrimaryKey();
                 }
                 $iPrimaryKeyValue = $this->_getDataOne($this->_getPrimaryKey());
                 $bUseFilter = array_key_exists(0, $aArgs) && is_array($aArgs[0]);
                 $sCmd = '';
                 $mCmdArgs = array();
                 switch ($sRelationType) {
                     case self::RELATION_TYPE_BELONGS_TO:
                         $sKeyTo = $aRelations[$sKey]['rel_key_to'] ?: $sRelPrimaryKey;
                         $sCmd = "{$sRelPluginPrefix}{$sRelModuleName}_get{$sRelEntityName}By" . func_camelize($sKeyTo);
                         $mCmdArgs = array($this->_getDataOne($sRelationKey));
                         break;
                     case self::RELATION_TYPE_HAS_ONE:
                         $aFilterAdd = $aRelations[$sKey]['filter'];
                         $sCmd = "{$sRelPluginPrefix}{$sRelModuleName}_get{$sRelEntityName}ByFilter";
                         $aFilterAdd = array_merge(array($sRelationKey => $iPrimaryKeyValue), $aFilterAdd);
                         $mCmdArgs = array($aFilterAdd);
                         break;
                     case self::RELATION_TYPE_HAS_MANY:
                         if ($aRelations[$sKey]['key_from']) {
                             $sRelationKeyValue = $this->_getDataOne($aRelations[$sKey]['key_from']);
                         } else {
                             $sRelationKeyValue = $iPrimaryKeyValue;
                         }
                         $aFilterAdd = $aRelations[$sKey]['filter'];
                         $sCmd = "{$sRelPluginPrefix}{$sRelModuleName}_get{$sRelEntityName}ItemsByFilter";
                         $aFilterAdd = array_merge(array($sRelationKey => $sRelationKeyValue), $aFilterAdd);
                         if ($bUseFilter) {
                             $aFilterAdd = array_merge($aFilterAdd, $aArgs[0]);
                         }
                         $mCmdArgs = array($aFilterAdd);
                         break;
                     case self::RELATION_TYPE_MANY_TO_MANY:
                         $sEntityJoin = $aRelations[$sKey]['join_entity'];
                         $sKeyJoin = $aRelations[$sKey]['join_key'];
                         $aFilterAdd = $aRelations[$sKey]['filter'];
                         $sCmd = "{$sRelPluginPrefix}Module{$sRelModuleName}_get{$sRelEntityName}ItemsByJoinEntity";
                         if ($bUseFilter) {
                             $aFilterAdd = array_merge($aFilterAdd, $aArgs[0]);
                         }
                         $mCmdArgs = array($sEntityJoin, $sKeyJoin, $sRelationKey, $iPrimaryKeyValue, $aFilterAdd);
                         break;
                     default:
                         break;
                 }
                 /**
                  * Если связь уже загруженна, то возвращаем результат
                  */
                 if (!$bUseFilter and array_key_exists($sKey, $this->aRelationsData)) {
                     return $this->aRelationsData[$sKey];
                 }
                 // Нужно ли учитывать дополнительный фильтр
                 $res = Engine::GetInstance()->_CallModule($sCmd, $mCmdArgs);
                 // Сохраняем данные только в случае "чистой" выборки
                 if (!$bUseFilter) {
                     $this->aRelationsData[$sKey] = $res;
                 }
                 // Создаём объекты-обёртки для связей MANY_TO_MANY
                 if ($sRelationType == self::RELATION_TYPE_MANY_TO_MANY) {
                     $this->_aManyToManyRelations[$sKey] = new ORMRelationManyToMany($res);
                 }
                 return $res;
             }
             return null;
         } elseif ($sType == 'set' and array_key_exists(0, $aArgs)) {
             if (array_key_exists($sKey, $this->aRelations)) {
                 $this->aRelationsData[$sKey] = $aArgs[0];
             } else {
                 $this->_aData[$this->_getField($sKey)] = $aArgs[0];
             }
             return $this;
         } elseif ($sType == 'reload') {
             if (array_key_exists($sKey, $this->aRelationsData)) {
                 unset($this->aRelationsData[$sKey]);
                 return $this->__call('get' . func_camelize($sKey), $aArgs);
             }
         }
     } else {
         return parent::__call($sName, $aArgs);
     }
 }
Exemplo n.º 7
0
 /**
  * Возвращает имя таблицы для сущности
  *
  * @param unknown_type $oEntity
  * @return unknown
  */
 public static function GetTableName($oEntity)
 {
     /**
      * Варианты таблиц:
      * 	prefix_user -> если модуль совпадает с сущностью
      * 	prefix_user_invite -> если модуль не сопадает с сущностью
      */
     $sClass = Engine::getInstance()->Plugin_GetDelegater('entity', is_object($oEntity) ? get_class($oEntity) : $oEntity);
     $sModuleName = func_underscore(Engine::GetModuleName($sClass));
     $sEntityName = func_underscore(Engine::GetEntityName($sClass));
     if (strpos($sEntityName, $sModuleName) === 0) {
         $sTable = func_underscore($sEntityName);
     } else {
         $sTable = func_underscore($sModuleName) . '_' . func_underscore($sEntityName);
     }
     if (Config::Get('db.table.' . $sTable)) {
         return Config::Get('db.table.' . $sTable);
     } else {
         return Config::Get('db.table.prefix') . $sTable;
     }
 }