/**
  * Возвращает имя таблицы для сущности
  *
  * @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
 public function __call($sName, $aArgs)
 {
     if (preg_match("@^add([\\w]+)\$@i", $sName, $aMatch)) {
         return $this->_AddEntity($aArgs[0]);
     }
     if (preg_match("@^update([\\w]+)\$@i", $sName, $aMatch)) {
         return $this->_UpdateEntity($aArgs[0]);
     }
     if (preg_match("@^save([\\w]+)\$@i", $sName, $aMatch)) {
         return $this->_SaveEntity($aArgs[0]);
     }
     if (preg_match("@^delete([\\w]+)\$@i", $sName, $aMatch)) {
         return $this->_DeleteEntity($aArgs[0]);
     }
     if (preg_match("@^reload([\\w]+)\$@i", $sName, $aMatch)) {
         return $this->_ReloadEntity($aArgs[0]);
     }
     if (preg_match("@^showcolumnsfrom([\\w]+)\$@i", $sName, $aMatch)) {
         return $this->_ShowColumnsFrom($aArgs[0]);
     }
     if (preg_match("@^showprimaryindexfrom([\\w]+)\$@i", $sName, $aMatch)) {
         return $this->_ShowPrimaryIndexFrom($aArgs[0]);
     }
     if (preg_match("@^getchildrenof([\\w]+)\$@i", $sName, $aMatch)) {
         return $this->_GetChildrenOfEntity($aArgs[0]);
     }
     if (preg_match("@^getparentof([\\w]+)\$@i", $sName, $aMatch)) {
         return $this->_GetParentOfEntity($aArgs[0]);
     }
     if (preg_match("@^getdescendantsof([\\w]+)\$@i", $sName, $aMatch)) {
         return $this->_GetDescendantsOfEntity($aArgs[0]);
     }
     if (preg_match("@^getancestorsof([\\w]+)\$@i", $sName, $aMatch)) {
         return $this->_GetAncestorsOfEntity($aArgs[0]);
     }
     if (preg_match("@^loadtreeof([\\w]+)\$@i", $sName, $aMatch)) {
         $sEntityFull = array_key_exists(1, $aMatch) ? $aMatch[1] : null;
         return $this->LoadTree($aArgs[0], $sEntityFull);
     }
     $sNameUnderscore = func_underscore($sName);
     $iEntityPosEnd = 0;
     if (strpos($sNameUnderscore, '_items') >= 3) {
         $iEntityPosEnd = strpos($sNameUnderscore, '_items');
     } else {
         if (strpos($sNameUnderscore, '_by') >= 3) {
             $iEntityPosEnd = strpos($sNameUnderscore, '_by');
         } else {
             if (strpos($sNameUnderscore, '_all') >= 3) {
                 $iEntityPosEnd = strpos($sNameUnderscore, '_all');
             }
         }
     }
     if ($iEntityPosEnd && $iEntityPosEnd > 4) {
         $sEntityName = substr($sNameUnderscore, 4, $iEntityPosEnd - 4);
     } else {
         $sEntityName = func_underscore(Engine::GetModuleName($this)) . '_';
         $sNameUnderscore = substr_replace($sNameUnderscore, $sEntityName, 4, 0);
         $iEntityPosEnd = strlen($sEntityName) - 1 + 4;
     }
     $sNameUnderscore = substr_replace($sNameUnderscore, str_replace('_', '', $sEntityName), 4, $iEntityPosEnd - 4);
     $sEntityName = func_camelize($sEntityName);
     /**
      * getUserItemsByFilter() get_user_items_by_filter
      */
     if (preg_match("@^get_([a-z]+)((_items)|())_by_filter\$@i", $sNameUnderscore, $aMatch)) {
         if ($aMatch[2] == '_items') {
             return $this->GetItemsByFilter($aArgs[0], $sEntityName);
         } else {
             return $this->GetByFilter($aArgs[0], $sEntityName);
         }
     }
     /**
      * getUserItemsByArrayId() get_user_items_by_array_id
      */
     if (preg_match("@^get_([a-z]+)_items_by_array_([_a-z]+)\$@i", $sNameUnderscore, $aMatch)) {
         return $this->GetItemsByArray(array($aMatch[2] => $aArgs[0]), $sEntityName);
     }
     /**
      * getUserItemsByJoinTable() get_user_items_by_join_table
      */
     if (preg_match("@^get_([a-z]+)_items_by_join_table\$@i", $sNameUnderscore, $aMatch)) {
         return $this->GetItemsByJoinTable($aArgs[0], func_camelize($sEntityName));
     }
     /**
      * getUserByLogin()					get_user_by_login
      * getUserByLoginAndMail()			get_user_by_login_and_mail
      * getUserItemsByName()				get_user_items_by_name
      * getUserItemsByNameAndActive()	get_user_items_by_name_and_active
      * getUserItemsByDateRegisterGte()	get_user_items_by_date_register_gte		(>=)
      * getUserItemsByProfileNameLike()	get_user_items_by_profile_name_like
      * getUserItemsByCityIdIn()			get_user_items_by_city_id_in
      */
     if (preg_match("@^get_([a-z]+)((_items)|())_by_([_a-z]+)\$@i", $sNameUnderscore, $aMatch)) {
         $aAliases = array('_gte' => ' >=', '_lte' => ' <=', '_gt' => ' >', '_lt' => ' <', '_like' => ' LIKE', '_in' => ' IN');
         $sSearchParams = str_replace(array_keys($aAliases), array_values($aAliases), $aMatch[5]);
         $aSearchParams = explode('_and_', $sSearchParams);
         $aSplit = array_chunk($aArgs, count($aSearchParams));
         $aFilter = array_combine($aSearchParams, $aSplit[0]);
         if (isset($aSplit[1][0])) {
             $aFilter = array_merge($aFilter, $aSplit[1][0]);
         }
         if ($aMatch[2] == '_items') {
             return $this->GetItemsByFilter($aFilter, $sEntityName);
         } else {
             return $this->GetByFilter($aFilter, $sEntityName);
         }
     }
     /**
      * getUserAll()			get_user_all 		OR
      * getUserItemsAll()	get_user_items_all
      */
     if (preg_match("@^get_([a-z]+)_all\$@i", $sNameUnderscore, $aMatch) || preg_match("@^get_([a-z]+)_items_all\$@i", $sNameUnderscore, $aMatch)) {
         $aFilter = array();
         if (isset($aArgs[0]) and is_array($aArgs[0])) {
             $aFilter = $aArgs[0];
         }
         return $this->GetItemsByFilter($aFilter, $sEntityName);
     }
     return $this->oEngine->_CallModule($sName, $aArgs);
 }
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;
     }
 }