├── src ├── db │ ├── readme.txt │ ├── template │ │ ├── other │ │ │ └── create │ │ │ │ ├── down.txt │ │ │ │ └── up.txt │ │ └── main.txt │ ├── install │ │ └── install.sql │ ├── main │ │ ├── SiteIntegrate.php │ │ ├── LanguageIntegrate.php │ │ └── GroupIntegrate.php │ ├── generator │ │ ├── providers │ │ │ ├── Site.php │ │ │ ├── language.php │ │ │ ├── Group.php │ │ │ ├── Hlblock.php │ │ │ ├── HlblockField.php │ │ │ ├── Iblock.php │ │ │ ├── IblockProperty.php │ │ │ └── IblockType.php │ │ └── Code.php │ ├── iblock │ │ ├── HighloadblockIntegrate.php │ │ ├── IblockTypeIntegrate.php │ │ ├── IblockPropertyIntegrate.php │ │ ├── IblockIntegrate.php │ │ └── HighloadblockFieldIntegrate.php │ └── entity │ │ └── MigrationTable.php ├── config │ ├── bim.json │ └── commands.json ├── Exception │ └── BimException.php ├── Revision.php ├── bin │ └── bim ├── Export │ ├── Dump │ │ └── dump.php │ └── Session.php ├── Migration.php ├── cmd │ ├── StartCommandClass.php~ │ ├── InitCommand.php │ ├── ExportCommand.php │ ├── InfoCommand.php │ ├── ListCommand.php │ ├── DownCommand.php │ ├── UpdateCommand.php │ ├── BaseCommand.php │ └── GenCommand.php └── Util │ ├── Config.php │ └── Helper.php ├── .gitignore ├── composer.json ├── docs ├── index.md~ ├── template.html └── index.md └── README.md /src/db/readme.txt: -------------------------------------------------------------------------------- 1 | Bitrix Migration (BIM) -------------------------------------------------------------------------------- /src/db/template/other/create/down.txt: -------------------------------------------------------------------------------- 1 | // empty down method (use Exception) 2 | -------------------------------------------------------------------------------- /src/db/template/other/create/up.txt: -------------------------------------------------------------------------------- 1 | // empty up method (use Exception) 2 | -------------------------------------------------------------------------------- /src/config/bim.json: -------------------------------------------------------------------------------- 1 | { 2 | "migration_path": "migrations", 3 | "logging_path": "_log/bim", 4 | "migration_table": "bim_migrations" 5 | } -------------------------------------------------------------------------------- /src/db/install/install.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE IF NOT EXISTS `bim_migrations` ( 2 | `id` VARCHAR(255) 3 | COLLATE utf8_unicode_ci NOT NULL 4 | ) 5 | ENGINE = InnoDB 6 | DEFAULT CHARSET = utf8 7 | COLLATE = utf8_unicode_ci -------------------------------------------------------------------------------- /src/Exception/BimException.php: -------------------------------------------------------------------------------- 1 | MakeDump($filename, $state); 23 | } -------------------------------------------------------------------------------- /src/Migration.php: -------------------------------------------------------------------------------- 1 | get("commands")); 23 | # run commands 24 | $console->run(); 25 | } 26 | 27 | } -------------------------------------------------------------------------------- /src/cmd/StartCommandClass.php~: -------------------------------------------------------------------------------- 1 | writeln('Привет это я',Colors::GREEN); 22 | } 23 | 24 | } -------------------------------------------------------------------------------- /src/cmd/InitCommand.php: -------------------------------------------------------------------------------- 1 | padding("Create migrations table : " . $this->color(strtoupper("completed"), 20 | \ConsoleKit\Colors::GREEN)); 21 | } else { 22 | $this->padding("Create migrations table : " . $this->color(strtoupper("already exist"), 23 | \ConsoleKit\Colors::YELLOW)); 24 | } 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/db/template/main.txt: -------------------------------------------------------------------------------- 1 | =1.0.0", 31 | "wp-cli/php-cli-tools": "*", 32 | "alchemy/zippy": ">=0.3.5" 33 | }, 34 | "support": { 35 | "email": "icjp2600@gmail.com", 36 | "docs": "https://github.com/cjp2600/bim-core", 37 | "source": "https://github.com/cjp2600/bim-core" 38 | }, 39 | "autoload": { 40 | "classmap": [ 41 | "src", 42 | "src/db", 43 | "src/db/generator", 44 | "src/db/generator/providers", 45 | "src/db/entity", 46 | "src/db/iblock", 47 | "src/db/main", 48 | "src/cmd", 49 | "src/Util", 50 | "src/Export", 51 | "src/Exception" 52 | ] 53 | }, 54 | "config": { 55 | "bin-dir": "src/bin", 56 | "preferred-install": "dist" 57 | }, 58 | "minimum-stability": "dev" 59 | } 60 | 61 | -------------------------------------------------------------------------------- /src/Util/Config.php: -------------------------------------------------------------------------------- 1 | data = $this->parse($path); 18 | } 19 | 20 | public function get($key, $default = null) { 21 | if (isset($this->cache[$key])) { 22 | return $this->cache[$key]; 23 | } 24 | 25 | $segs = explode('.', $key); 26 | $root = $this->data; 27 | 28 | foreach ($segs as $part) { 29 | if (isset($root[$part])) { 30 | $root = $root[$part]; 31 | continue; 32 | } else { 33 | $root = $default; 34 | break; 35 | } 36 | } 37 | 38 | return ($this->cache[$key] = $root); 39 | } 40 | 41 | protected function parse($path) { 42 | $data = json_decode(file_get_contents($path), true); 43 | 44 | if (function_exists('json_last_error_msg')) { 45 | $error_message = json_last_error_msg(); 46 | } else { 47 | $error_message = 'Syntax error'; 48 | } 49 | 50 | if (json_last_error() !== JSON_ERROR_NONE) { 51 | $error = array( 52 | 'message' => $error_message, 53 | 'type' => json_last_error(), 54 | 'file' => $path, 55 | ); 56 | throw new \Exception($error); 57 | } 58 | 59 | return $data; 60 | } 61 | } -------------------------------------------------------------------------------- /src/db/main/SiteIntegrate.php: -------------------------------------------------------------------------------- 1 | Add($fields); 41 | if ($ID) { 42 | return $ID; 43 | } else { 44 | throw new BimException($obSite->LAST_ERROR); 45 | } 46 | } 47 | 48 | /** 49 | * Update 50 | * @param $ID 51 | * @param $fields 52 | */ 53 | public static function Update($ID, $fields) 54 | { 55 | // Update 56 | } 57 | 58 | /** 59 | * Delete 60 | * @param $ID 61 | * @return mixed 62 | * @throws \Exception 63 | */ 64 | public static function Delete($ID) 65 | { 66 | $obSite = new \CSite; 67 | $dbSite = $obSite->GetList($by = "sort", $order = "desc", array('ID' => $ID)); 68 | if ($arSite = $dbSite->Fetch()) { 69 | $res = $obSite->Delete($ID); 70 | if ($res) { 71 | return $ID; 72 | } else { 73 | throw new BimException($obSite->LAST_ERROR); 74 | } 75 | } 76 | } 77 | 78 | 79 | } -------------------------------------------------------------------------------- /src/Util/Helper.php: -------------------------------------------------------------------------------- 1 | 'asc'); 55 | $groupTmp = 'sort'; 56 | $groupQuery = $group->GetList($groupOrder, $groupTmp); 57 | $groups = array(); 58 | for ($i = 0; $item = $groupQuery->Fetch(); $i++) { 59 | $groups[$i] = $item; 60 | } 61 | return $groups; 62 | } 63 | 64 | /** 65 | * Удаление полей массива 66 | * 67 | * @param $needle 68 | * @param $data : Формируемый массив 69 | */ 70 | public static function unsetFields($needle, &$data) 71 | { 72 | if (!is_array($needle)) { 73 | array($needle); 74 | } 75 | 76 | foreach ($needle as $item) { 77 | unset($data[$item]); 78 | } 79 | } 80 | } -------------------------------------------------------------------------------- /src/db/generator/providers/Site.php: -------------------------------------------------------------------------------- 1 | checkParams($siteId); 23 | $siteData = $this->ownerItemDbData; 24 | unset($siteData['ID']); 25 | $addFields = $siteData; 26 | return $this->getMethodContent('Bim\Db\Main\SiteIntegrate', 'Add', array($addFields)); 27 | } 28 | 29 | /** 30 | * Генерация кода обновления 31 | * 32 | * generateUpdateCode 33 | * @param $params 34 | * @return mixed|void 35 | */ 36 | public function generateUpdateCode($params) 37 | { 38 | // Update 39 | } 40 | 41 | /** 42 | * Метод для генерации кода удаления 43 | * 44 | * generateDeleteCode 45 | * @param $siteId 46 | * @return mixed 47 | */ 48 | public function generateDeleteCode($siteId) 49 | { 50 | $this->checkParams($siteId); 51 | 52 | $siteData = $this->ownerItemDbData; 53 | return $this->getMethodContent('Bim\Db\Main\SiteIntegrate', 'Delete', array($siteData['LID'])); 54 | } 55 | 56 | 57 | /** 58 | * Абстрактный метод проверки передаваемых параметров 59 | * 60 | * checkParams 61 | * @param array $siteId 62 | * @return mixed|void 63 | * @throws \Exception 64 | */ 65 | public function checkParams($siteId) 66 | { 67 | $site = new \CSite(); 68 | if (!isset($siteId) || empty($siteId)) { 69 | throw new BimException('В параметрах не найден siteId'); 70 | } 71 | $this->ownerItemDbData = array(); 72 | $siteDbRes = $site->GetList($by = "lid", $order = "desc", array('LID' => $siteId)); 73 | if ($siteDbRes === false || !$siteDbRes->SelectedRowsCount()) { 74 | throw new BimException('Не найден сайт с id = ' . $siteId); 75 | } 76 | $siteData = $siteDbRes->Fetch(); 77 | $this->ownerItemDbData = $siteData; 78 | } 79 | 80 | 81 | } -------------------------------------------------------------------------------- /docs/index.md~: -------------------------------------------------------------------------------- 1 | # Welcome to Viewdocs 2 | 3 | Viewdocs is [Read the Docs](https://readthedocs.org/) meets [Gist.io](http://gist.io/) for simple project documentation. It renders Markdown from your repository's `docs` directory as simple static pages. 4 | 5 | ### Getting Started 6 | 7 | Just make a `docs` directory in your Github project repository and put an `index.md` file in there to get started. Then browse to: 8 | 9 | http://.viewdocs.io/ 10 | 11 | Any other Markdown files in your `docs` directory are available as a subpath, including files in directories. You can update pages by just pushing to your repository or editing directly on Github. It can take up to 1-2 minutes before changes will appear. 12 | 13 | This page is an example of what documentation will look like by default. Here is [another example page](/viewdocs/example). The source for these pages are in the [docs directory](https://github.com/progrium/viewdocs/tree/master/docs) of the Viewdocs project. 14 | 15 | ### Preview changes before pushing documentation back the repository 16 | 17 | If you want to find out how things look like locally before pushing your code back to the remote repository, you might want to try out [`previewdocs`](http://fgrehm.viewdocs.io/previewdocs). 18 | 19 | ### Advanced Usage 20 | 21 | You can show documentation for different [branches](http://inconshreveable.viewdocs.io/ngrok~master/DEVELOPMENT) or [tags](http://discourse.viewdocs.io/discourse~v0.9.6/INSTALL-ubuntu) of a repository by including a reference name after a tilde in the repository part of the path. It would look like this: 22 | 23 | http://.viewdocs.io/~ 24 | 25 | You can also customize the look and layout of your docs. Make your own `docs/template.html` based on the [default template](https://github.com/progrium/viewdocs/blob/master/docs/template.html) and your pages will be rendered with that template. If you create a `home.html` template, this will be used for your project's landing page. 26 | 27 | I also highly recommend you [read the source](https://github.com/progrium/viewdocs/blob/master/viewdocs.go) to this app. It's less than 500 lines of Go. If you want to hack on Viewdocs, [check this out](/viewdocs/development). 28 | 29 |
30 | Enjoy!
31 | [Jeff Lindsay](http://twitter.com/progrium) 32 | -------------------------------------------------------------------------------- /src/db/generator/Code.php: -------------------------------------------------------------------------------- 1 | Add($fields); 46 | if ($ID) { 47 | return $ID; 48 | } else { 49 | throw new BimException($obLang->LAST_ERROR); 50 | } 51 | } 52 | 53 | /** 54 | * @return bool 55 | */ 56 | public static function Update() 57 | { 58 | return true; 59 | } 60 | 61 | /** 62 | * Удаление 63 | * 64 | * @param $ID 65 | * @return array 66 | * @throws BimException 67 | */ 68 | public static function Delete($ID) 69 | { 70 | $obLang = new \CLanguage(); 71 | if ($ID) { 72 | $dbLang = $obLang->GetList($by = "lid", $order = "desc", array('ID' => $ID)); 73 | if ($arLang = $dbLang->Fetch()) { 74 | 75 | $res = $obLang->Delete($ID); 76 | if (!$res) { 77 | throw new BimException($obLang->LAST_ERROR); 78 | } 79 | } 80 | } else { 81 | throw new BimException("Language ID is empty"); 82 | } 83 | } 84 | 85 | 86 | } -------------------------------------------------------------------------------- /src/db/generator/providers/language.php: -------------------------------------------------------------------------------- 1 | checkParams($langId); 22 | 23 | $langData = $this->ownerItemDbData; 24 | unset($langData['ID']); 25 | $addFields = $langData; 26 | 27 | return $this->getMethodContent('Bim\Db\Main\LanguageIntegrate', 'Add', array($addFields)); 28 | } 29 | 30 | /** 31 | * метод для генерации кода обновления языка системы 32 | * @param $params array 33 | * @return string 34 | */ 35 | public function generateUpdateCode($params) 36 | { 37 | $this->checkParams($params); 38 | $langData = $this->ownerItemDbData; 39 | $updateFields = $langData; 40 | return $this->getMethodContent('Bim\Db\Main\LanguageIntegrate', 'Update', array($updateFields['LID'], $updateFields)); 41 | 42 | } 43 | 44 | /** 45 | * метод для генерации кода удаления языка системы 46 | * @param array $langId 47 | * @return mixed 48 | * @throws BimException 49 | */ 50 | public function generateDeleteCode($langId) 51 | { 52 | $this->checkParams($langId); 53 | $langData = $this->ownerItemDbData; 54 | return $this->getMethodContent('Bim\Db\Main\LanguageIntegrate', 'Delete', array($langData['LID'])); 55 | } 56 | 57 | /** 58 | * @param array $langId 59 | * @return mixed|void 60 | * @throws BimException 61 | * @internal param array $params 62 | */ 63 | public function checkParams($langId) 64 | { 65 | $lang = new \CLanguage(); 66 | if (!isset($langId) || empty($langId)) { 67 | throw new BimException('В параметрах не найден langId'); 68 | } 69 | 70 | $this->ownerItemDbData = array(); 71 | $langDbRes = $lang->GetList($by = "lid", $order = "desc", array('LID' => $langId)); 72 | if ($langDbRes === false || !$langDbRes->SelectedRowsCount()) { 73 | throw new BimException('Не найден язык системы с id = ' . $langId); 74 | } 75 | 76 | $langData = $langDbRes->Fetch(); 77 | $this->ownerItemDbData = $langData; 78 | } 79 | 80 | 81 | } -------------------------------------------------------------------------------- /docs/template.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | {{NAME}} :: viewdocs.io 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 38 | 39 | 40 |
41 |
42 |

{{NAME}} :: index

43 |
44 |
45 | {{CONTENT}} 46 |
47 |
48 | 56 | 57 | 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /src/db/generator/providers/Group.php: -------------------------------------------------------------------------------- 1 | checkParams($groupId); 25 | if ($groupData = $this->ownerItemDbData) { 26 | unset($groupData['ID']); 27 | $addFields = $groupData; 28 | return $this->getMethodContent('Bim\Db\Main\GroupIntegrate', 'Add', array($addFields)); 29 | } 30 | return true; 31 | } 32 | 33 | /** 34 | * Генерация кода обновления 35 | * 36 | * generateUpdateCode 37 | * @param array $params 38 | * @return mixed|void 39 | */ 40 | public function generateUpdateCode($params) 41 | { 42 | // Update generate 43 | } 44 | 45 | /** 46 | * метод для генерации кода удаления 47 | * 48 | * generateDeleteCode 49 | * @param array $groupId 50 | * @return string 51 | * @throws \Exception 52 | * @internal param array $params 53 | */ 54 | public function generateDeleteCode($groupId) 55 | { 56 | $this->checkParams($groupId); 57 | 58 | if ($groupData = $this->ownerItemDbData) { 59 | unset($groupData['ID']); 60 | return $this->getMethodContent('Bim\Db\Main\GroupIntegrate', 'Delete', array($groupData['STRING_ID'])); 61 | } 62 | return false; 63 | } 64 | 65 | /** 66 | * Абстрактный метод проверки передаваемых параметров 67 | * 68 | * checkParams 69 | * @param array $groupId 70 | * @return mixed|void 71 | * @throws \Exception 72 | * @internal param array $params 73 | */ 74 | public function checkParams($groupId) 75 | { 76 | $group = new \CGroup(); 77 | if (!isset($groupId) || empty($groupId)) { 78 | throw new BimException('empty groupId param'); 79 | } 80 | $this->ownerItemDbData = array(); 81 | $groupDbRes = $group->GetList($by = 'id', $order = 'desc', array('ID' => $groupId)); 82 | if ($groupDbRes === false || !$groupDbRes->SelectedRowsCount()) { 83 | throw new BimException('Group with id = ' . $groupId . ' not exists'); 84 | } 85 | $groupData = $groupDbRes->Fetch(); 86 | if (!strlen($groupData['STRING_ID'])) { 87 | throw new BimException('Group with id = ' . $groupId . ' have empty STRING_ID!'); 88 | } 89 | $this->ownerItemDbData = $groupData; 90 | } 91 | 92 | 93 | } -------------------------------------------------------------------------------- /src/db/iblock/HighloadblockIntegrate.php: -------------------------------------------------------------------------------- 1 | trim($entityName), 34 | 'TABLE_NAME' => trim($tableName) 35 | ); 36 | $addResult = HL\HighloadBlockTable::add($addFields); 37 | if (!$addResult->isSuccess()) { 38 | throw new \Exception(implode(", ", $addResult->getErrorMessages())); 39 | } 40 | return true; 41 | } 42 | 43 | 44 | /** 45 | * Delete 46 | * @param $entityName 47 | * @return bool 48 | * @throws \Exception 49 | */ 50 | public static function Delete($entityName) 51 | { 52 | $userType = new \CUserTypeEntity(); 53 | if (!strlen($entityName)) { 54 | throw new BimException('Incorrect entityName param value'); 55 | } 56 | $filter = array('NAME' => $entityName); 57 | $hlBlockDbRes = HL\HighloadBlockTable::getList(array( 58 | "filter" => $filter 59 | )); 60 | if (!$hlBlockDbRes->getSelectedRowsCount()) { 61 | throw new BimException('Not found highloadBlock with entityName = ' . $entityName); 62 | } 63 | $hlBlockRow = $hlBlockDbRes->fetch(); 64 | $entity = HL\HighloadBlockTable::compileEntity($hlBlockRow); 65 | $entityDataClass = $entity->getDataClass(); 66 | 67 | $obList = $entityDataClass::getList(); 68 | if ($obList->getSelectedRowsCount() > 0) { 69 | throw new BimException('Unable to remove a highloadBlock[' . $entityName . '], because it has elements'); 70 | } 71 | 72 | # delete all Fields 73 | $obHl = $userType->GetList(array(), array("ENTITY_ID" => "HLBLOCK_" . $hlBlockRow['ID'])); 74 | while ($arHl = $obHl->Fetch()) { 75 | 76 | $obUF = new \CUserTypeEntity(); 77 | $obUF->Delete($arHl['ID']); 78 | 79 | } 80 | 81 | $delResult = HL\HighloadBlockTable::delete($hlBlockRow['ID']); 82 | if (!$delResult->isSuccess()) { 83 | throw new BimException(implode(", ", $delResult->getErrorMessages())); 84 | } 85 | return true; 86 | } 87 | 88 | } -------------------------------------------------------------------------------- /src/db/main/GroupIntegrate.php: -------------------------------------------------------------------------------- 1 | 'error', 'error_text' => 'Field STRING_ID is required.'); 30 | } 31 | if (!isset($fields['ACTIVE']) || empty($fields['ACTIVE'])) { 32 | $fields['ACTIVE'] = "N"; 33 | } 34 | if (!isset($fields['C_SORT']) || empty($fields['C_SORT'])) { 35 | $fields['C_SORT'] = 100; 36 | } 37 | $groupDbRes = $group->GetList($by = 'sort', $sort = 'asc', array('STRING_ID' => $fields['STRING_ID'])); 38 | if ($groupDbRes !== false && $groupDbRes->SelectedRowsCount()) { 39 | throw new BimException('Group with STRING_ID = "' . $fields['STRING_ID'] . '" already exist.'); 40 | } 41 | $group = new \CGroup; 42 | $ID = $group->Add($fields); 43 | if ($ID) { 44 | return $ID; 45 | } else { 46 | throw new BimException($group->LAST_ERROR); 47 | } 48 | } 49 | 50 | 51 | /** 52 | * Update 53 | * @param $CODE 54 | * @param $fields 55 | * @return bool 56 | */ 57 | public function Update($CODE, $fields) 58 | { 59 | return true; 60 | } 61 | 62 | 63 | /** 64 | * Delete 65 | * @param $CODE 66 | * @return array 67 | * @throws \Exception 68 | */ 69 | public static function Delete($CODE) 70 | { 71 | $group = new \CGroup(); 72 | $user = new \CUser(); 73 | if (!empty($CODE)) { 74 | $by = "ID"; 75 | $order = "asc"; 76 | $dbGroup = $group->GetList($by, $order, array('STRING_ID' => $CODE)); 77 | if ($arGroup = $dbGroup->Fetch()) { 78 | $arReturn = $arGroup; 79 | } 80 | } else { 81 | throw new BimException('Empty group code'); 82 | } 83 | 84 | if (intval($arReturn['ID']) > 0) { 85 | $arUsers = $group->GetGroupUser($arReturn['ID']); 86 | foreach ($arUsers as $UserID) { 87 | $arGroup = $user->GetUserGroup($UserID); 88 | $arGroup[] = "3"; 89 | $user->SetUserGroup($UserID, $arGroup); 90 | } 91 | $res = $group->Delete($arReturn['ID']); 92 | 93 | if (is_object($res)) { 94 | return $arReturn['ID']; 95 | } else { 96 | throw new BimException($group->LAST_ERROR); 97 | } 98 | } else { 99 | throw new BimException('Group not found'); 100 | } 101 | } 102 | 103 | 104 | } -------------------------------------------------------------------------------- /src/db/iblock/IblockTypeIntegrate.php: -------------------------------------------------------------------------------- 1 | array( 45 | 'NAME' => 'Название', 46 | 'SECTION_NAME' => 'Разделы', 47 | 'ELEMENT_NAME' => 'Элементы', 48 | ), 49 | 'en' => array( 50 | 'NAME' => 'Common', 51 | 'SECTION_NAME' => 'Sections', 52 | 'ELEMENT_NAME' => 'Elements', 53 | ), 54 | ); 55 | $l = \CLanguage::GetList($lby = "sort", $lorder = "asc"); 56 | while ($arIBTLang = $l->GetNext()) { 57 | if (array_key_exists($arIBTLang["LID"], $langDefaults)) { 58 | $arFields["LANG"][$arIBTLang["LID"]] = $langDefaults[$arIBTLang["LID"]]; 59 | } 60 | } 61 | } 62 | $CIblockType = new \CIBlockType(); 63 | if ($CIblockType->Add($arFields)) { 64 | return true; 65 | } else { 66 | throw new BimException($CIblockType->LAST_ERROR); 67 | } 68 | } 69 | 70 | /** 71 | * Delete 72 | * @param $IblockTypeCode 73 | * @return bool 74 | * @throws \Exception 75 | */ 76 | public static function Delete($IblockTypeCode) 77 | { 78 | $Iblock = new \CIBlock(); 79 | $iblockEl = new \CIBlockElement(); 80 | $dbIblock = $Iblock->GetList(array(), array('TYPE' => $IblockTypeCode)); 81 | while ($dbRow = $dbIblock->Fetch()) { 82 | $iblockElDbRes = $iblockEl->GetList(array(), array('IBLOCK_ID' => $dbRow['ID'])); 83 | if ($iblockElDbRes !== false && $iblockElDbRes->SelectedRowsCount()) { 84 | throw new BimException('Can not delete iblock type: iblock id =' . $dbRow['ID'] . ' have elements'); 85 | } 86 | } 87 | if (!\CIBlockType::Delete($IblockTypeCode)) { 88 | throw new BimException('Delete iblock type error!'); 89 | } 90 | return true; 91 | } 92 | 93 | } -------------------------------------------------------------------------------- /src/db/entity/MigrationTable.php: -------------------------------------------------------------------------------- 1 | get("migration_table"); 25 | } 26 | 27 | /** 28 | * isExistsInTable 29 | * @param $id 30 | * @return bool 31 | * @throws \Exception 32 | */ 33 | public static function isExistsInTable($id) 34 | { 35 | # check migration tables 36 | self::checkMigrationTable(); 37 | 38 | global $DB; 39 | if ($result = $DB->Query("SELECT 'id' FROM " . self::getTableName() . " WHERE id = '" . $id . "'", true)) { 40 | if ($result->AffectedRowsCount()) { 41 | return true; 42 | } 43 | } else { 44 | throw new \Exception($DB->GetErrorMessage()); 45 | } 46 | return false; 47 | } 48 | 49 | /** 50 | * add 51 | * @param $id 52 | * @return bool 53 | * @throws Exception 54 | */ 55 | public static function add($id) 56 | { 57 | global $DB; 58 | if (!self::isExistsInTable($id)) { 59 | $DB->Add(self::getTableName(), array( 60 | "id" => $id 61 | )); 62 | if (self::isExistsInTable($id)) { 63 | return true; 64 | } 65 | } 66 | return false; 67 | } 68 | 69 | /** 70 | * delete 71 | * @param $id 72 | * @return bool 73 | * @throws \Exception 74 | */ 75 | public static function delete($id) 76 | { 77 | global $DB; 78 | if ($result = $DB->Query("DELETE FROM " . self::getTableName() . " WHERE id = '" . $id . "'", true)) { 79 | return true; 80 | } else { 81 | throw new \Exception($DB->GetErrorMessage()); 82 | } 83 | return false; 84 | } 85 | 86 | 87 | /** 88 | * checkMigrationTable 89 | * @throws Exception 90 | */ 91 | public static function checkMigrationTable() 92 | { 93 | global $DB; 94 | if (!$DB->Query("SELECT 'id' FROM " . self::getTableName(), true)) { 95 | throw new \Exception("Migration table not found, run init command. Example: php bim init"); 96 | } 97 | } 98 | 99 | /** 100 | * createTable 101 | * @return bool 102 | * @throws \Exception 103 | */ 104 | public static function createTable() 105 | { 106 | global $DB; 107 | $errors = false; 108 | if (!$DB->Query("SELECT 'id' FROM " . self::getTableName(), true)) { 109 | $errors = $DB->RunSQLBatch(__DIR__ . '/../install/install.sql'); 110 | } else { 111 | return false; 112 | } 113 | if ($errors !== false) { 114 | throw new \Exception(implode("", $errors)); 115 | return false; 116 | } 117 | return true; 118 | } 119 | 120 | } -------------------------------------------------------------------------------- /src/cmd/ExportCommand.php: -------------------------------------------------------------------------------- 1 | 0) { 24 | $methodName = ucfirst($args[0]); 25 | if (method_exists($this, $methodName)) { 26 | $this->{$methodName}($args); 27 | } else { 28 | throw new \Bim\Exception\BimException("command (export " . $args[0] . ") not found"); 29 | } 30 | } else { 31 | $this->padding(" call default method " . $this->color(strtoupper("completed"), 32 | \ConsoleKit\Colors::GREEN)); 33 | } 34 | } 35 | 36 | /** 37 | * @throws \Bim\Exception\BimException 38 | */ 39 | public function Make() 40 | { 41 | $time_start = microtime(true); 42 | $this->info(" -> Start make export:"); 43 | $this->writeln(''); 44 | 45 | $session = new \Bim\Export\Session(); 46 | $session->init(); 47 | $session->packCore(); 48 | 49 | $this->padding($session->getDataResponse()); 50 | 51 | $time_end = microtime(true); 52 | $time = $time_end - $time_start; 53 | $this->writeln(''); 54 | $this->info(" -> " . round($time, 2) . "s"); 55 | } 56 | 57 | /** 58 | * @param bool $return 59 | * @return array|mixed 60 | * @throws \Bim\Exception\BimException 61 | */ 62 | public function Ls($return = false) 63 | { 64 | $exportJson = self::getMigrationPath() . \Bim\Export\Session::EXPORT_FOLDER . "/export.json"; 65 | if (file_exists($exportJson)) { 66 | $data = json_decode(file_get_contents($exportJson), true); 67 | } else { 68 | $data = array(); 69 | file_put_contents($exportJson, json_encode($data)); 70 | } 71 | 72 | if ($return === true) { 73 | return $data; 74 | } 75 | 76 | if (!empty($data)) { 77 | if (isset($data['items'])) { 78 | $list = array(); 79 | foreach ($data['items'] as $key => $item) { 80 | $list[] = "[" . $key . "] - " . $this->color(strtoupper($item['id']), 81 | \ConsoleKit\Colors::GREEN); 82 | } 83 | $this->padding(implode("\n", $list)); 84 | } else { 85 | throw new \Bim\Exception\BimException("Bad format export.json"); 86 | } 87 | } else { 88 | // empty 89 | } 90 | return $data; 91 | } 92 | 93 | 94 | public function Install($args) 95 | { 96 | global $DB; 97 | $this->padding("up export databases (Revision № ".$args[1].") ..."); 98 | $session = new \Bim\Export\Session(); 99 | $sqlBatch = $session->getSqlBatchByExport($args, $this->Ls(true)); 100 | 101 | $i = 0; 102 | if ($sqlBatch) { 103 | foreach ($sqlBatch as $i => $bath) { 104 | $err_mess = "Line: "; 105 | $res = $DB->Query($bath, false, $err_mess.__LINE__); 106 | fwrite(\STDOUT, " SQL QUERY: ".$i." \r"); 107 | } 108 | } 109 | fwrite(\STDOUT, " SQL QUERY: ".$i." - ".$this->color(strtoupper("completed"),\ConsoleKit\Colors::GREEN)." \n"); 110 | 111 | 112 | $this->padding("up export core (Revision № ".$args[1].") ..."); 113 | 114 | } 115 | 116 | } 117 | -------------------------------------------------------------------------------- /src/db/iblock/IblockPropertyIntegrate.php: -------------------------------------------------------------------------------- 1 | false, 40 | 'IS_REQUIRED' => false, 41 | 'ACTIVE' => true, 42 | 'PROPERTY_TYPE' => 'S', 43 | 'USER_TYPE' => false, 44 | 'FILE_TYPE' => '', 45 | 'LIST_TYPE' => 'L', 46 | 'ROW_COUNT' => 1, 47 | 'COL_COUNT' => 30, 48 | 'LINK_IBLOCK_ID' => null, 49 | 'DEFAULT_VALUE' => null, 50 | 'WITH_DESCRIPTION' => 'N', 51 | 'SEARCHABLE' => 'N', 52 | 'FILTRABLE' => 'N', 53 | 'MULTIPLE_CNT' => 5, 54 | 'HINT' => '', 55 | 'SECTION_PROPERTY' => 'Y', 56 | 'SMART_FILTER' => 'N', 57 | 'USER_TYPE_SETTINGS' => array(), 58 | 'VALUES' => array() 59 | ); 60 | if ($arFields['IBLOCK_CODE']) { 61 | unset($arFields['IBLOCK_ID']); 62 | $rsIBlock = $iblock->GetList(array(), 63 | array('CODE' => $arFields['IBLOCK_CODE'], 'CHECK_PERMISSIONS' => 'N')); 64 | if ($arIBlock = $rsIBlock->Fetch()) { 65 | $arFields['IBLOCK_ID'] = $arIBlock['ID']; 66 | } else { 67 | throw new BimException(__METHOD__ . ' Not found iblock with code ' . $arFields['IBLOCK_CODE']); 68 | } 69 | } 70 | if (!strlen($arFields['CODE'])) { 71 | throw new BimException(__METHOD__ . ' Not found property code'); 72 | } 73 | $iblockPropDbRes = \CIBlockProperty::GetList(array(), 74 | array('IBLOCK_ID' => $arFields['IBLOCK_ID'], 'CODE' => $arFields['CODE'])); 75 | if ($iblockPropDbRes !== false && $iblockPropDbRes->SelectedRowsCount()) { 76 | throw new BimException(__METHOD__ . 'Property with code = "' . $arFields['CODE'] . '" '); 77 | } 78 | if ($arFields['LINK_IBLOCK_CODE']) { 79 | unset($arFields['LINK_IBLOCK_ID']); 80 | $rsIBlock = $iblock->GetList(array(), 81 | array('CODE' => $arFields['LINK_IBLOCK_CODE'], 'CHECK_PERMISSIONS' => 'N')); 82 | if ($arIBlock = $rsIBlock->Fetch()) { 83 | $arFields['LINK_IBLOCK_ID'] = $arIBlock['ID']; 84 | } 85 | } 86 | foreach ($arDefaultValues as $DefaultName => $DefaultValue) { 87 | if (!isset($arFields[$DefaultName]) || empty($arFields[$DefaultName])) { 88 | $arFields[$DefaultName] = $DefaultValue; 89 | } 90 | } 91 | $objCIBlockProperty = new \CIBlockProperty(); 92 | unset($arFields['ID']); 93 | $iId = $objCIBlockProperty->Add($arFields); 94 | if ($iId) { 95 | return $iId; 96 | } else { 97 | throw new BimException(__METHOD__ . ' ' . $objCIBlockProperty->LAST_ERROR); 98 | } 99 | } 100 | 101 | /** 102 | * Delete 103 | * @param $sIBlockCode 104 | * @param $sPropertyCode 105 | * @return array 106 | * @throws \Exception 107 | */ 108 | public static function Delete($sIBlockCode, $sPropertyCode) 109 | { 110 | $rsProperty = \CIBlockProperty::GetList(array(), 111 | array('IBLOCK_CODE' => $sIBlockCode, 'CODE' => $sPropertyCode)); 112 | if ($arProperty = $rsProperty->Fetch()) { 113 | if (\CIBlockProperty::Delete($arProperty['ID'])) { 114 | return true; 115 | } else { 116 | throw new BimException(__METHOD__ . "Iblock property delete error!"); 117 | } 118 | } else { 119 | throw new BimException(__METHOD__ . 'Not find property with code ' . $sPropertyCode); 120 | } 121 | } 122 | 123 | } -------------------------------------------------------------------------------- /src/db/generator/providers/Hlblock.php: -------------------------------------------------------------------------------- 1 | userType = new CUserTypeEntity(); 41 | $this->iblock = new CIBlock(); 42 | } 43 | 44 | 45 | /** 46 | * Генерация создания 47 | * 48 | * generateAddCode 49 | * @param array $hlBlockId 50 | * @return string 51 | * @throws \Exception 52 | */ 53 | public function generateAddCode($hlBlockId) 54 | { 55 | $return = array(); 56 | $hlBlock = HL\HighloadBlockTable::getById($hlBlockId)->fetch(); 57 | if (!$hlBlock) { 58 | throw new BimException('Not found highload block with id = ' . $hlBlockId); 59 | } 60 | $return[] = $this->getMethodContent('Bim\Db\Iblock\HighloadblockIntegrate', 'Add', 61 | array($hlBlock['NAME'], $hlBlock['TABLE_NAME'])); 62 | 63 | $hlQuery = $this->userType->GetList(array(), array("ENTITY_ID" => "HLBLOCK_" . $hlBlockId)); 64 | while ($hlData = $hlQuery->Fetch()) { 65 | 66 | $fullData = $this->userType->GetByID($hlData['ID']); 67 | unset($fullData['ID']); 68 | unset($fullData['ENTITY_ID']); 69 | 70 | if (($fullData['USER_TYPE_ID'] == "iblock_element" || $fullData['USER_TYPE_ID'] == "iblock_section") && (isset($fullData['SETTINGS']['IBLOCK_ID']))) { 71 | if (!empty($fullData['SETTINGS']['IBLOCK_ID'])) { 72 | $iblockId = $fullData['SETTINGS']['IBLOCK_ID']; 73 | unset($fullData['SETTINGS']['IBLOCK_ID']); 74 | $blockQuery = $this->iblock->GetList(array(), array('ID' => $iblockId, 'CHECK_PERMISSIONS' => 'N')); 75 | if ($iBlockData = $blockQuery->Fetch()) { 76 | $fullData['SETTINGS']['IBLOCK_CODE'] = $iBlockData['CODE']; 77 | } else { 78 | throw new BimException(' Not found iblock with id ' . $iblockId); 79 | } 80 | } 81 | } 82 | 83 | $return[] = $this->getMethodContent('Bim\Db\Iblock\HighloadblockFieldIntegrate', 'Add', 84 | array($hlBlock['NAME'], $fullData)); 85 | } 86 | return implode(PHP_EOL, $return); 87 | } 88 | 89 | 90 | /** 91 | * Генерация кода обновления 92 | * 93 | * generateUpdateCode 94 | * @param array $params 95 | * @return mixed|void 96 | */ 97 | public function generateUpdateCode($params) 98 | { 99 | // update 100 | } 101 | 102 | 103 | /** 104 | * метод для генерации кода удаления 105 | * 106 | * generateDeleteCode 107 | * @param array $hlBlockId 108 | * @return string 109 | * @throws \Exception 110 | */ 111 | public function generateDeleteCode($hlBlockId) 112 | { 113 | $hlBlock = HL\HighloadBlockTable::getById($hlBlockId)->fetch(); 114 | if (!$hlBlock) { 115 | throw new BimException('В системе не найден highload инфоблок с id = ' . $hlBlockId); 116 | } 117 | 118 | return $this->getMethodContent('Bim\Db\Iblock\HighloadblockIntegrate', 'Delete', array($hlBlock['NAME'])); 119 | } 120 | 121 | /** 122 | * Абстрактный метод проверки передаваемых параметров 123 | * 124 | * checkParams 125 | * @param array $params 126 | * @return mixed|void 127 | * @throws \Exception 128 | */ 129 | public function checkParams($params) 130 | { 131 | if (!isset($params['hlblockId']) || empty($params['hlblockId'])) { 132 | throw new BimException('В параметрах не найден hlblockId'); 133 | } 134 | foreach ($params['hlblockId'] as $hlblockId) { 135 | $hlBlock = HL\HighloadBlockTable::getById($hlblockId)->fetch(); 136 | if (!$hlBlock) { 137 | throw new BimException('В системе не найден highload инфоблок с id = ' . $hlblockId); 138 | } 139 | $this->ownerItemDbData[] = $hlBlock; 140 | } 141 | } 142 | 143 | 144 | } -------------------------------------------------------------------------------- /src/db/generator/providers/HlblockField.php: -------------------------------------------------------------------------------- 1 | iblock = new CIBlock(); 38 | $this->userType = new CUserTypeEntity(); 39 | } 40 | 41 | /** 42 | * Генерация создания 43 | * 44 | * generateAddCode 45 | * @param array $params 46 | * @return string 47 | * @throws \Exception 48 | */ 49 | public function generateAddCode($params) 50 | { 51 | $this->checkParams($params); 52 | $return = ""; 53 | $hlBlockData = $this->ownerItemDbData['hlblockData']; 54 | if ($hlFieldData = $this->ownerItemDbData['hlFieldData']) { 55 | unset($hlFieldData['ID']); 56 | unset($hlFieldData['ENTITY_ID']); 57 | 58 | # add iblock code to 59 | if (($hlFieldData['USER_TYPE_ID'] == "iblock_element" || $hlFieldData['USER_TYPE_ID'] == "iblock_section") && (isset($hlFieldData['SETTINGS']['IBLOCK_ID']))) { 60 | if (!empty($hlFieldData['SETTINGS']['IBLOCK_ID'])) { 61 | $iblockId = $hlFieldData['SETTINGS']['IBLOCK_ID']; 62 | unset($hlFieldData['SETTINGS']['IBLOCK_ID']); 63 | $rsIBlock = $this->iblock->GetList(array(), array('ID' => $iblockId, 'CHECK_PERMISSIONS' => 'N')); 64 | if ($arIBlock = $rsIBlock->Fetch()) { 65 | $hlFieldData['SETTINGS']['IBLOCK_CODE'] = $arIBlock['CODE']; 66 | } else { 67 | throw new BimException(' Not found iblock with id ' . $iblockId); 68 | } 69 | } 70 | } 71 | 72 | $return = $this->getMethodContent('Bim\Db\Iblock\HighloadblockFieldIntegrate', 'Add', 73 | array($hlBlockData['NAME'], $hlFieldData)); 74 | } 75 | return $return; 76 | } 77 | 78 | /** 79 | * Генерация кода обновления 80 | * 81 | * generateUpdateCode 82 | * @param array $params 83 | * @return string 84 | * @throws \Exception 85 | */ 86 | public function generateUpdateCode($params) 87 | { 88 | // UPDATE 89 | } 90 | 91 | /** 92 | * метод для генерации кода удаления 93 | * 94 | * generateDeleteCode 95 | * @param array $params 96 | * @return string 97 | * @throws \Exception 98 | */ 99 | public function generateDeleteCode($params) 100 | { 101 | $this->checkParams($params); 102 | $return = ""; 103 | $hlBlockData = $this->ownerItemDbData['hlblockData']; 104 | if ($hlFieldData = $this->ownerItemDbData['hlFieldData']) { 105 | $return = $this->getMethodContent('Bim\Db\Iblock\HighloadblockFieldIntegrate', 'Delete', 106 | array($hlBlockData['NAME'], $hlFieldData['FIELD_NAME'])); 107 | } 108 | return $return; 109 | } 110 | 111 | /** 112 | * Абстрактный метод проверки передаваемых параметров 113 | * 114 | * checkParams 115 | * @param array $params 116 | * @return mixed|void 117 | * @throws \Exception 118 | */ 119 | public function checkParams($params) 120 | { 121 | if (!isset($params['hlblockId']) || empty($params['hlblockId'])) { 122 | throw new BimException('В параметрах не найден hlblockId'); 123 | } 124 | if (!isset($params['hlFieldId']) || empty($params['hlFieldId'])) { 125 | throw new BimException('В параметрах не найден hlFieldId'); 126 | } 127 | $hlBlock = HL\HighloadBlockTable::getById($params['hlblockId'])->fetch(); 128 | if (!$hlBlock) { 129 | throw new BimException('В системе не найден highload инфоблок с id = ' . $params['hlblockId']); 130 | } 131 | $this->ownerItemDbData['hlblockData'] = $hlBlock; 132 | if ($params['hlFieldId']) { 133 | $userFieldData = $this->userType->GetByID($params['hlFieldId']); 134 | if ($userFieldData === false || empty($userFieldData)) { 135 | throw new BimException('Не найдено пользовательское поле с id = ' . $params['hlFieldId']); 136 | } 137 | $this->ownerItemDbData['hlFieldData'] = $userFieldData; 138 | } 139 | } 140 | 141 | } -------------------------------------------------------------------------------- /src/db/iblock/IblockIntegrate.php: -------------------------------------------------------------------------------- 1 | 'Y', 46 | 'LIST_PAGE_URL' => '#SITE_DIR#/' . $input['IBLOCK_TYPE_ID'] . '/index.php?ID=#IBLOCK_ID#', 47 | 'SECTION_PAGE_URL' => '#SITE_DIR#/' . $input['IBLOCK_TYPE_ID'] . '/list.php?SECTION_ID=#ID#', 48 | 'DETAIL_PAGE_URL' => '#SITE_DIR#/' . $input['IBLOCK_TYPE_ID'] . '/detail.php?ID=#ID#', 49 | 'INDEX_SECTION' => 'Y', 50 | 'INDEX_ELEMENT' => 'Y', 51 | 'PICTURE' => array( 52 | 'del' => null, 53 | 'MODULE_ID' => 'iblock', 54 | ), 55 | 'DESCRIPTION' => '', 56 | 'DESCRIPTION_TYPE' => 'text', 57 | 'EDIT_FILE_BEFORE' => '', 58 | 'EDIT_FILE_AFTER' => '', 59 | 'WORKFLOW' => 'N', 60 | 'BIZPROC' => 'N', 61 | 'SECTION_CHOOSER' => 'L', 62 | 'LIST_MODE' => '', 63 | 'FIELDS' => array(), 64 | 'ELEMENTS_NAME' => 'Элементы', 65 | 'ELEMENT_NAME' => 'Элемент', 66 | 'ELEMENT_ADD' => 'Добавить элемент', 67 | 'ELEMENT_EDIT' => 'Изменить элемент', 68 | 'ELEMENT_DELETE' => 'Удалить элемент', 69 | 'SECTIONS_NAME' => 'Разделы', 70 | 'SECTION_NAME' => 'Раздел', 71 | 'SECTION_ADD' => 'Добавить раздел', 72 | 'SECTION_EDIT' => 'Изменить раздел', 73 | 'SECTION_DELETE' => 'Удалить раздел', 74 | 'RIGHTS_MODE' => 'S', 75 | 'GROUP_ID' => array( 76 | 2 => 'R', 77 | 1 => 'X' 78 | ), 79 | 'VERSION' => 1 80 | ); 81 | if (!strlen($input['CODE'])) { 82 | throw new BimException('Not found iblock code'); 83 | } 84 | $iblockDbRes = $iBlock->GetList(array(), array('CODE' => $input['CODE'], 'CHECK_PERMISSIONS' => 'N')); 85 | if ($iblockDbRes !== false && $iblockDbRes->SelectedRowsCount()) { 86 | throw new BimException('Iblock with code = "' . $input['CODE'] . '" already exist.'); 87 | } 88 | foreach ($defaultValue as $defaultName => $defaultValue) { 89 | if (!isset($input[$defaultName]) || empty($input[$defaultName])) { 90 | $input[$defaultName] = $defaultValue; 91 | } 92 | } 93 | 94 | // Перегоняем имена групп (если были изменены при накатывании миграции) в идентификаторы групп 95 | $arGroups = Helper::getUserGroups(); 96 | foreach ($input['GROUP_ID'] as $groupCode => $right) { 97 | $groupId = Helper::getUserGroupId($groupCode, $arGroups); 98 | if ($groupId != null && strlen($groupId) > 0) { 99 | $input['GROUP_ID'][$groupId] = $input['GROUP_ID'][$groupCode]; 100 | unset($input['GROUP_ID'][$groupCode]); 101 | } 102 | } 103 | 104 | $ID = $iBlock->Add($input); 105 | if ($ID) { 106 | return $ID; 107 | } else { 108 | throw new BimException($iBlock->LAST_ERROR); 109 | } 110 | } 111 | 112 | /** 113 | * Метод удаления информационного блока. 114 | * 115 | * @param $IblockCode 116 | * @return bool 117 | * @throws \Exception 118 | */ 119 | public static function Delete($IblockCode) 120 | { 121 | $iBlock = new CIBlock(); 122 | $iBlockElement = new CIBlockElement(); 123 | $dbIblock = $iBlock->GetList(array(), array('CODE' => $IblockCode, 'CHECK_PERMISSIONS' => 'N')); 124 | if ($item = $dbIblock->Fetch()) { 125 | $iblockElDbRes = $iBlockElement->GetList(array(), array('IBLOCK_ID' => $item['ID'])); 126 | if ($iblockElDbRes !== false && $iblockElDbRes->SelectedRowsCount()) { 127 | throw new BimException('Can not delete iblock id = ' . $item['ID'] . ' have elements'); 128 | } 129 | if (\CIBlock::Delete($item['ID'])) { 130 | return true; 131 | } else { 132 | throw new BimException('Iblock delete error!'); 133 | } 134 | } else { 135 | throw new BimException('Not find iblock with code ' . $IblockCode); 136 | } 137 | } 138 | 139 | } -------------------------------------------------------------------------------- /src/db/iblock/HighloadblockFieldIntegrate.php: -------------------------------------------------------------------------------- 1 | $fields["ENTITY_ID"], 43 | "FIELD_NAME" => $fields["FIELD_NAME"], 44 | )); 45 | if ($typeEntityDbRes !== false && $typeEntityDbRes->SelectedRowsCount()) { 46 | throw new \Exception('Hlblock field with name = "' . $fields["FIELD_NAME"] . '" already exist.'); 47 | } 48 | 49 | #if 50 | if (($fields['USER_TYPE_ID'] == "iblock_element" || $fields['USER_TYPE_ID'] == "iblock_section") && (isset($fields['SETTINGS']['IBLOCK_CODE']))) { 51 | unset($fields['SETTINGS']['IBLOCK_CODE']); 52 | $rsIBlock = \CIBlock::GetList(array(), 53 | array('CODE' => $fields['SETTINGS']['IBLOCK_CODE'], 'CHECK_PERMISSIONS' => 'N')); 54 | if ($arIBlock = $rsIBlock->Fetch()) { 55 | $fields['SETTINGS']['IBLOCK_ID'] = $arIBlock['ID']; 56 | } else { 57 | throw new \Exception(__METHOD__ . ' Not found iblock with code ' . $fields['SETTINGS']['IBLOCK_CODE']); 58 | } 59 | } 60 | 61 | $UserType = new \CUserTypeEntity; 62 | $ID = $UserType->Add($fields); 63 | if (!(int)$ID) { 64 | throw new \Exception('Not added Hlblock field'); 65 | } 66 | return $ID; 67 | } 68 | 69 | /** 70 | * Delete 71 | * @param $entityName 72 | * @param $fieldName 73 | * @return mixed 74 | * @throws \Exception 75 | */ 76 | public static function Delete($entityName, $fieldName) 77 | { 78 | if (empty($entityName)) { 79 | throw new \Exception('entityName is required'); 80 | } 81 | 82 | if (empty($fieldName)) { 83 | throw new \Exception('fieldName is required.'); 84 | } 85 | 86 | $filter = array('NAME' => $entityName); 87 | $hlBlockDbRes = HL\HighloadBlockTable::getList(array( 88 | "filter" => $filter 89 | )); 90 | if (!$hlBlockDbRes->getSelectedRowsCount()) { 91 | throw new \Exception('Not found highloadBlock with entityName = ' . $entityName); 92 | } 93 | 94 | $hlBlockRow = $hlBlockDbRes->fetch(); 95 | $entity = HL\HighloadBlockTable::compileEntity($hlBlockRow); 96 | $entityDataClass = $entity->getDataClass(); 97 | 98 | $obList = $entityDataClass::getList(array("select" => array("ID"))); 99 | if ($obList->getSelectedRowsCount() > 0) { 100 | throw new \Exception('Unable to remove a highloadBlock[ ' . $entityName . ' ], because it has elements'); 101 | } 102 | 103 | $userFieldEntity = self::_getEntityId($entityName); 104 | $typeEntityDbRes = \CUserTypeEntity::GetList(array(), array( 105 | "ENTITY_ID" => $userFieldEntity, 106 | "FIELD_NAME" => $fieldName, 107 | )); 108 | if ($typeEntityDbRes->SelectedRowsCount() > 0) { 109 | $hlBlockFieldData = $typeEntityDbRes->Fetch(); 110 | $userType = new \CUserTypeEntity; 111 | if (!$userType->Delete($hlBlockFieldData['ID'])) { 112 | throw new \Exception('Not delete Hlblock field'); 113 | } 114 | return $hlBlockFieldData['ID']; 115 | } 116 | } 117 | 118 | /** 119 | * _getEntityId 120 | * @param $entityName 121 | * @return bool|string 122 | * @throws \Exception 123 | */ 124 | public static function _getEntityId($entityName) 125 | { 126 | if (!strlen($entityName)) { 127 | return false; 128 | } 129 | $filter = array('NAME' => $entityName); 130 | $hlBlockDbRes = HL\HighloadBlockTable::getList(array( 131 | "filter" => $filter 132 | )); 133 | if (!$hlBlockDbRes->getSelectedRowsCount()) { 134 | throw new \Exception('Not found highloadBlock with entityName = " ' . $entityName . ' "'); 135 | } 136 | $hlBlockRow = $hlBlockDbRes->fetch(); 137 | $userFieldEntity = sprintf('HLBLOCK_%s', $hlBlockRow['ID']); 138 | return $userFieldEntity; 139 | } 140 | 141 | } -------------------------------------------------------------------------------- /src/db/generator/providers/Iblock.php: -------------------------------------------------------------------------------- 1 | iblock = new \CIBlock(); 31 | } 32 | 33 | /** 34 | * Генерация создания Информационного блока 35 | * 36 | * generateAddCode 37 | * @param array $IblockCode 38 | * @return bool|string 39 | */ 40 | public function generateAddCode($IblockCode) 41 | { 42 | $return = array(); 43 | $iblockObject = $this->iblock->GetList(array(), array('CODE' => $IblockCode, 'CHECK_PERMISSIONS' => 'N')); 44 | 45 | if ($item = $iblockObject->Fetch()) { 46 | 47 | # Установка групп пользователей 48 | $this->setUserGroupId($item['ID'], $item); 49 | 50 | $item['FIELDS'] = \CIBlock::GetFields($item['ID']); 51 | Helper::unsetFields(array('ID'),$item); 52 | 53 | if ($return[] = $this->getMethodContent('Bim\Db\Iblock\IblockIntegrate', 'Add', array($item))) { 54 | 55 | $IblockProperty = new \CIBlockProperty(); 56 | $iblockPropertyQuery = $IblockProperty->GetList(array(), array('IBLOCK_CODE' => $item['CODE'])); 57 | while ($iblockProperty = $iblockPropertyQuery->Fetch()) { 58 | Helper::unsetFields(array('ID'),$iblockProperty); 59 | 60 | $iblockProperty['IBLOCK_CODE'] = $item['CODE']; 61 | $propertyQuery = \CIBlockPropertyEnum::GetList( 62 | array(), 63 | array("IBLOCK_ID" => $iblockProperty['IBLOCK_ID'], "CODE" => $iblockProperty['CODE'])); 64 | while ($propertyValues = $propertyQuery->Fetch()) { 65 | 66 | Helper::unsetFields(array('ID','PROPERTY_ID'),$propertyValues); 67 | $iblockProperty['VALUES'][] = $propertyValues; 68 | 69 | } 70 | if (!is_null($iblockProperty['LINK_IBLOCK_ID'])) { 71 | $linkedIBlock = $this->iblock->GetList(array(), 72 | array('ID' => $iblockProperty['LINK_IBLOCK_ID'], 'CHECK_PERMISSIONS' => 'N'))->Fetch(); 73 | $iblockProperty['LINK_IBLOCK_CODE'] = $linkedIBlock['CODE']; 74 | } 75 | $return[] = $this->getMethodContent('Bim\Db\Iblock\IblockPropertyIntegrate', 'Add', 76 | array($iblockProperty)); 77 | } 78 | 79 | return implode(PHP_EOL, $return); 80 | } else { 81 | return false; 82 | } 83 | } else { 84 | return false; 85 | } 86 | } 87 | 88 | /** 89 | * Генерация кода обновления инфоблока 90 | * 91 | * @param $params array 92 | * @return mixed 93 | */ 94 | public function generateUpdateCode($params) 95 | { 96 | $this->checkParams($params); 97 | $code = false; 98 | foreach ($this->ownerItemDbData as $iblockData) { 99 | $updateFields = $iblockData; 100 | 101 | Helper::unsetFields(array('ID'),$updateFields); 102 | 103 | $updateFields['FIELDS'] = \CIBlock::GetFields($iblockData['ID']); 104 | $this->setUserGroupId($iblockData['ID'], $iblockData); 105 | 106 | $code = $code . $this->getMethodContent('Bim\Db\Iblock\IblockIntegrate', 'Update', 107 | array($updateFields['CODE'], $updateFields)) . PHP_EOL . PHP_EOL; 108 | } 109 | return $code; 110 | } 111 | 112 | /** 113 | * Метод для генерации кода удаления инфоблока 114 | * 115 | * @param array $iblockCode 116 | * @return mixed 117 | * @internal param array $params 118 | */ 119 | public function generateDeleteCode($iblockCode) 120 | { 121 | return $this->getMethodContent('Bim\Db\Iblock\IblockIntegrate', 'Delete', array($iblockCode)); 122 | } 123 | 124 | /** 125 | * Абстрактный метод проверки передаваемых параметров 126 | * 127 | * @param $params array 128 | * @return mixed 129 | */ 130 | public function checkParams($params) 131 | { 132 | // TODO: Implement checkParams() method. 133 | } 134 | 135 | /** 136 | * Установка групп пользователей 137 | * 138 | * @param $id : ID Информационного блока 139 | * @param $item : Формируемый массив 140 | */ 141 | private function setUserGroupId($id, &$item) 142 | { 143 | $item['GROUP_ID'] = $this->iblock->GetGroupPermissions($id); 144 | $arGroups = Helper::getUserGroups(); 145 | foreach ($item['GROUP_ID'] as $groupId => $right) { 146 | $groupCode = Helper::getUserGroupCode($groupId, $arGroups); 147 | if ($groupCode != null && strlen($groupCode) > 0) { 148 | $item['GROUP_ID'][$groupCode] = $item['GROUP_ID'][$groupId]; 149 | unset($item['GROUP_ID'][$groupId]); 150 | } 151 | } 152 | } 153 | 154 | } -------------------------------------------------------------------------------- /src/cmd/InfoCommand.php: -------------------------------------------------------------------------------- 1 | results as $item) { 47 | if ($item->name == "cjp2600/bim-core") { 48 | $dataPack = $item; 49 | } 50 | } 51 | 52 | if (is_null($dataPack)) { 53 | $info_text = PHP_EOL . 'Bitrix migration (BIM) ' . PHP_EOL . 'http://cjp2600.github.io/bim-core' . PHP_EOL; 54 | } else { 55 | $info_text = PHP_EOL . 'Bitrix migration (BIM)' . PHP_EOL; 56 | foreach ((array)$dataPack as $key => $val) { 57 | $info_text .= Colors::colorize(ucfirst($key), Colors::YELLOW) . ": " . $val . PHP_EOL; 58 | } 59 | $info_text .= PHP_EOL; 60 | } 61 | 62 | # edition 63 | $return[] = Colors::colorize('Edition:', Colors::YELLOW) . " " . $this->checkRedaction(); 64 | $this->info("About bitrix project:"); 65 | 66 | # display 67 | $this->padding(implode(PHP_EOL, $return)); 68 | $this->info("About bim:"); 69 | 70 | # for fun :) 71 | $this->padding($info_text); 72 | } 73 | 74 | /** 75 | * checkRedaction 76 | * @return int|string 77 | */ 78 | public function checkRedaction() 79 | { 80 | $bitrix_modules = $this->getModules(); 81 | $redactions = array( 82 | 'Первый сайт' => array("main", "main"), 83 | 'Старт' => array("main", "search"), 84 | 'Стандарт' => array("main", "photogallery"), 85 | 'Эксперт' => array("main", "advertising"), 86 | 'Малый бизнес' => array("main", "sale"), 87 | 'Бизнес' => array("main", "workflow", "report") 88 | ); 89 | $current_redaction = "не определено"; 90 | foreach ($redactions as $module => $ids) { 91 | foreach ($ids as $id) { 92 | $check = true; 93 | if (!isset($bitrix_modules[$id])) { 94 | $check = false; 95 | } 96 | if ($check) { 97 | $current_redaction = $module; 98 | } 99 | } 100 | } 101 | return $current_redaction; 102 | } 103 | 104 | /** 105 | * getModules 106 | * @return mixed 107 | */ 108 | public function getModules() 109 | { 110 | $folders = array( 111 | "/local/modules", 112 | "/bitrix/modules", 113 | ); 114 | foreach ($folders as $folder) { 115 | $handle = @opendir($_SERVER["DOCUMENT_ROOT"] . $folder); 116 | if ($handle) { 117 | while (false !== ($dir = readdir($handle))) { 118 | if (!isset($arModules[$dir]) && is_dir($_SERVER["DOCUMENT_ROOT"] . $folder . "/" . $dir) && $dir != "." && $dir != ".." && $dir != "main" && strpos($dir, 119 | ".") === false 120 | ) { 121 | $module_dir = $_SERVER["DOCUMENT_ROOT"] . $folder . "/" . $dir; 122 | if ($info = CModule::CreateModuleObject($dir)) { 123 | $arModules[$dir]["MODULE_ID"] = $info->MODULE_ID; 124 | $arModules[$dir]["MODULE_NAME"] = $info->MODULE_NAME; 125 | $arModules[$dir]["MODULE_DESCRIPTION"] = $info->MODULE_DESCRIPTION; 126 | $arModules[$dir]["MODULE_VERSION"] = $info->MODULE_VERSION; 127 | $arModules[$dir]["MODULE_VERSION_DATE"] = $info->MODULE_VERSION_DATE; 128 | $arModules[$dir]["MODULE_SORT"] = $info->MODULE_SORT; 129 | $arModules[$dir]["MODULE_PARTNER"] = (strpos($dir, 130 | ".") !== false) ? $info->PARTNER_NAME : ""; 131 | $arModules[$dir]["MODULE_PARTNER_URI"] = (strpos($dir, 132 | ".") !== false) ? $info->PARTNER_URI : ""; 133 | $arModules[$dir]["IsInstalled"] = $info->IsInstalled(); 134 | } 135 | } 136 | } 137 | closedir($handle); 138 | } 139 | } 140 | uasort($arModules, create_function('$a, $b', 141 | 'if($a["MODULE_SORT"] == $b["MODULE_SORT"]) return strcasecmp($a["MODULE_NAME"], $b["MODULE_NAME"]); return ($a["MODULE_SORT"] < $b["MODULE_SORT"])? -1 : 1;')); 142 | return $arModules; 143 | } 144 | 145 | } 146 | -------------------------------------------------------------------------------- /src/db/generator/providers/IblockProperty.php: -------------------------------------------------------------------------------- 1 | GetList(array(), 37 | array('IBLOCK_CODE' => $IblockCode, 'CODE' => $PropertyCode)); 38 | if ($arIblockProperty = $dbIblockProperty->Fetch()) { 39 | if ($arIblockProperty['PROPERTY_TYPE'] == 'L') { 40 | $arIblockProperty['VALUES'] = $this->getEnumItemList($arIblockProperty['IBLOCK_ID'], 41 | $arIblockProperty['ID']); 42 | } 43 | if (isset($arIblockProperty['LINK_IBLOCK_ID'])) { 44 | $res = $iBlock->GetByID($arIblockProperty['LINK_IBLOCK_ID']); 45 | if ($ar_res = $res->GetNext()) { 46 | unset($arIblockProperty['LINK_IBLOCK_ID']); 47 | $arIblockProperty['LINK_IBLOCK_CODE'] = $ar_res['CODE']; 48 | } 49 | } 50 | unset($arIblockProperty['ID']); 51 | unset($arIblockProperty['IBLOCK_ID']); 52 | $arIblockProperty['IBLOCK_CODE'] = $IblockCode; 53 | 54 | return $this->getMethodContent('Bim\Db\Iblock\IblockPropertyIntegrate', 'Add', array($arIblockProperty)); 55 | } else { 56 | return false; 57 | } 58 | } 59 | 60 | 61 | public function generateUpdateCode($params) 62 | { 63 | //UPDATE 64 | } 65 | 66 | /** 67 | * метод для генерации кода удаления свойства инфоблока 68 | * @param $params array 69 | * @return mixed 70 | */ 71 | public function generateDeleteCode($params) 72 | { 73 | return $this->getMethodContent('Bim\Db\Iblock\IblockPropertyIntegrate', 'Delete', 74 | array($params['iblockCode'], $params['propertyCode'])); 75 | } 76 | 77 | /** 78 | * getEnumItemList 79 | * @param $iblockId 80 | * @param $iblockPropId 81 | * @return array 82 | */ 83 | private function getEnumItemList($iblockId, $iblockPropId) 84 | { 85 | $result = array(); 86 | $propEnumDbRes = \CIBlockPropertyEnum::GetList(array('SORT' => 'ASC'), 87 | array('IBLOCK_ID' => $iblockId, 'PROPERTY_ID' => $iblockPropId)); 88 | if ($propEnumDbRes !== false && $propEnumDbRes->SelectedRowsCount()) { 89 | $index = 0; 90 | while ($propEnum = $propEnumDbRes->Fetch()) { 91 | $result[$index] = array( 92 | 'ID' => $index, 93 | 'VALUE' => $propEnum['VALUE'], 94 | 'XML_ID' => $propEnum['XML_ID'], 95 | 'SORT' => $propEnum['SORT'], 96 | 'DEF' => $propEnum['DEF'] 97 | ); 98 | $index++; 99 | } 100 | } 101 | return $result; 102 | } 103 | 104 | /** 105 | * getIblockCode 106 | * @param $iblockId 107 | * @return bool 108 | */ 109 | private function getIblockCode($iblockId) 110 | { 111 | $iBlock = new \CIBlock(); 112 | $iblockDbRes = $iBlock->GetByID($iblockId); 113 | 114 | if ($iblockDbRes !== false && $iblockDbRes->SelectedRowsCount()) { 115 | $iblockData = $iblockDbRes->Fetch(); 116 | if (strlen($iblockData['CODE'])) { 117 | return $iblockData['CODE']; 118 | } 119 | } 120 | return false; 121 | } 122 | 123 | /** 124 | * checkParams 125 | * @param array $params 126 | * @return mixed|void 127 | * @throws \Exception 128 | */ 129 | public function checkParams($params) 130 | { 131 | $iBlock = new \CIBlock(); 132 | 133 | if (!isset($params['iblockId']) || !strlen($params['iblockId'])) { 134 | throw new BimException('В параметрах не найден iblockId'); 135 | } 136 | 137 | if (!isset($params['propertyId']) || empty($params['propertyId'])) { 138 | throw new BimException('В параметрах не найден propertyId'); 139 | } 140 | 141 | $iblockDbRes = $iBlock->GetByID($params['iblockId']); 142 | if ($iblockDbRes === false || !$iblockDbRes->SelectedRowsCount()) { 143 | throw new BimException('Не найден инфоблок с iblockId = ' . $params['iblockId']); 144 | } 145 | $iblockData = $iblockDbRes->Fetch(); 146 | if (!strlen($iblockData['CODE'])) { 147 | throw new BimException('В инфоблоке не указан символьный код'); 148 | } 149 | $this->ownerItemDbData['iblockData'] = $iblockData; 150 | $this->ownerItemDbData['propertyData'] = array(); 151 | foreach ($params['propertyId'] as $propertyId) { 152 | $propertyDbRes = \CIBlockProperty::GetByID($propertyId); 153 | if ($propertyDbRes === false || !$propertyDbRes->SelectedRowsCount()) { 154 | throw new BimException('Не найдено св-во с id = ' . $propertyId); 155 | } 156 | $propertyData = $propertyDbRes->Fetch(); 157 | if (!strlen($propertyData['CODE'])) { 158 | throw new BimException('В свойстве c id =' . $propertyData['ID'] . ' не указан символьный код.'); 159 | } 160 | $this->ownerItemDbData['propertyData'][] = $propertyData; 161 | } 162 | } 163 | 164 | } 165 | 166 | ?> 167 | -------------------------------------------------------------------------------- /src/db/generator/providers/IblockType.php: -------------------------------------------------------------------------------- 1 | GetByID($IblockTypeId); 43 | if ($arIblockType = $dbIblockType->GetNext()) { 44 | $Iblock = new \CIBlock(); 45 | $dbIblock = $Iblock->GetList(array(), array('TYPE' => $IblockTypeId, 'CHECK_PERMISSIONS' => 'N')); 46 | while ($arIblock = $dbIblock->GetNext()) { 47 | $IblockProperty = new \CIBlockProperty(); 48 | $dbIblockProperty = $IblockProperty->GetList(array(), 49 | array('IBLOCK_CODE' => $arIblock['CODE'], 'CHECK_PERMISSIONS' => 'N')); 50 | while ($arIblockProperty = $dbIblockProperty->GetNext()) { 51 | $dbPropertyValues = \CIBlockPropertyEnum::GetList(array(), 52 | array("IBLOCK_ID" => $arIblockProperty['IBLOCK_ID'], "CODE" => $arIblockProperty['CODE'])); 53 | while ($arPropertyValues = $dbPropertyValues->Fetch()) { 54 | $arIblockProperty['VALUES'][$arPropertyValues['ID']] = $arPropertyValues; 55 | } 56 | 57 | Helper::unsetFields(array( 58 | 'ID', 59 | '~ID', 60 | 'IBLOCK_ID', 61 | '~IBLOCK_ID' 62 | ), $arIblockProperty); 63 | 64 | $arIblockProperty['IBLOCK_CODE'] = $arIblock['CODE']; 65 | 66 | foreach ($arIblockProperty as $k => $v) { 67 | if (strstr($k, "~") || is_null($v)) { 68 | unset($arIblockProperty[$k]); 69 | } 70 | } 71 | if (isset($arIblockProperty['LINK_IBLOCK_ID'])) { 72 | $res = $iBlock->GetList(array(), 73 | array("ID" => $arIblockProperty['LINK_IBLOCK_ID'], 'CHECK_PERMISSIONS' => 'N')); 74 | if ($ar_res = $res->GetNext()) { 75 | unset($arIblockProperty['LINK_IBLOCK_ID']); 76 | $arIblockProperty['LINK_IBLOCK_CODE'] = $ar_res['CODE']; 77 | } 78 | } 79 | $return[] = $this->getMethodContent('Bim\Db\Iblock\IblockPropertyIntegrate', 'Add', 80 | array($arIblockProperty)); 81 | } 82 | foreach ($arIblock as $k => $v) { 83 | if ((strstr($k, "~")) || ($k == 'ID')) { 84 | unset($arIblock[$k]); 85 | } 86 | } 87 | $return[] = $this->getMethodContent('Bim\Db\Iblock\IblockIntegrate', 'Add', array($arIblock)); 88 | } 89 | foreach ($arIblockType as $k => $v) { 90 | if (strstr($k, "~") || is_null($v)) { 91 | unset($arIblockType[$k]); 92 | } 93 | } 94 | $rsLang = $lang->GetList($by = "lid", $order = "desc"); 95 | while ($arLang = $rsLang->Fetch()) { 96 | $arTypeLang = $CIblockType->GetByIDLang($IblockTypeId, $arLang['LID']); 97 | $arIblockType["LANG"][$arLang['LID']] = array( 98 | 'NAME' => $arTypeLang['NAME'], 99 | 'SECTION_NAME' => $arTypeLang['SECTION_NAME'], 100 | 'ELEMENT_NAME' => $arTypeLang['ELEMENT_NAME'], 101 | ); 102 | } 103 | $return[] = $this->getMethodContent('Bim\Db\Iblock\IblockTypeIntegrate', 'Add', array($arIblockType)); 104 | $return = array_reverse($return); 105 | 106 | return implode(PHP_EOL, $return); 107 | } else { 108 | return false; 109 | } 110 | } 111 | 112 | /** 113 | * Генерация кода обновления 114 | * 115 | * generateUpdateCode 116 | * @param array $params 117 | * @return mixed|void 118 | */ 119 | public function generateUpdateCode($params) 120 | { 121 | // UPDATE .. 122 | } 123 | 124 | /** 125 | * метод для генерации кода удаления 126 | * 127 | * generateDeleteCode 128 | * @param array $IblockTypeId 129 | * @return string 130 | */ 131 | public function generateDeleteCode($IblockTypeId) 132 | { 133 | return $this->getMethodContent('Bim\Db\Iblock\IblockTypeIntegrate', 'Delete', array($IblockTypeId)); 134 | } 135 | 136 | /** 137 | * getLangData 138 | * @param $iblockTypeId 139 | * @return array 140 | */ 141 | private function getLangData($iblockTypeId) 142 | { 143 | $CIblockType = new \CIBlockType(); 144 | $lang = new \CLanguage(); 145 | 146 | $result = array(); 147 | $langDbRes = $lang->GetList($by = "lid", $order = "desc", Array()); 148 | while ($langData = $langDbRes->Fetch()) { 149 | $typeLangItemTmp = $CIblockType->GetByIDLang($iblockTypeId, $langData['LID']); 150 | $typeLangItem = array(); 151 | foreach ($typeLangItemTmp as $key => $value) { 152 | if (strstr($key, '~')) { 153 | continue; 154 | } 155 | $typeLangItem[$key] = $value; 156 | } 157 | 158 | $result[$langData['LID']] = $typeLangItem; 159 | } 160 | return $result; 161 | } 162 | 163 | /** 164 | * Абстрактный метод проверки передаваемых параметров 165 | * 166 | * checkParams 167 | * @param array $params 168 | * @return mixed|void 169 | * @throws \Exception 170 | */ 171 | public function checkParams($params) 172 | { 173 | $CIblockType = new \CIBlockType(); 174 | if (!isset($params['iblockTypeId']) || !strlen($params['iblockTypeId'])) { 175 | throw new BimException('В параметрах не найден iblockTypeId'); 176 | } 177 | $iblockTypeDbRes = $CIblockType->GetByID($params['iblockTypeId']); 178 | if ($iblockTypeDbRes === false || !$iblockTypeDbRes->SelectedRowsCount()) { 179 | throw new BimException('В системе не найден тип инфоблока с id = ' . $params['iblockTypeId']); 180 | } 181 | $this->ownerItemDbData = $iblockTypeDbRes->Fetch(); 182 | } 183 | 184 | } -------------------------------------------------------------------------------- /src/cmd/ListCommand.php: -------------------------------------------------------------------------------- 1 | migrationPath = (isset($options['migration_path'])) ? $options['migration_path'] : null; 34 | 35 | $list = $this->getDirectoryTree($this->getMigrationPath(), "php"); 36 | 37 | # get filename 38 | $file = (isset($options['f'])) ? true : false; 39 | $filter_apply = (isset($options['a'])) ? $options['a'] : false; 40 | $filter_new = (isset($options['n'])) ? $options['n'] : false; 41 | $filter_from = (isset($options['from'])) ? $options['from'] : false; 42 | $filter_to = (isset($options['to'])) ? $options['to'] : false; 43 | $filter_from = ($filter_from) ? strtotime($filter_from) : false; 44 | $filter_to = ($filter_to) ? strtotime($filter_to) : false; 45 | 46 | #check tag list 47 | $filer_tag = (isset($options['tag'])) ? $options['tag'] : false; 48 | 49 | if (!empty($list)) { 50 | 51 | $headers = array('№', 'id', 'Author', 'Date'); 52 | if ($file) { 53 | $headers[] = 'File'; 54 | } 55 | 56 | $headers[] = 'Description'; 57 | $headers[] = 'Status'; 58 | 59 | $table = new \cli\Table(); 60 | $table->setHeaders($headers); 61 | 62 | $count = 0; 63 | $applied = 0; 64 | $new = 0; 65 | $i = 1; 66 | $return_array_new = array(); 67 | $return_array_apply = array(); 68 | 69 | #filter 70 | $is_filter = false; 71 | $this->prepareFilter($list, $filter_from, $filter_to, $filer_tag, $options, $is_filter); 72 | 73 | foreach ($list as $id => $data) { 74 | $count++; 75 | 76 | $row = $data['file']; 77 | $name = $data['name']; 78 | 79 | # check in db 80 | $is_new = (!$this->checkInDb($id)); 81 | $class_name = "Migration" . $id; 82 | include_once "" . $this->getMigrationPath() . $row . ""; 83 | 84 | $color = ConsoleKit\Colors::GREEN; 85 | $status = ConsoleKit\Colors::colorize('apply', Colors::GREEN); 86 | 87 | # check in db 88 | if ($is_new) { 89 | $new++; 90 | $color = ConsoleKit\Colors::RED; 91 | $status = ConsoleKit\Colors::colorize('new', Colors::RED); 92 | } else { 93 | $applied++; 94 | } 95 | 96 | $rowArray = array( 97 | ConsoleKit\Colors::colorize($i, $color), 98 | ConsoleKit\Colors::colorize($id, $color), 99 | $data['author'], 100 | date("d.m.y G:h", $data['date']) 101 | ); 102 | if ($file) { 103 | $rowArray[] = $row; 104 | } 105 | $rowArray[] = $data['description']; 106 | $rowArray[] = $status; 107 | 108 | if ($is_new) { 109 | $return_array_new[] = $rowArray; 110 | } else { 111 | $return_array_apply[] = $rowArray; 112 | } 113 | 114 | $i++; 115 | } 116 | 117 | if ($filter_new) { 118 | $table->setRows($return_array_new); 119 | } else { 120 | if ($filter_apply) { 121 | $table->setRows($return_array_apply); 122 | } else { 123 | $table->setRows(array_merge($return_array_apply, $return_array_new)); 124 | } 125 | } 126 | 127 | $displayArray = $table->getDisplayLines(); 128 | if (!empty($displayArray)) { 129 | $table->display(); 130 | } 131 | 132 | if (!$is_filter) { 133 | # count info 134 | $return[] = Colors::colorize('New:', Colors::RED) . " " . $new; 135 | $return[] = Colors::colorize('Applied:', Colors::GREEN) . " " . $applied; 136 | $return[] = "Count: " . $count; 137 | } 138 | 139 | # display 140 | $this->padding(implode(PHP_EOL, $return)); 141 | 142 | } else { 143 | $this->info('Empty migration'); 144 | } 145 | } 146 | 147 | /** 148 | * prepareFilter 149 | * @param $list 150 | * @param $filter_from 151 | * @param $filter_to 152 | * @param $filer_tag 153 | * @param $options 154 | * @param $is_filter 155 | */ 156 | public function prepareFilter(&$list, $filter_from, $filter_to, $filer_tag, $options, &$is_filter) 157 | { 158 | if ($filter_from || $filter_to) { 159 | $this->padding("Filter to the list:" . $this->color(PHP_EOL . "from: " . $options['from'] . PHP_EOL . "to: " . $options['to'], 160 | Colors::YELLOW)); 161 | $newArrayList = array(); 162 | foreach ($list as $id => $data) { 163 | if ($filter_from && $filter_to) { 164 | if ($id >= $filter_from && $id <= $filter_to) { 165 | $newArrayList[$id] = $data; 166 | } 167 | } else { 168 | if ($filter_from && !$filter_to) { 169 | if ($id >= $filter_from) { 170 | $newArrayList[$id] = $data; 171 | } 172 | } else { 173 | if (!$filter_from && $filter_to) { 174 | if ($id <= $filter_to) { 175 | $newArrayList[$id] = $data; 176 | } 177 | } 178 | } 179 | } 180 | } 181 | if (!empty($newArrayList)) { 182 | $is_filter = true; 183 | $list = $newArrayList; 184 | } else { 185 | $list = array(); 186 | } 187 | } 188 | # check to tag list 189 | if ($filer_tag) { 190 | $newArrayList = array(); 191 | foreach ($list as $id => $data) { 192 | if (!empty($data['tags'])) { 193 | if (in_array(strtolower($filer_tag), $data['tags'])) { 194 | $newArrayList[$id] = $data; 195 | } 196 | } 197 | } 198 | if (!empty($newArrayList)) { 199 | $is_filter = true; 200 | $list = $newArrayList; 201 | } else { 202 | $list = array(); 203 | } 204 | } 205 | } 206 | 207 | 208 | } 209 | -------------------------------------------------------------------------------- /src/Export/Session.php: -------------------------------------------------------------------------------- 1 | sessionDBtFileName; 40 | } 41 | 42 | /** 43 | * @param null $sessionDBtFileName 44 | */ 45 | public function setSessionDBtFileName($sessionDBtFileName) 46 | { 47 | $this->sessionDBtFileName = $sessionDBtFileName; 48 | } 49 | 50 | /** 51 | * @return null 52 | */ 53 | public function getSessionExportId() 54 | { 55 | return $this->sessionExportId; 56 | } 57 | 58 | /** 59 | * @param null $sessionExportId 60 | */ 61 | public function setSessionExportId($sessionExportId) 62 | { 63 | $this->sessionExportId = $sessionExportId; 64 | } 65 | 66 | 67 | public function init() 68 | { 69 | $this->setSessionExportId(date("d_m_Y_H_i_s")); 70 | if (!file_exists($this->getMigrationPath() . self::EXPORT_FOLDER)) { 71 | mkdir($this->getMigrationPath() . self::EXPORT_FOLDER, 0777); 72 | } 73 | 74 | $sessionPath = $this->getMigrationPath() . self::EXPORT_FOLDER . "/" . $this->getSessionExportId(); 75 | if (!file_exists($sessionPath)) { 76 | mkdir($sessionPath, 0777); 77 | } 78 | 79 | $this->setSessionExportPathName($sessionPath); 80 | $this->setSessionExportFileName(self::EXPORT_FILE_PREFIX . $this->getSessionExportId() . ".tar.gz"); 81 | $this->setSessionDBtFileName($this->getSessionExportPathName() . '/' . 'db_' . self::EXPORT_FILE_PREFIX . $this->getSessionExportId() . '.sql'); 82 | } 83 | 84 | /** 85 | * @return null 86 | */ 87 | public function getSessionExportPathName() 88 | { 89 | return $this->sessionExportPathName; 90 | } 91 | 92 | /** 93 | * @param null $sessionExportPathName 94 | */ 95 | public function setSessionExportPathName($sessionExportPathName) 96 | { 97 | $this->sessionExportPathName = $sessionExportPathName; 98 | } 99 | 100 | /** 101 | * @return null 102 | */ 103 | public function getSessionExportFileName() 104 | { 105 | return $this->sessionExportFileName; 106 | } 107 | 108 | /** 109 | * @param null $sessionExportFileName 110 | */ 111 | public function setSessionExportFileName($sessionExportFileName) 112 | { 113 | $this->sessionExportFileName = $sessionExportFileName; 114 | } 115 | 116 | /** 117 | * @return string 118 | */ 119 | public function getFullPath() 120 | { 121 | return $this->getSessionExportPathName() . '/' . $this->getSessionExportFileName(); 122 | } 123 | 124 | /** 125 | * packCore 126 | * 127 | * @return \Alchemy\Zippy\Archive\ArchiveInterface 128 | * @throws BimException 129 | */ 130 | public function packCore() 131 | { 132 | try { 133 | $this->dumpMysql(); 134 | 135 | $zippy = Zippy::load(); 136 | $archive = $zippy->create($this->getFullPath(), $this->getBitrixCore(), true); 137 | 138 | $this->dataResponse[] = $this->color(strtoupper("completed"), 139 | Colors::GREEN) . " : " . $this->getFullPath(); 140 | 141 | $this->saveInfoToJson(); 142 | 143 | $this->dataResponse[] = $this->color(strtoupper("completed"), 144 | Colors::GREEN) . " : " . $this->getSessionDBtFileName(); 145 | 146 | return $archive; 147 | } catch (RuntimeException $e) { 148 | $this->clearExport(); 149 | throw new BimException("EXPORT ERROR: " . $e->getMessage()); 150 | } 151 | } 152 | 153 | /** 154 | * dumpMysql 155 | */ 156 | public function dumpMysql() 157 | { 158 | require_once($_SERVER["DOCUMENT_ROOT"] . "/vendor/cjp2600/bim-core/src/Export/Dump/dump.php"); 159 | 160 | if (!defined("START_EXEC_TIME")) { 161 | define("START_EXEC_TIME", microtime(true)); 162 | } 163 | define('NO_TIME', true); 164 | 165 | IntOption("dump_base_skip_stat",1); 166 | IntOption("dump_base_skip_search",1); 167 | IntOption("dump_base_skip_log",1); 168 | 169 | makeLocalDump($this->getSessionDBtFileName()); 170 | } 171 | 172 | /** 173 | * getBitrixCore 174 | * @return array 175 | */ 176 | public function getBitrixCore() 177 | { 178 | $excludeFolder = array("cache", "managed_cache", "stack_cache"); 179 | $dirs = array_diff(scandir($_SERVER["DOCUMENT_ROOT"] . "/bitrix/"), Array(".", "..")); 180 | $folder = array(); 181 | foreach ($dirs as $dir) { 182 | if (in_array($dir, $excludeFolder)) { 183 | continue; 184 | } 185 | $folder[] = $_SERVER["DOCUMENT_ROOT"] . "/bitrix/" . $dir; 186 | } 187 | return $folder; 188 | } 189 | 190 | /** 191 | * saveInfoToJson 192 | */ 193 | private function saveInfoToJson() 194 | { 195 | $data = []; 196 | $exportJson = $this->getMigrationPath() . self::EXPORT_FOLDER . "/export.json"; 197 | if (file_exists($exportJson)) { 198 | $data = json_decode(file_get_contents($exportJson), true); 199 | unlink($exportJson); 200 | } 201 | 202 | $dataItem = array( 203 | "id" => $this->getSessionExportId(), 204 | "core_name" => $this->getSessionExportFileName(), 205 | "core_path" => $this->getFullPath(), 206 | "db_file" => $this->getSessionDBtFileName(), 207 | ); 208 | $data['items'][] = $dataItem; 209 | file_put_contents($exportJson, json_encode($data)); 210 | } 211 | 212 | private function clearExport() 213 | { 214 | $this->deleteDirectory($this->getSessionExportPathName()); 215 | } 216 | 217 | /** 218 | * @param $dir 219 | * @return bool 220 | */ 221 | function deleteDirectory($dir) 222 | { 223 | if (!file_exists($dir)) { 224 | return true; 225 | } 226 | if (!is_dir($dir)) { 227 | return unlink($dir); 228 | } 229 | foreach (scandir($dir) as $item) { 230 | if ($item == '.' || $item == '..') { 231 | continue; 232 | } 233 | if (!$this->deleteDirectory($dir . DIRECTORY_SEPARATOR . $item)) { 234 | return false; 235 | } 236 | } 237 | return rmdir($dir); 238 | } 239 | 240 | /** 241 | * @return mixed 242 | */ 243 | public function getDataResponse() 244 | { 245 | return implode("\n", $this->dataResponse); 246 | } 247 | 248 | /** 249 | * getSqlBatchByExport 250 | * 251 | * @param $args 252 | * @param $json 253 | * @return array|bool 254 | * @throws BimException 255 | */ 256 | public function getSqlBatchByExport($args, $json) 257 | { 258 | global $DB; 259 | 260 | if (!isset($args[1])) { 261 | throw new BimException("number 0f export not fount. Example: pgp vendor/bin/bim export install 1"); 262 | } 263 | 264 | if (empty($json)) { 265 | throw new BimException("empty export.json"); 266 | 267 | } 268 | $num = $args[1]; 269 | if (isset($json['items'][$num])) { 270 | $dump = $json['items'][$num]['db_file']; 271 | 272 | if (!file_exists($dump) || !is_file($dump)) { 273 | throw new BimException("File " . $dump . " is not found."); 274 | } 275 | 276 | $contents = file_get_contents($dump); 277 | $sqlBatch = $DB->ParseSqlBatch($contents, false); 278 | 279 | return $sqlBatch; 280 | } 281 | return false; 282 | } 283 | 284 | } -------------------------------------------------------------------------------- /src/cmd/DownCommand.php: -------------------------------------------------------------------------------- 1 | migrationPath = (isset($options['migration_path'])) ? $options['migration_path'] : null; 46 | 47 | $list = $this->getDirectoryTree($this->getMigrationPath(), "php"); 48 | krsort($list); #по убыванию 49 | if (!empty($list)) { 50 | foreach ($list as $id => $data) { 51 | $row = $data['file']; 52 | $name = $data['name']; 53 | 54 | # check in db 55 | $is_new = (!$this->checkInDb($id)); 56 | $class_name = "Migration" . $id; 57 | 58 | if ($is_new) { 59 | $return_array_new[$id] = array( 60 | $class_name, 61 | "" . $this->getMigrationPath() . $row . "", 62 | $name, 63 | $data['tags'] 64 | ); 65 | } else { 66 | $return_array_apply[$id] = array( 67 | $class_name, 68 | "" . $this->getMigrationPath() . $row . "", 69 | $name, 70 | $data['tags'] 71 | ); 72 | } 73 | } 74 | 75 | # filer 76 | $is_filter = false; 77 | $f_id = false; 78 | if ((isset($options['id']))) { 79 | if (is_string($options['id'])) { 80 | $f_id = $options['id']; 81 | } else { 82 | $dialog = new \ConsoleKit\Widgets\Dialog($this->console); 83 | $f_id = $dialog->ask('Type migration id:', $f_id); 84 | } 85 | } else { 86 | if (isset($args[0])) { 87 | if (is_string($args[0])) { 88 | $f_id = $args[0]; 89 | } 90 | } 91 | } 92 | #check tag list 93 | $filer_tag = (isset($options['tag'])) ? $options['tag'] : false; 94 | 95 | if ($f_id) { 96 | if (isset ($return_array_apply[$f_id])) { 97 | $is_filter = true; 98 | $return_array_apply = array($f_id => $return_array_apply[$f_id]); 99 | } else { 100 | if (isset ($return_array_apply[$f_id])) { 101 | $logging_output[] = "Migration " . $f_id . " - is already applied"; 102 | throw new Exception("Migration " . $f_id . " - is already applied"); 103 | } else { 104 | $logging_output[] = "Migration " . $f_id . " - is not found in applied list"; 105 | throw new Exception("Migration " . $f_id . " - is not found in applied list"); 106 | } 107 | } 108 | } 109 | 110 | # check to tag list 111 | if ($filer_tag) { 112 | $this->padding("down migration for tag : " . $filer_tag); 113 | $newArrayList = array(); 114 | foreach ($return_array_apply as $id => $mig) { 115 | if (!empty($mig[3])) { 116 | if (in_array(strtolower($filer_tag), $mig[3])) { 117 | $newArrayList[$id] = $mig; 118 | } 119 | } 120 | } 121 | if (!empty($newArrayList)) { 122 | $is_filter = true; 123 | $return_array_apply = $newArrayList; 124 | } else { 125 | $return_array_apply = array(); 126 | } 127 | } 128 | 129 | if (!$is_filter) { 130 | $this->askDoOperation((isset($options['force'])),"Are you sure you want to remove all applied migration"); 131 | } 132 | 133 | if (empty($return_array_apply)) { 134 | $logging_output[] = "Applied migrations list is empty."; 135 | $this->info("Applied migrations list is empty."); 136 | if ($logging) { 137 | $this->logging($logging_output, "down"); 138 | } 139 | return false; 140 | } 141 | 142 | $time_start = microtime(true); 143 | $this->info(" <- Start revert migration:"); 144 | $this->writeln(''); 145 | foreach ($return_array_apply as $id => $mig) { 146 | include_once "" . $mig[1] . ""; 147 | if ((method_exists($mig[0], "down"))) { 148 | try { 149 | # start transaction 150 | $DB->StartTransaction(); 151 | if (false !== $mig[0]::down()) { 152 | if (Bim\Db\Entity\MigrationsTable::isExistsInTable($id)) { 153 | if (Bim\Db\Entity\MigrationsTable::delete($id)) { 154 | # commit transaction 155 | $DB->Commit(); 156 | $this->writeln($this->color(" - revert : " . $mig[2], Colors::GREEN)); 157 | $logging_output[] = "revert : " . $mig[2]; 158 | } else { 159 | # rollback transaction 160 | $DB->Rollback(); 161 | $logging_output[] = "error : " . $mig[2] . " - Error delete in migration table"; 162 | throw new Exception("Error delete in migration table"); 163 | } 164 | } 165 | } else { 166 | $this->writeln(Colors::colorize(" - error : " . $mig[2], 167 | Colors::RED) . " " . Colors::colorize("(Method Down return false)", 168 | Colors::YELLOW)); 169 | $logging_output[] = "error : " . $mig[2] . " - Method Down return false"; 170 | } 171 | } catch (Exception $e) { 172 | if ((isset($options['debug']))) { 173 | $debug = "[" . $e->getFile() . ">" . $e->getLine() . "] "; 174 | } else { 175 | $debug = ""; 176 | } 177 | # rollback transaction 178 | $DB->Rollback(); 179 | $this->writeln(Colors::colorize(" - error : " . $mig[2], 180 | Colors::RED) . " " . Colors::colorize("( " . $debug . "" . $e->getMessage() . " )", 181 | Colors::YELLOW)); 182 | $logging_output[] = "error : " . $mig[2] . " " . $debug . $e->getMessage(); 183 | } 184 | } 185 | } 186 | 187 | $time_end = microtime(true); 188 | $time = $time_end - $time_start; 189 | $this->writeln(''); 190 | $this->info(" <- " . round($time, 2) . "s"); 191 | $logging_output[] = "End time - " . round($time, 2) . "s"; 192 | if ($logging) { 193 | $this->logging($logging_output, "down"); 194 | } 195 | } else { 196 | $this->info('Empty migration'); 197 | } 198 | } 199 | } -------------------------------------------------------------------------------- /src/cmd/UpdateCommand.php: -------------------------------------------------------------------------------- 1 | migrationPath = (isset($options['migration_path'])) ? $options['migration_path'] : null; 55 | 56 | $list = $this->getDirectoryTree($this->getMigrationPath(), "php"); 57 | ksort($list); # по возрастанию 58 | if (!empty($list)) { 59 | foreach ($list as $id => $data) { 60 | $row = $data['file']; 61 | $name = $data['name']; 62 | 63 | # check in db 64 | $is_new = (!$this->checkInDb($id)); 65 | $class_name = "Migration" . $id; 66 | 67 | if ($is_new) { 68 | $return_array_new[$id] = array( 69 | $class_name, 70 | "" . $this->getMigrationPath() . $row . "", 71 | $name, 72 | $data['tags'] 73 | ); 74 | } else { 75 | $return_array_apply[$id] = array( 76 | $class_name, 77 | "" . $this->getMigrationPath() . $row . "", 78 | $name, 79 | $data['tags'] 80 | ); 81 | } 82 | } 83 | 84 | # filer 85 | $f_id = false; 86 | $is_filter = false; 87 | if ((isset($options['id']))) { 88 | $is_filter = true; 89 | if (is_string($options['id'])) { 90 | $f_id = $options['id']; 91 | } else { 92 | $dialog = new \ConsoleKit\Widgets\Dialog($this->console); 93 | $f_id = $dialog->ask('Type migration id:', $f_id); 94 | } 95 | } else { 96 | if (isset($args[0])) { 97 | $is_filter = true; 98 | if (is_string($args[0])) { 99 | $f_id = $args[0]; 100 | } 101 | } 102 | } 103 | #check tag list 104 | $filer_tag = (isset($options['tag'])) ? $options['tag'] : false; 105 | 106 | if ($f_id) { 107 | if (isset ($return_array_new[$f_id])) { 108 | $return_array_new = array($f_id => $return_array_new[$f_id]); 109 | } else { 110 | if (isset ($return_array_apply[$f_id])) { 111 | $logging_output[] = "Migration " . $f_id . " - is already applied"; 112 | throw new Exception("Migration " . $f_id . " - is already applied"); 113 | } else { 114 | $logging_output[] = "Migration " . $f_id . " - is not found in new migrations list"; 115 | throw new Exception("Migration " . $f_id . " - is not found in new migrations list"); 116 | } 117 | } 118 | } 119 | # check to tag list 120 | if ($filer_tag) { 121 | $is_filter = true; 122 | $this->padding("up migration for tag : " . $filer_tag); 123 | $newArrayList = array(); 124 | foreach ($return_array_new as $id => $mig) { 125 | if (!empty($mig[3])) { 126 | if (in_array(strtolower($filer_tag), $mig[3])) { 127 | $newArrayList[$id] = $mig; 128 | } 129 | } 130 | } 131 | if (!empty($newArrayList)) { 132 | $return_array_new = $newArrayList; 133 | } else { 134 | $return_array_new = array(); 135 | } 136 | } 137 | 138 | if (!$is_filter) { 139 | $this->askDoOperation((isset($options['force']))); 140 | } 141 | 142 | 143 | if (empty($return_array_new)) { 144 | $logging_output[] = "New migrations list is empty."; 145 | $this->info("New migrations list is empty."); 146 | if ($logging) { 147 | $this->logging($logging_output); 148 | } 149 | return false; 150 | } 151 | 152 | $time_start = microtime(true); 153 | $this->info(" -> Start applying migration:"); 154 | $this->writeln(''); 155 | foreach ($return_array_new as $id => $mig) { 156 | include_once "" . $mig[1] . ""; 157 | # check bim migration. 158 | if ((method_exists($mig[0], "up"))) { 159 | try { 160 | # start transaction 161 | $DB->StartTransaction(); 162 | # call up function 163 | if (false !== $mig[0]::up()) { 164 | if (!Bim\Db\Entity\MigrationsTable::isExistsInTable($id)) { 165 | if (Bim\Db\Entity\MigrationsTable::add($id)) { 166 | # commit transaction 167 | $DB->Commit(); 168 | $this->writeln($this->color(" - applied : " . $mig[2], Colors::GREEN)); 169 | $logging_output[] = "applied : " . $mig[2]; 170 | } else { 171 | # rollback transaction 172 | $DB->Rollback(); 173 | $logging_output[] = "error : " . $mig[2] . " - Add in migration table error"; 174 | throw new Exception("add in migration table error"); 175 | } 176 | } 177 | } else { 178 | $this->writeln(Colors::colorize(" - error : " . $mig[2], 179 | Colors::RED) . " " . Colors::colorize("(Method Up return false)", Colors::YELLOW)); 180 | $logging_output[] = "error : " . $mig[2] . " - Method Up return false"; 181 | } 182 | } catch (Exception $e) { 183 | if ((isset($options['debug']))) { 184 | $debug = "[" . $e->getFile() . ">" . $e->getLine() . "] "; 185 | } else { 186 | $debug = ""; 187 | } 188 | # rollback transaction 189 | $DB->Rollback(); 190 | $this->writeln(Colors::colorize(" - error : " . $mig[2], 191 | Colors::RED) . " " . Colors::colorize("( " . $debug . "" . $e->getMessage() . ")", 192 | Colors::YELLOW)); 193 | $logging_output[] = "error : " . $mig[2] . "( " . $debug . "" . $e->getMessage() . " )"; 194 | } 195 | } 196 | } 197 | $time_end = microtime(true); 198 | $time = $time_end - $time_start; 199 | $this->writeln(''); 200 | $this->info(" -> " . round($time, 2) . "s"); 201 | $logging_output[] = "End time - " . round($time, 2) . "s"; 202 | if ($logging) { 203 | $this->logging($logging_output); 204 | } 205 | } else { 206 | $this->info('Empty migration'); 207 | } 208 | } 209 | 210 | 211 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # Bitrix Migration (BIM) 3 | 4 | [![Latest Stable Version](https://poser.pugx.org/cjp2600/bim-core/v/stable.svg)](https://packagist.org/packages/cjp2600/bim-core) [![Total Downloads](https://poser.pugx.org/cjp2600/bim-core/downloads.svg)](https://packagist.org/packages/cjp2600/bim-core) [![Latest Unstable Version](https://poser.pugx.org/cjp2600/bim-core/v/unstable.svg)](https://packagist.org/packages/cjp2600/bim-core) [![License](https://poser.pugx.org/cjp2600/bim-core/license.svg)](https://packagist.org/packages/cjp2600/bim-core) 5 | 6 | Версионная миграция структуры БД для **[1С Битрикс CMS](http://bitrix.ru)** 7 | 8 | - [Установка](#install) 9 | * [Автоматическая установка](#auto) 10 | * [Ручная установка](#hand) 11 | - [Настройка](#prop) 12 | - [Выполнение - bim up](#up) 13 | - [Отмена - bim down](#down) 14 | - [Вывод списка - bim ls](#ls) 15 | - [Создание - bim gen](#gen) 16 | * [Создание пустой миграции](#gen_empty) 17 | * [Создание миграционного кода по наличию](#gen_nal) 18 | * Модуль (iblock,highloadblock) 19 | * [IblockType](#iblocktype) 20 | * [Iblock](#iblock) 21 | * [IblockProperty](#iblockproperty) 22 | * [Highloadblock](#hlblock) 23 | * [HighloadblockField](#hlblockfield) 24 | * Модуль (main) 25 | * [Group](#main_group) 26 | * [Site](#main_site) 27 | * [Режим multi - bim gen multi](#multi) 28 | * [Тегирование миграций](#tag) 29 | * [Логирование](#logging) 30 | - [Информация о проекте - bim info](#info) 31 | 32 | # 1 Установка 33 | 34 | ### 1.1 Автоматическая установка 35 | 36 | Для установки и инициализации bim для bitrix проекта необходимо выполнить следующиие действия из корня проекта: 37 | 38 | - Установить Composer: 39 | ``` 40 | curl -s https://getcomposer.org/installer | php 41 | ``` 42 | - Выполнить установочный скрипт: 43 | 44 | ``` bash 45 | php -r "readfile('https://raw.githubusercontent.com/cjp2600/bim/master/install');" | php 46 | ``` 47 | > Автоматические действия установщика: 48 | 49 | > 1. Добавление файла bim в корень проекта. 50 | > 2. Инициализация **composer autoloader** в файле **init.php** 51 | > 3. Создание файла **composer.json** в корне проекта со ссылкой на bim репозиторий **"require": { "cjp2600/bim-core": ">=1.0.0"}** 52 | 53 | ### 1.2 Ручная установка 54 | 55 | Для ручной установки bim необходимо: 56 | 57 | - Установить Composer: 58 | 59 | ``` 60 | curl -s https://getcomposer.org/installer | php 61 | ``` 62 | - Добавть инициализацию composer (в файл init.php добавить запись): 63 | 64 | ```bash 65 | if (file_exists($_SERVER['DOCUMENT_ROOT'] . '/vendor/autoload.php')) 66 | require_once $_SERVER['DOCUMENT_ROOT'] . '/vendor/autoload.php'; 67 | ``` 68 | 69 | - Создать в корне сайта файл **composer.json** с содержимым: 70 | 71 | ```json 72 | { 73 | "require": { 74 | "cjp2600/bim-core": ">=1.0.0" 75 | } 76 | } 77 | ``` 78 | 79 | - В **.gitignore** добавить запись: 80 | 81 | ``` 82 | /vendor 83 | ``` 84 | 85 | - Done! :): 86 | 87 | ``` php 88 | php vendor/bin/bim info 89 | ``` 90 | 91 | # 2 Настройка 92 | 93 | Для начала работы обновляем **composer** и создаем миграционную таблицу в БД: 94 | 95 | ``` bash 96 | php composer.phar update 97 | ``` 98 | Создаём таблицу миграций : 99 | 100 | ```bash 101 | php bim init 102 | ``` 103 | 104 | 105 | # 3 Выполнение миграций [BIM UP] 106 | 107 | - Общее выполнение: 108 | ```bash 109 | php bim up 110 | ``` 111 | Выполняет полный список не выполненых либо ранее отмененных миграционных классов отсортированых по названию (**timestamp**). 112 | 113 | - Еденичное выполнение: 114 | ```bash 115 | php bim up 1423660766 116 | ``` 117 | Выполняет указанную в праметрах миграцию. 118 | 119 | - Выполнение по временному периоду: 120 | ```bash 121 | php bim up --from="29.01.2015 00:01" --to="29.01.2015 23:55" 122 | ``` 123 | - Выполнение по тегу: 124 | ```bash 125 | php bim up --tag=iws-123 126 | ``` 127 | Выполняет все миграции где найден указанный тег в описании. 128 | 129 | - Логирование: 130 | ``` bash 131 | php bim up --logging 132 | ``` 133 | 134 | # 4 Отмена выполненых миграций [BIM DOWN] 135 | 136 | - Общая отмена: 137 | ```bash 138 | php bim down 139 | ``` 140 | Отменяет весь список выполненных миграционных классов. 141 | 142 | - Еденичная отмена: 143 | ``` bash 144 | php bim down 1423660766 145 | ``` 146 | Отменяет указанную в праметрах миграцию. 147 | 148 | - Отмена по временному периоду: 149 | ```bash 150 | php bim down --from="29.01.2015 00:01" --to="29.01.2015 23:55" 151 | ``` 152 | - Отмена по тегу: 153 | ```bash 154 | php bim down --tag=iws-123 155 | ``` 156 | Отменяет все миграции где найден указанный тег в описании. 157 | 158 | - Логирование: 159 | ``` bash 160 | php bim down --logging 161 | ``` 162 | 163 | # 5 Вывод списка миграций [BIM LS] 164 | - Общей список: 165 | ```bash 166 | php bim ls 167 | ``` 168 | - Список выполненных миграций: 169 | ```bash 170 | php bim ls --a 171 | ``` 172 | - Список отменённых миграций: 173 | ```bash 174 | php bim ls --n 175 | ``` 176 | - Список миграций за определённый период времени: 177 | ```bash 178 | php bim ls --from="29.01.2015 00:01" --to="29.01.2015 23:55" 179 | ``` 180 | - Список миграций по тегу: 181 | ```bash 182 | php bim ls --tag=iws-123 183 | ``` 184 | 185 | # 6 Создание новых миграций [BIM GEN] 186 | 187 | Существует два способа создания миграций: 188 | 189 | ## 1) Создание пустой миграции: 190 | Создается пустой шаблон миграционного класса. Структура класса определена интерфейсом *Bim/Revision* и включает следующие 191 | обязательные методы: 192 | 193 | - *up();* - выполнение 194 | - *down();* - отмена 195 | - *getDescription();* - получения описания. 196 | - *getAuthor();* - получение автора. 197 | 198 | Дополнительно запрашивается: 199 | - [Description] 200 | 201 | **Пример:** 202 | 203 | ``` bash 204 | php bim gen 205 | ``` 206 | Также возможно передать description опционально: 207 | ``` bash 208 | php bim gen --d="new description #iws-123" 209 | ``` 210 | 211 | > Далее создается файл миграции вида: */[migrations_path]/[timestamp].php 212 | 213 | > Например: /migrations/123412434.php 214 | 215 | ## 2) Создание миграционного кода по наличию: 216 | 217 | Создается код развертывания/отката существующего элемента схемы bitrix БД. 218 | На данный момент доступно генерация по наличию для следующих элементов bitrix БД: 219 | 220 | ### 2.1 IblockType *( php bim gen IblockType:[add|delete] )*: 221 | 222 | Создается Миграционный код "**Типа ИБ**" включая созданные для него *(UserFields, IBlock, IblockProperty)* 223 | 224 | Дополнительно запрашивается: 225 | - [IBLOCK_TYPE_ID] 226 | - [Description] 227 | 228 | **Пример:** 229 | 230 | ``` bash 231 | php bim gen IblockType:add 232 | ``` 233 | Также возможно передать iblock type id и description опционально: 234 | ``` bash 235 | php bim gen IblockType:add --typeId=catalog --d="new description #iws-123" 236 | ``` 237 | ### 2.2 Iblock *( php bim gen Iblock:[add|delete] )*: 238 | 239 | Создается Миграционный код "**ИБ**" включая созданные для него *(IblockProperty)* 240 | 241 | Дополнительно запрашивается: 242 | - [IBLOCK_CODE] 243 | - [Description] 244 | 245 | **Пример:** 246 | ``` bash 247 | php bim gen Iblock:add 248 | ``` 249 | Также возможно передать iblock code и description опционально: 250 | ``` bash 251 | php bim gen Iblock:add --code=goods --d="new description #iws-123" 252 | ``` 253 | 254 | ### 2.3 IblockProperty *( php bim gen IblockProperty:[add|delete] )*: 255 | 256 | Создается Миграционный код "**Свойства ИБ**" 257 | 258 | Дополнительно запрашивается: 259 | - [IBLOCK_CODE] 260 | - [PROPERTY_CODE] 261 | - [Description] 262 | 263 | **Пример:** 264 | ``` bash 265 | php bim gen IblockProperty:add 266 | ``` 267 | Также возможно передать iblock code, property code и description опционально: 268 | ``` bash 269 | php bim gen IblockProperty:add --code=goods --propertyCode=NEW_ITEM --d="new description #iws-123" 270 | ``` 271 | 272 | ### 2.4 Hlblock *( php bim gen Hlblock:[add|delete] )*: 273 | 274 | Создается Миграционный код "**Highloadblock**" включая созданные для него *(UserFields)* 275 | 276 | Дополнительно запрашивается: 277 | - [HLBLOCK_ID] 278 | - [Description] 279 | 280 | **Пример:** 281 | ``` bash 282 | php bim gen Hlblock:add 283 | ``` 284 | Также возможно передать hlblock id и description опционально: 285 | ``` bash 286 | php bim gen IHlblock:add --id=82 --d="new description #iws-123" 287 | ``` 288 | 289 | ### 2.5 HlblockField *( php bim gen HlblockField:[add|delete] )*: 290 | 291 | Создается Миграционный код "**HighloadblockField (UserField)**" 292 | 293 | Дополнительно запрашивается: 294 | - [HLBLOCK_ID] 295 | - [USER_FIELD_ID] 296 | - [Description] 297 | 298 | **Пример:** 299 | ``` bash 300 | php bim gen HlblockField:add 301 | ``` 302 | Также возможно передать hlblock id, hlblock field id и description опционально: 303 | ``` bash 304 | php bim gen IHlblock:add --hlblockid=93 --hlFieldId=582 --d="new description #iws-123" 305 | ``` 306 | 307 | ### 2.6 Group *( php bim gen Group:[add|delete] )*: 308 | 309 | Создается Миграционный код "**Group (Группы пользователей)**" 310 | 311 | Дополнительно запрашивается: 312 | - [GROUP_ID] 313 | - [Description] 314 | 315 | **Пример:** 316 | ``` bash 317 | php bim gen Group:add 318 | ``` 319 | Также возможно передать group id, и description опционально: 320 | ``` bash 321 | php bim gen Group:add --id=5 --d="new description #iws-123" 322 | ``` 323 | 324 | ### 2.7 Site *( php bim gen Site:[add|delete] )*: 325 | 326 | Создается Миграционный код "**Site (Сайты)**" 327 | 328 | Дополнительно запрашивается: 329 | - [SITE_ID] 330 | - [Description] 331 | 332 | **Пример:** 333 | ``` bash 334 | php bim gen Site:add 335 | ``` 336 | Также возможно передать site id, и description опционально: 337 | ``` bash 338 | php bim gen Site:add --id=s1 --d="new description #iws-123" 339 | ``` 340 | 341 | 342 | > Обратите внимание! 343 | 344 | > что миграционные классы созданные по наличию, выполняются автоматически. 345 | 346 | 347 | ## Режим multi [BIM GEN MULTI]: 348 | 349 | Так же доступен режим массовой генерации по наличию. Данный способ удобен при созданиие миграций по наличию для множества одинаковых элементов. 350 | Например для нескольких UserFields. 351 | 352 | **Пример:** 353 | 354 | ``` bash 355 | php bim gen multi 356 | ``` 357 | 358 | ## Тегирование миграций: 359 | 360 | При создании нового миграционного класса существует возможность выставления тега в комментарии к миграции для дальнейшей более удобной отмены либо выполнения группы миграций связанных одним тегом. 361 | 362 | **Формат**: #[название] 363 | 364 | **Пример:** 365 | Как вариант применения, вставлять тег номера задачи из трекера. 366 | 367 | ``` bash 368 | [Description]: #IWS-242 Add new Iblock[services] 369 | ``` 370 | 371 | ## Логирование: 372 | 373 | Существует возможность логирования информации о состоянии выполнения или отмены миграций. 374 | 375 | **Пример:** 376 | ``` bash 377 | php bim up --logging 378 | ``` 379 | или 380 | ``` bash 381 | php bim down --logging 382 | ``` 383 | **Примечание:** 384 | По умолчанию инфомация сохраняется в файл вида **_log/bim/[Year]/[Month]/[Day]/bim.log** 385 | 386 | # 7 Информация о проекет [BIM INFO] 387 | 388 | Информация о текущем bitrix проекте: 389 | 390 | - Название проекта 391 | - Версия bitrix 392 | - Редакция bitrix 393 | 394 | **Пример:** 395 | ``` bash 396 | php bim info 397 | ``` 398 | -------------------------------------------------------------------------------- /docs/index.md: -------------------------------------------------------------------------------- 1 | 2 | # Bitrix Migration (BIM) 3 | 4 | [![Latest Stable Version](https://poser.pugx.org/cjp2600/bim-core/v/stable.svg)](https://packagist.org/packages/cjp2600/bim-core) [![Total Downloads](https://poser.pugx.org/cjp2600/bim-core/downloads.svg)](https://packagist.org/packages/cjp2600/bim-core) [![Latest Unstable Version](https://poser.pugx.org/cjp2600/bim-core/v/unstable.svg)](https://packagist.org/packages/cjp2600/bim-core) [![License](https://poser.pugx.org/cjp2600/bim-core/license.svg)](https://packagist.org/packages/cjp2600/bim-core) 5 | 6 | Версионная миграция структуры БД для **[1С Битрикс CMS](http://bitrix.ru)** 7 | 8 | - [Установка](#install) 9 | * [Автоматическая установка](#auto) 10 | * [Ручная установка](#hand) 11 | - [Настройка](#prop) 12 | - [Выполнение - bim up](#up) 13 | - [Отмена - bim down](#down) 14 | - [Вывод списка - bim ls](#ls) 15 | - [Создание - bim gen](#gen) 16 | * [Создание пустой миграции](#gen_empty) 17 | * [Создание миграционного кода по наличию](#gen_nal) 18 | * Модуль (iblock,highloadblock) 19 | * [IblockType](#iblocktype) 20 | * [Iblock](#iblock) 21 | * [IblockProperty](#iblockproperty) 22 | * [Highloadblock](#hlblock) 23 | * [HighloadblockField](#hlblockfield) 24 | * Модуль (main) 25 | * [Group](#main_group) 26 | * [Site](#main_site) 27 | * [Режим multi - bim gen multi](#multi) 28 | * [Тегирование миграций](#tag) 29 | * [Логирование](#logging) 30 | - [Информация о проекте - bim info](#info) 31 | 32 | # 1 Установка 33 | 34 | ### 1.1 Автоматическая установка 35 | 36 | Для установки и инициализации bim для bitrix проекта необходимо выполнить следующиие действия из корня проекта: 37 | 38 | - Установить Composer: 39 | ``` 40 | curl -s https://getcomposer.org/installer | php 41 | ``` 42 | - Выполнить установочный скрипт: 43 | 44 | ``` bash 45 | php -r "readfile('https://raw.githubusercontent.com/cjp2600/bim/master/install');" | php 46 | ``` 47 | > Автоматические действия установщика: 48 | 49 | > 1. Добавление файла bim в корень проекта. 50 | > 2. Инициализация **composer autoloader** в файле **init.php** 51 | > 3. Создание файла **composer.json** в корне проекта со ссылкой на bim репозиторий **"require": { "cjp2600/bim-core": ">=1.0.0"}** 52 | 53 | ### 1.2 Ручная установка 54 | 55 | Для ручной установки bim необходимо: 56 | 57 | - Установить Composer: 58 | 59 | ``` 60 | curl -s https://getcomposer.org/installer | php 61 | ``` 62 | - Добавть инициализацию composer (в файл init.php добавить запись): 63 | 64 | ```bash 65 | if (file_exists($_SERVER['DOCUMENT_ROOT'] . '/vendor/autoload.php')) 66 | require_once $_SERVER['DOCUMENT_ROOT'] . '/vendor/autoload.php'; 67 | ``` 68 | 69 | - Создать в корне сайта файл **composer.json** с содержимым: 70 | 71 | ```json 72 | { 73 | "require": { 74 | "cjp2600/bim-core": ">=1.0.0" 75 | } 76 | } 77 | ``` 78 | 79 | - В **.gitignore** добавить запись: 80 | 81 | ``` 82 | /vendor 83 | *.lock 84 | ``` 85 | 86 | - Done! :): 87 | 88 | ``` php 89 | php vendor/bin/bim info 90 | ``` 91 | 92 | # 2 Настройка 93 | 94 | Для начала работы обновляем **composer** и создаем миграционную таблицу в БД: 95 | 96 | ``` bash 97 | php composer.phar update 98 | ``` 99 | Создаём таблицу миграций : 100 | 101 | ```bash 102 | php bim init 103 | ``` 104 | 105 | 106 | # 3 Выполнение миграций [BIM UP] 107 | 108 | - Общее выполнение: 109 | ```bash 110 | php bim up 111 | ``` 112 | Выполняет полный список не выполненых либо ранее отмененных миграционных классов отсортированых по названию (**timestamp**). 113 | 114 | - Еденичное выполнение: 115 | ```bash 116 | php bim up 1423660766 117 | ``` 118 | Выполняет указанную в праметрах миграцию. 119 | 120 | - Выполнение по временному периоду: 121 | ```bash 122 | php bim up --from="29.01.2015 00:01" --to="29.01.2015 23:55" 123 | ``` 124 | - Выполнение по тегу: 125 | ```bash 126 | php bim up --tag=iws-123 127 | ``` 128 | Выполняет все миграции где найден указанный тег в описании. 129 | 130 | - Логирование: 131 | ``` bash 132 | php bim up --logging 133 | ``` 134 | 135 | # 4 Отмена выполненых миграций [BIM DOWN] 136 | 137 | - Общая отмена: 138 | ```bash 139 | php bim down 140 | ``` 141 | Отменяет весь список выполненных миграционных классов. 142 | 143 | - Еденичная отмена: 144 | ``` bash 145 | php bim down 1423660766 146 | ``` 147 | Отменяет указанную в праметрах миграцию. 148 | 149 | - Отмена по временному периоду: 150 | ```bash 151 | php bim down --from="29.01.2015 00:01" --to="29.01.2015 23:55" 152 | ``` 153 | - Отмена по тегу: 154 | ```bash 155 | php bim down --tag=iws-123 156 | ``` 157 | Отменяет все миграции где найден указанный тег в описании. 158 | 159 | - Логирование: 160 | ``` bash 161 | php bim down --logging 162 | ``` 163 | 164 | # 5 Вывод списка миграций [BIM LS] 165 | - Общей список: 166 | ```bash 167 | php bim ls 168 | ``` 169 | - Список выполненных миграций: 170 | ```bash 171 | php bim ls --a 172 | ``` 173 | - Список отменённых миграций: 174 | ```bash 175 | php bim ls --n 176 | ``` 177 | - Список миграций за определённый период времени: 178 | ```bash 179 | php bim ls --from="29.01.2015 00:01" --to="29.01.2015 23:55" 180 | ``` 181 | - Список миграций по тегу: 182 | ```bash 183 | php bim ls --tag=iws-123 184 | ``` 185 | 186 | # 6 Создание новых миграций [BIM GEN] 187 | 188 | Существует два способа создания миграций: 189 | 190 | ## 1) Создание пустой миграции: 191 | Создается пустой шаблон миграционного класса. Структура класса определена интерфейсом *Bim/Revision* и включает следующие 192 | обязательные методы: 193 | 194 | - *up();* - выполнение 195 | - *down();* - отмена 196 | - *getDescription();* - получения описания. 197 | - *getAuthor();* - получение автора. 198 | 199 | Дополнительно запрашивается: 200 | - [Description] 201 | 202 | **Пример:** 203 | 204 | ``` bash 205 | php bim gen 206 | ``` 207 | Также возможно передать description опционально: 208 | ``` bash 209 | php bim gen --d="new description #iws-123" 210 | ``` 211 | 212 | > Далее создается файл миграции вида: */[migrations_path]/[timestamp].php 213 | 214 | > Например: /migrations/123412434.php 215 | 216 | ## 2) Создание миграционного кода по наличию: 217 | 218 | Создается код развертывания/отката существующего элемента схемы bitrix БД. 219 | На данный момент доступно генерация по наличию для следующих элементов bitrix БД: 220 | 221 | ### 2.1 IblockType *( php bim gen IblockType:[add|delete] )*: 222 | 223 | Создается Миграционный код "**Типа ИБ**" включая созданные для него *(UserFields, IBlock, IblockProperty)* 224 | 225 | Дополнительно запрашивается: 226 | - [IBLOCK_TYPE_ID] 227 | - [Description] 228 | 229 | **Пример:** 230 | 231 | ``` bash 232 | php bim gen IblockType:add 233 | ``` 234 | Также возможно передать iblock type id и description опционально: 235 | ``` bash 236 | php bim gen IblockType:add --typeId=catalog --d="new description #iws-123" 237 | ``` 238 | ### 2.2 Iblock *( php bim gen Iblock:[add|delete] )*: 239 | 240 | Создается Миграционный код "**ИБ**" включая созданные для него *(IblockProperty)* 241 | 242 | Дополнительно запрашивается: 243 | - [IBLOCK_CODE] 244 | - [Description] 245 | 246 | **Пример:** 247 | ``` bash 248 | php bim gen Iblock:add 249 | ``` 250 | Также возможно передать iblock code и description опционально: 251 | ``` bash 252 | php bim gen Iblock:add --code=goods --d="new description #iws-123" 253 | ``` 254 | 255 | ### 2.3 IblockProperty *( php bim gen IblockProperty:[add|delete] )*: 256 | 257 | Создается Миграционный код "**Свойства ИБ**" 258 | 259 | Дополнительно запрашивается: 260 | - [IBLOCK_CODE] 261 | - [PROPERTY_CODE] 262 | - [Description] 263 | 264 | **Пример:** 265 | ``` bash 266 | php bim gen IblockProperty:add 267 | ``` 268 | Также возможно передать iblock code, property code и description опционально: 269 | ``` bash 270 | php bim gen IblockProperty:add --code=goods --propertyCode=NEW_ITEM --d="new description #iws-123" 271 | ``` 272 | 273 | ### 2.4 Hlblock *( php bim gen Hlblock:[add|delete] )*: 274 | 275 | Создается Миграционный код "**Highloadblock**" включая созданные для него *(UserFields)* 276 | 277 | Дополнительно запрашивается: 278 | - [HLBLOCK_ID] 279 | - [Description] 280 | 281 | **Пример:** 282 | ``` bash 283 | php bim gen Hlblock:add 284 | ``` 285 | Также возможно передать hlblock id и description опционально: 286 | ``` bash 287 | php bim gen IHlblock:add --id=82 --d="new description #iws-123" 288 | ``` 289 | 290 | ### 2.5 HlblockField *( php bim gen HlblockField:[add|delete] )*: 291 | 292 | Создается Миграционный код "**HighloadblockField (UserField)**" 293 | 294 | Дополнительно запрашивается: 295 | - [HLBLOCK_ID] 296 | - [USER_FIELD_ID] 297 | - [Description] 298 | 299 | **Пример:** 300 | ``` bash 301 | php bim gen HlblockField:add 302 | ``` 303 | Также возможно передать hlblock id, hlblock field id и description опционально: 304 | ``` bash 305 | php bim gen IHlblock:add --hlblockid=93 --hlFieldId=582 --d="new description #iws-123" 306 | ``` 307 | 308 | ### 2.6 Group *( php bim gen Group:[add|delete] )*: 309 | 310 | Создается Миграционный код "**Group (Группы пользователей)**" 311 | 312 | Дополнительно запрашивается: 313 | - [GROUP_ID] 314 | - [Description] 315 | 316 | **Пример:** 317 | ``` bash 318 | php bim gen Group:add 319 | ``` 320 | Также возможно передать group id, и description опционально: 321 | ``` bash 322 | php bim gen Group:add --id=5 --d="new description #iws-123" 323 | ``` 324 | 325 | ### 2.7 Site *( php bim gen Site:[add|delete] )*: 326 | 327 | Создается Миграционный код "**Site (Сайты)**" 328 | 329 | Дополнительно запрашивается: 330 | - [SITE_ID] 331 | - [Description] 332 | 333 | **Пример:** 334 | ``` bash 335 | php bim gen Site:add 336 | ``` 337 | Также возможно передать site id, и description опционально: 338 | ``` bash 339 | php bim gen Site:add --id=s1 --d="new description #iws-123" 340 | ``` 341 | 342 | 343 | > Обратите внимание! 344 | 345 | > что миграционные классы созданные по наличию, выполняются автоматически. 346 | 347 | 348 | ## Режим multi [BIM GEN MULTI]: 349 | 350 | Так же доступен режим массовой генерации по наличию. Данный способ удобен при созданиие миграций по наличию для множества одинаковых элементов. 351 | Например для нескольких UserFields. 352 | 353 | **Пример:** 354 | 355 | ``` bash 356 | php bim gen multi 357 | ``` 358 | 359 | ## Тегирование миграций: 360 | 361 | При создании нового миграционного класса существует возможность выставления тега в комментарии к миграции для дальнейшей более удобной отмены либо выполнения группы миграций связанных одним тегом. 362 | 363 | **Формат**: #[название] 364 | 365 | **Пример:** 366 | Как вариант применения, вставлять тег номера задачи из трекера. 367 | 368 | ``` bash 369 | [Description]: #IWS-242 Add new Iblock[services] 370 | ``` 371 | 372 | ## Логирование: 373 | 374 | Существует возможность логирования информации о состоянии выполнения или отмены миграций. 375 | 376 | **Пример:** 377 | ``` bash 378 | php bim up --logging 379 | ``` 380 | или 381 | ``` bash 382 | php bim down --logging 383 | ``` 384 | **Примечание:** 385 | По умолчанию инфомация сохраняется в файл вида **_log/bim/[Year]/[Month]/[Day]/bim.log** 386 | 387 | # 7 Информация о проекет [BIM INFO] 388 | 389 | Информация о текущем bitrix проекте: 390 | 391 | - Название проекта 392 | - Версия bitrix 393 | - Редакция bitrix 394 | 395 | **Пример:** 396 | ``` bash 397 | php bim info 398 | ``` 399 | -------------------------------------------------------------------------------- /src/cmd/BaseCommand.php: -------------------------------------------------------------------------------- 1 | writeln($text, Colors::YELLOW); 25 | } 26 | 27 | /** 28 | * success 29 | * @param $text 30 | */ 31 | public function success($text) 32 | { 33 | $this->writeln($text, Colors::GREEN); 34 | } 35 | 36 | /** 37 | * padding 38 | * @param $text 39 | * @throws \ConsoleKit\ConsoleException 40 | */ 41 | public function padding($text) 42 | { 43 | $box = new ConsoleKit\Widgets\Box($this->console, $text, ''); 44 | $box->write(); 45 | $this->writeln(''); 46 | } 47 | 48 | /** 49 | * info 50 | * @param $text 51 | */ 52 | public function error($text) 53 | { 54 | $this->writeln($text, Colors::RED); 55 | } 56 | 57 | /** 58 | * setTemplate 59 | * @param $name of create 60 | * @param $method 61 | * @param array $data 62 | * @param string $type up|down 63 | * @return mixed|string 64 | */ 65 | public function setTemplateMethod($name, $method, $data = array(), $type = "up") 66 | { 67 | $template = file_get_contents(__DIR__ . '/../db/template/' . $name . '/' . $method . '/' . $type . '.txt'); 68 | if (!empty($data)) { 69 | foreach ($data as $key => $val) { 70 | $template = str_replace("#" . $key . "#", $val, $template); 71 | } 72 | } 73 | return $template; 74 | } 75 | 76 | /** 77 | * setTemplate 78 | * @param $class_name 79 | * @param $up_content 80 | * @param $down_content 81 | * @param string $desc_content 82 | * @param string $author 83 | * @return mixed|string 84 | */ 85 | public function setTemplate($class_name, $up_content, $down_content, $desc_content = "", $author = "") 86 | { 87 | $template = file_get_contents(__DIR__ . '/../db/template/main.txt'); 88 | $template = str_replace(array( 89 | "#CLASS_NAME#", 90 | "#UP_CONTENT#", 91 | "#DOWN_CONTENT#", 92 | "#DESC_CONTENT#", 93 | "#AUTHOR_CONTENT#" 94 | ), array($class_name, $up_content, $down_content, $desc_content, $author), $template); 95 | return $template; 96 | } 97 | 98 | /** 99 | * saveTemplate 100 | * @param $filename 101 | * @param $template 102 | * @param bool $needUp 103 | * @throws Exception 104 | */ 105 | public function saveTemplate($filename, $template, $needUp = false) 106 | { 107 | $migration_path = $this->getMigrationPath(); 108 | if (!file_exists($migration_path)) { 109 | mkdir($migration_path, 0777); 110 | } 111 | if (!is_writable($migration_path)) { 112 | throw new Exception("No permission to create a migration file in the folder " . $migration_path); 113 | } 114 | 115 | $save_file = $migration_path . $filename . '.php'; 116 | $newFile = fopen($save_file, 'w'); 117 | fwrite($newFile, $template); 118 | fclose($newFile); 119 | 120 | if (file_exists($save_file)) { 121 | 122 | #if need up 123 | if ($needUp) { 124 | $this->autoUpMethod($needUp, $save_file, $filename); 125 | } 126 | 127 | # output 128 | $this->writeln("Create new migration file: "); 129 | $this->success($save_file); 130 | 131 | } else { 132 | throw new Exception("Failed to create the migration file " . $save_file); 133 | } 134 | 135 | } 136 | 137 | /** 138 | * autoUpMethod 139 | * @param $needUp 140 | * @param $save_file 141 | * @param $migration 142 | * @throws Exception 143 | * @throws \Bim\Db\Entity\Exception 144 | */ 145 | public function autoUpMethod($needUp, $save_file, $migration) 146 | { 147 | $time_start = microtime(true); 148 | $this->info(" -> Start auto applying migration:"); 149 | $this->writeln(''); 150 | if ($needUp != "add") { 151 | include_once "" . $save_file . ""; 152 | $migrationClass = "Migration" . $migration; 153 | # check bim migration. 154 | if ((method_exists($migrationClass, "up"))) { 155 | try { 156 | # call up function 157 | if (false !== $migrationClass::up()) { 158 | 159 | if (!Bim\Db\Entity\MigrationsTable::isExistsInTable($migration)) { 160 | if (Bim\Db\Entity\MigrationsTable::add($migration)) { 161 | $this->writeln($this->color(" - applied : " . $migration, Colors::GREEN)); 162 | } else { 163 | throw new Exception("add in migration table error"); 164 | } 165 | } 166 | } else { 167 | $this->writeln(Colors::colorize(" - error : " . $migration, 168 | Colors::RED) . " " . Colors::colorize("(Method Up return false)", Colors::YELLOW)); 169 | } 170 | } catch (Exception $e) { 171 | $this->writeln(Colors::colorize(" - error : " . $migration, 172 | Colors::RED) . " " . Colors::colorize("(" . $e->getMessage() . ")", Colors::YELLOW)); 173 | } 174 | } 175 | } else { 176 | 177 | if (!Bim\Db\Entity\MigrationsTable::isExistsInTable($migration)) { 178 | if (Bim\Db\Entity\MigrationsTable::add($migration)) { 179 | $this->writeln($this->color(" - applied : " . $migration, Colors::GREEN)); 180 | } else { 181 | throw new Exception("add in migration table error"); 182 | } 183 | } 184 | 185 | } 186 | $time_end = microtime(true); 187 | $time = $time_end - $time_start; 188 | $this->writeln(''); 189 | $this->info(" -> " . round($time, 2) . "s"); 190 | } 191 | 192 | /** 193 | * Получение папк хранения миграций 194 | * 195 | * getMigrationPath 196 | * @param bool $full 197 | * @return mixed|string 198 | * @throws \Bim\Exception\BimException 199 | */ 200 | public function getMigrationPath($full = true) 201 | { 202 | if (!is_null($this->migrationPath)) { 203 | if (substr($this->migrationPath, -1) != "/") { 204 | $this->migrationPath = $this->migrationPath . "/"; 205 | } 206 | $path = $this->migrationPath; 207 | } else { 208 | $conf = new Config(__DIR__ . "/../config/bim.json"); 209 | $migration_path = $conf->get("migration_path"); 210 | $path = ($full) ? $_SERVER["DOCUMENT_ROOT"] . "/" . $migration_path . "/" : $migration_path; 211 | } 212 | 213 | if (!file_exists($path)) { 214 | mkdir($path, 0777); 215 | } 216 | 217 | return $path; 218 | } 219 | 220 | /** 221 | * clear 222 | * @param $text 223 | * @return mixed 224 | */ 225 | public function clear($text) 226 | { 227 | return trim($text); 228 | } 229 | 230 | /** 231 | * getMigrationName 232 | * @return string 233 | */ 234 | public function getMigrationName() 235 | { 236 | return time(); 237 | } 238 | 239 | /** 240 | * fromCamelCase 241 | * @param $input 242 | * @return string 243 | */ 244 | public function fromCamelCase($input) 245 | { 246 | preg_match_all('!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!', $input, $matches); 247 | $ret = $matches[0]; 248 | foreach ($ret as &$match) { 249 | $match = $match == strtoupper($match) ? strtolower($match) : lcfirst($match); 250 | } 251 | return implode('_', $ret); 252 | } 253 | 254 | /** 255 | * camelCase 256 | * @param $str 257 | * @param array $noStrip 258 | * @return mixed|string 259 | */ 260 | public function camelCase($str, array $noStrip = array()) 261 | { 262 | // non-alpha and non-numeric characters become spaces 263 | $str = preg_replace('/[^a-z0-9' . implode("", $noStrip) . ']+/i', ' ', $str); 264 | $str = trim($str); 265 | // uppercase the first character of each word 266 | $str = ucwords($str); 267 | $str = str_replace(" ", "", $str); 268 | $str = str_replace(":", "", $str); 269 | $str = preg_replace('/[0-9]+/', '', $str); 270 | $str = lcfirst($str); 271 | 272 | return $str; 273 | } 274 | 275 | /** 276 | * getDirectoryTree 277 | * @param $outerDir 278 | * @param $x 279 | * @return array 280 | */ 281 | public function getDirectoryTree($outerDir, $x) 282 | { 283 | $dirs = array_diff(scandir($outerDir), Array(".", "..")); 284 | $dir_array = Array(); 285 | foreach ($dirs as $d) { 286 | if (is_dir($outerDir . "/" . $d)) { 287 | $dir_array[$d] = $this->getDirectoryTree($outerDir . "/" . $d, $x); 288 | } else { 289 | if (($x) ? preg_match('/'.$x . '$/', $d) : 1) { 290 | $dir_array[str_replace("." . $x, "", $d)] = $d; 291 | } 292 | } 293 | } 294 | 295 | $return = array(); 296 | foreach ($dir_array as $key => $val) { 297 | 298 | if (!preg_match('/^.*\.(' . $x . ')$/i', $val)) { 299 | continue; 300 | } 301 | 302 | # include migration file. 303 | include_once "" . $this->getMigrationPath() . $val . ""; 304 | $class_name = "Migration" . $key; 305 | # check instance of Revision interface. 306 | if (new $class_name() instanceof Bim\Revision) { 307 | # get description 308 | $description = (method_exists($class_name, "getDescription")) ? $class_name::getDescription() : ""; 309 | # set translit description (because its cli) 310 | $description = $this->translit($description); 311 | # colorize 312 | $description = $this->color_tg($description); 313 | # get tags 314 | $tags = (!empty($description)) ? $this->getHashTags($description) : array(); 315 | # get author 316 | $author = (method_exists($class_name, "getAuthor")) ? $class_name::getAuthor() : ""; 317 | 318 | $return[$key] = array( 319 | "name" => $key, 320 | "file" => $val, 321 | "date" => $key, 322 | "author" => $author, 323 | "description" => $description, 324 | "tags" => $tags 325 | ); 326 | } 327 | } 328 | return $return; 329 | } 330 | 331 | /** 332 | * logging 333 | * 334 | * @param array $input_array 335 | * @param string $file_name 336 | * @param string $type 337 | */ 338 | public function logging($input_array = array(), $type = "up", $file_name = 'bim.log') 339 | { 340 | $conf = new Config(__DIR__ . "/../config/bim.json"); 341 | $logging_path = $conf->get("logging_path"); 342 | $return_message = " >> php bim " . $type . " \n"; 343 | $return_message .= date('d.m.Y H:i:s') . "\n"; 344 | $return_message .= print_r($input_array, true) . "\n"; 345 | $return_message .= "\n----------\n\n"; 346 | $file_name = empty($file_name) ? 'bim.log' : $file_name; 347 | $log_path = $_SERVER['DOCUMENT_ROOT'] . '/' . $logging_path . '/' . date("Y") . "/" . date("m") . "/" . date("d"); 348 | if (!file_exists($log_path)) { 349 | mkdir($log_path, 0777, true); 350 | } 351 | file_put_contents($log_path . '/' . $file_name, $return_message, FILE_APPEND); 352 | $this->writeln("Put info to log file > " . Colors::colorize($log_path . '/' . $file_name, Colors::GREEN)); 353 | } 354 | 355 | /** 356 | * translit 357 | * 358 | * Analog bitrix Utils::translit 359 | * Unfortunately, the standard method does not work as it is necessary for us. 360 | * (because its bitrix baby!) 361 | * 362 | * @param $str 363 | * @return string 364 | */ 365 | public function translit($str) 366 | { 367 | $params = array( 368 | "max_len" => "200", 369 | "change_case" => "L", 370 | "replace_space" => " ", 371 | "replace_other" => " ", 372 | "delete_repeat_replace" => "true", 373 | "safe_chars" => "#_-[]()" 374 | ); 375 | $russian = array( 376 | 'А', 377 | 'Б', 378 | 'В', 379 | 'Г', 380 | 'Д', 381 | 'Е', 382 | 'Ё', 383 | 'Ж', 384 | 'З', 385 | 'И', 386 | 'Й', 387 | 'К', 388 | 'Л', 389 | 'М', 390 | 'Н', 391 | 'О', 392 | 'П', 393 | 'Р', 394 | 'С', 395 | 'Т', 396 | 'У', 397 | 'Ф', 398 | 'Х', 399 | 'Ц', 400 | 'Ч', 401 | 'Ш', 402 | 'Щ', 403 | 'Ъ', 404 | 'Ы', 405 | 'Ь', 406 | 'Э', 407 | 'Ю', 408 | 'Я', 409 | 'а', 410 | 'б', 411 | 'в', 412 | 'г', 413 | 'д', 414 | 'е', 415 | 'ё', 416 | 'ж', 417 | 'з', 418 | 'и', 419 | 'й', 420 | 'к', 421 | 'л', 422 | 'м', 423 | 'н', 424 | 'о', 425 | 'п', 426 | 'р', 427 | 'с', 428 | 'т', 429 | 'у', 430 | 'ф', 431 | 'х', 432 | 'ц', 433 | 'ч', 434 | 'ш', 435 | 'щ', 436 | 'ъ', 437 | 'ы', 438 | 'ь', 439 | 'э', 440 | 'ю', 441 | 'я' 442 | ); 443 | $latin = array( 444 | 'A', 445 | 'B', 446 | 'V', 447 | 'G', 448 | 'D', 449 | 'E', 450 | 'E', 451 | 'Gh', 452 | 'Z', 453 | 'I', 454 | 'Y', 455 | 'K', 456 | 'L', 457 | 'M', 458 | 'N', 459 | 'O', 460 | 'P', 461 | 'R', 462 | 'S', 463 | 'T', 464 | 'U', 465 | 'F', 466 | 'H', 467 | 'C', 468 | 'Ch', 469 | 'Sh', 470 | 'Sch', 471 | 'Y', 472 | 'Y', 473 | 'Y', 474 | 'E', 475 | 'Yu', 476 | 'Ya', 477 | 'a', 478 | 'b', 479 | 'v', 480 | 'g', 481 | 'd', 482 | 'e', 483 | 'e', 484 | 'gh', 485 | 'z', 486 | 'i', 487 | 'y', 488 | 'k', 489 | 'l', 490 | 'm', 491 | 'n', 492 | 'o', 493 | 'p', 494 | 'r', 495 | 's', 496 | 't', 497 | 'u', 498 | 'f', 499 | 'h', 500 | 'c', 501 | 'ch', 502 | 'sh', 503 | 'sch', 504 | 'y', 505 | 'y', 506 | 'y', 507 | 'e', 508 | 'yu', 509 | 'ya' 510 | ); 511 | $str = str_replace($russian, $latin, $str); 512 | $len = strlen($str); 513 | $str_new = ''; 514 | $last_chr_new = ''; 515 | for ($i = 0; $i < $len; $i++) { 516 | $chr = substr($str, $i, 1); 517 | if (preg_match("/[a-zA-Z0-9]/" . BX_UTF_PCRE_MODIFIER, $chr) || strpos($params["safe_chars"], 518 | $chr) !== false 519 | ) { 520 | $chr_new = $chr; 521 | } elseif (preg_match("/\\s/" . BX_UTF_PCRE_MODIFIER, $chr)) { 522 | if ( 523 | !$params["delete_repeat_replace"] 524 | || 525 | ($i > 0 && $last_chr_new != $params["replace_space"]) 526 | ) { 527 | $chr_new = $params["replace_space"]; 528 | } else { 529 | $chr_new = ''; 530 | } 531 | } else { 532 | if ( 533 | !$params["delete_repeat_replace"] 534 | || 535 | ($i > 0 && $i != $len - 1 && $last_chr_new != $params["replace_other"]) 536 | ) { 537 | $chr_new = $params["replace_other"]; 538 | } else { 539 | $chr_new = ''; 540 | } 541 | } 542 | if (strlen($chr_new)) { 543 | if ($params["change_case"] == "L" || $params["change_case"] == "l") { 544 | $chr_new = ToLower($chr_new); 545 | } elseif ($params["change_case"] == "U" || $params["change_case"] == "u") { 546 | $chr_new = ToUpper($chr_new); 547 | } 548 | $str_new .= $chr_new; 549 | $last_chr_new = $chr_new; 550 | } 551 | if (strlen($str_new) >= $params["max_len"]) { 552 | break; 553 | } 554 | } 555 | return $str_new; 556 | } 557 | 558 | /** 559 | * getHashTags 560 | * @param $text 561 | * @return array 562 | */ 563 | public function getHashTags($text) 564 | { 565 | $hashtags = array(); 566 | preg_match_all("/#([\w-]+)/i", $text, $matches); 567 | if (!empty($matches[0])) { 568 | foreach ($matches[0] as $hashtag) { 569 | $hashtag = strtolower(str_replace('#', '', $hashtag)); 570 | $hashtags[] = $hashtag; 571 | } 572 | } 573 | if (!empty($hashtags)) { 574 | $hashtags = array_unique($hashtags); 575 | } 576 | return $hashtags; 577 | } 578 | 579 | /** 580 | * color_tg 581 | * @param $text 582 | * @return mixed 583 | */ 584 | public function color_tg($text) 585 | { 586 | return preg_replace("/#([\w-]+)/i", Colors::colorize("$0", Colors::BLUE), $text); 587 | } 588 | 589 | /** 590 | * green 591 | * @param $text 592 | * @return string 593 | */ 594 | public function color($text, $color) 595 | { 596 | return Colors::colorize($text, $color); 597 | } 598 | 599 | /** 600 | * checkInDb 601 | * @param $migration_id 602 | * @return bool 603 | */ 604 | public function checkInDb($migration_id) 605 | { 606 | # check migration table 607 | return Bim\Db\Entity\MigrationsTable::isExistsInTable($migration_id); 608 | } 609 | 610 | /** 611 | * @param bool $force 612 | * @param string $text 613 | * @param array $variants 614 | */ 615 | public function askDoOperation($force = false, $text = "Apply it's not The applied migration?",$variants = ['yes','no']) 616 | { 617 | if (!$force) { 618 | $dialog = new \ConsoleKit\Widgets\Dialog($this->console); 619 | $this->writeln(""); 620 | $desk = $this->color($text, 621 | \ConsoleKit\Colors::WHITE); 622 | $askResponse = $dialog->ask(" " . $desk . " " . $this->color('['.implode("|",$variants).']:', 623 | \ConsoleKit\Colors::YELLOW), '', 624 | false); 625 | 626 | if (strtolower($askResponse) != strtolower($variants[0])) { 627 | die(); 628 | } 629 | } 630 | } 631 | 632 | } 633 | -------------------------------------------------------------------------------- /src/cmd/GenCommand.php: -------------------------------------------------------------------------------- 1 | multiCommands($args, $options); 42 | } else { 43 | # single command generator 44 | if (strstr($args[0], ':')) { 45 | $ex = explode(":", $args[0]); 46 | $this->setGenerateObject(Bim\Db\Generator\Code::buildHandler(ucfirst($ex[0]))); 47 | $methodName = ucfirst($ex[0]) . ucfirst($ex[1]); 48 | } else { 49 | throw new \Bim\Exception\BimException("Improperly formatted command. Example: php bim gen iblock:add"); 50 | } 51 | $method = "gen" . $methodName; 52 | if (method_exists($this, $method)) { 53 | $this->{$method}($args, $options); 54 | } else { 55 | throw new \Bim\Exception\BimException("Missing command, see help Example: php bim help gen"); 56 | } 57 | } 58 | } else { 59 | $this->createOther($args, $options); 60 | } 61 | } 62 | 63 | /** 64 | * 65 | * 66 | * IblockType 67 | * 68 | * 69 | */ 70 | 71 | /** 72 | * genIblockTypeAdd 73 | * @param array $args 74 | * @param array $options 75 | */ 76 | public function genIblockTypeAdd(array $args, array $options = array()) 77 | { 78 | $dialog = new \ConsoleKit\Widgets\Dialog($this->console); 79 | $iblockTypeId = (isset($options['typeId'])) ? $options['typeId'] : false; 80 | 81 | if (!$iblockTypeId) { 82 | $do = true; 83 | while ($do) { 84 | $desk = "Put block type id - no default/required"; 85 | $iblockTypeId = $dialog->ask($desk . PHP_EOL . $this->color('[IBLOCK_TYPE_ID]:', 86 | \ConsoleKit\Colors::YELLOW), '', false); 87 | $iblockDbRes = \CIBlockType::GetByID($iblockTypeId); 88 | if ($iblockDbRes->SelectedRowsCount()) { 89 | $do = false; 90 | } else { 91 | $this->error('Iblock with id = "' . $iblockTypeId . '" not exist.'); 92 | } 93 | } 94 | } 95 | 96 | # get description options 97 | $desc = (isset($options['d'])) ? $options['d'] : ""; 98 | 99 | $autoTag = "add"; 100 | $this->_save( 101 | $this->generateObject->generateAddCode($iblockTypeId), 102 | $this->generateObject->generateDeleteCode($iblockTypeId), 103 | $desc, 104 | $autoTag 105 | ); 106 | 107 | } 108 | 109 | /** 110 | * genIblocktypeDelete 111 | * @param array $args 112 | * @param array $options 113 | */ 114 | public function genIblocktypeDelete(array $args, array $options = array()) 115 | { 116 | $dialog = new \ConsoleKit\Widgets\Dialog($this->console); 117 | $iblockTypeId = (isset($options['typeId'])) ? $options['typeId'] : false; 118 | 119 | if (!$iblockTypeId) { 120 | $do = true; 121 | while ($do) { 122 | $desk = "Put block type id - no default/required"; 123 | $iblockTypeId = $dialog->ask($desk . PHP_EOL . $this->color('[IBLOCK_TYPE_ID]:', 124 | \ConsoleKit\Colors::YELLOW), '', false); 125 | $iblockDbRes = \CIBlockType::GetByID($iblockTypeId); 126 | if ($iblockDbRes->SelectedRowsCount()) { 127 | $do = false; 128 | } else { 129 | $this->error('Iblock with id = "' . $iblockTypeId . '" not exist.'); 130 | } 131 | } 132 | } 133 | 134 | # get description options 135 | $desc = (isset($options['d'])) ? $options['d'] : ""; 136 | 137 | $autoTag = "delete"; 138 | $this->_save( 139 | $this->generateObject->generateDeleteCode($iblockTypeId), 140 | $this->generateObject->generateAddCode($iblockTypeId) 141 | , $desc, 142 | $autoTag 143 | ); 144 | 145 | } 146 | 147 | 148 | /** 149 | * 150 | * 151 | * Iblock 152 | * 153 | * 154 | */ 155 | 156 | /** 157 | * createIblock 158 | * @param array $args 159 | * @param array $options 160 | * @throws Exception 161 | */ 162 | public function genIblockAdd(array $args, array $options = array()) 163 | { 164 | $dialog = new \ConsoleKit\Widgets\Dialog($this->console); 165 | $code = (isset($options['code'])) ? $options['code'] : false; 166 | 167 | if (!$code) { 168 | $do = true; 169 | while ($do) { 170 | $desk = "Put code information block - no default/required"; 171 | $code = $dialog->ask($desk . PHP_EOL . $this->color('[IBLOCK_CODE]:', \ConsoleKit\Colors::YELLOW), '', 172 | false); 173 | $iblockDbRes = \CIBlock::GetList(array(), array('CODE' => $code, 'CHECK_PERMISSIONS' => 'N')); 174 | if ($iblockDbRes->SelectedRowsCount()) { 175 | $do = false; 176 | } else { 177 | $this->error('Iblock with code = "' . $code . '" not exist.'); 178 | } 179 | } 180 | } 181 | 182 | # get description options 183 | $desc = (isset($options['d'])) ? $options['d'] : ""; 184 | 185 | $autoTag = "add"; 186 | $this->_save( 187 | $this->generateObject->generateAddCode($code), 188 | $this->generateObject->generateDeleteCode($code) 189 | , $desc, 190 | $autoTag 191 | ); 192 | 193 | } 194 | 195 | /** 196 | * createIblockDelete 197 | * @param array $args 198 | * @param array $options 199 | */ 200 | public function genIblockDelete(array $args, array $options = array()) 201 | { 202 | $iBlock = new \CIBlock(); 203 | $dialog = new \ConsoleKit\Widgets\Dialog($this->console); 204 | $code = (isset($options['code'])) ? $options['code'] : false; 205 | 206 | if (!$code) { 207 | $do = true; 208 | while ($do) { 209 | $desk = "Put code information block - no default/required"; 210 | $code = $dialog->ask($desk . PHP_EOL . $this->color('[IBLOCK_CODE]:', \ConsoleKit\Colors::YELLOW), '', 211 | false); 212 | $iblockDbRes = $iBlock->GetList(array(), array('CODE' => $code, 'CHECK_PERMISSIONS' => 'N')); 213 | if ($iblockDbRes->SelectedRowsCount()) { 214 | $do = false; 215 | } else { 216 | $this->error('Iblock with code = "' . $code . '" not exist.'); 217 | } 218 | } 219 | } 220 | 221 | # get description options 222 | $desc = (isset($options['d'])) ? $options['d'] : ""; 223 | 224 | $autoTag = "delete"; 225 | $this->_save( 226 | $this->generateObject->generateDeleteCode($code), 227 | $this->generateObject->generateAddCode($code) 228 | , $desc, 229 | $autoTag 230 | ); 231 | 232 | } 233 | 234 | /** 235 | * 236 | * 237 | * IblockProperty 238 | * 239 | * 240 | */ 241 | 242 | /** 243 | * genIblockPropertyAdd 244 | * @param array $args 245 | * @param array $options 246 | * @throws Exception 247 | */ 248 | public function genIblockPropertyAdd(array $args, array $options = array()) 249 | { 250 | $iBlock = new \CIBlock(); 251 | $dialog = new \ConsoleKit\Widgets\Dialog($this->console); 252 | $code = (isset($options['code'])) ? $options['code'] : false; 253 | 254 | if (!$code) { 255 | $do = true; 256 | while ($do) { 257 | $desk = "Put code information block - no default/required"; 258 | $code = $dialog->ask($desk . PHP_EOL . $this->color('[IBLOCK_CODE]:', \ConsoleKit\Colors::YELLOW), '', 259 | false); 260 | $iblockDbRes = $iBlock->GetList(array(), array('CODE' => $code, 'CHECK_PERMISSIONS' => 'N')); 261 | if ($iblockDbRes->SelectedRowsCount()) { 262 | $do = false; 263 | } else { 264 | $this->error('Iblock with code = "' . $code . '" not exist.'); 265 | } 266 | } 267 | } 268 | 269 | $propertyCode = (isset($options['propertyCode'])) ? $options['propertyCode'] : false; 270 | if (!$propertyCode) { 271 | $do = true; 272 | while ($do) { 273 | $desk = "Put property code - no default/required"; 274 | $propertyCode = $dialog->ask($desk . PHP_EOL . $this->color('[PROPERTY_CODE]:', 275 | \ConsoleKit\Colors::YELLOW), '', false); 276 | $IblockProperty = new \CIBlockProperty(); 277 | $dbIblockProperty = $IblockProperty->GetList(array(), 278 | array('IBLOCK_CODE' => $code, 'CODE' => $propertyCode)); 279 | if ($arIblockProperty = $dbIblockProperty->Fetch()) { 280 | $do = false; 281 | } else { 282 | $this->error('Property with code = "' . $propertyCode . '" not exist.'); 283 | } 284 | } 285 | } 286 | 287 | if (!empty($code) && !empty($propertyCode)) { 288 | $params['iblockCode'] = $code; 289 | $params['propertyCode'] = $propertyCode; 290 | } else { 291 | throw new Exception("Ошибка генерации params"); 292 | } 293 | 294 | # get description options 295 | $desc = (isset($options['d'])) ? $options['d'] : ""; 296 | 297 | $autoTag = "add"; 298 | $this->_save( 299 | $this->generateObject->generateAddCode($params), 300 | $this->generateObject->generateDeleteCode($params) 301 | , $desc, 302 | $autoTag 303 | ); 304 | 305 | } 306 | 307 | 308 | /** 309 | * genIblockPropertyDelete 310 | * @param array $args 311 | * @param array $options 312 | * @throws Exception 313 | */ 314 | public function genIblockPropertyDelete(array $args, array $options = array()) 315 | { 316 | $iBlock = new \CIBlock(); 317 | $dialog = new \ConsoleKit\Widgets\Dialog($this->console); 318 | $code = (isset($options['code'])) ? $options['code'] : false; 319 | 320 | if (!$code) { 321 | $do = true; 322 | while ($do) { 323 | $desk = "Put code information block - no default/required"; 324 | $code = $dialog->ask($desk . PHP_EOL . $this->color('[IBLOCK_CODE]:', \ConsoleKit\Colors::YELLOW), '', 325 | false); 326 | $iblockDbRes = $iBlock->GetList(array(), array('CODE' => $code, 'CHECK_PERMISSIONS' => 'N')); 327 | if ($iblockDbRes->SelectedRowsCount()) { 328 | $do = false; 329 | } else { 330 | $this->error('Iblock with code = "' . $code . '" not exist.'); 331 | } 332 | } 333 | } 334 | 335 | $propertyCode = (isset($options['propertyCode'])) ? $options['propertyCode'] : false; 336 | if (!$propertyCode) { 337 | $do = true; 338 | while ($do) { 339 | $desk = "Put property code - no default/required"; 340 | $propertyCode = $dialog->ask($desk . PHP_EOL . $this->color('[PROPERTY_CODE]:', 341 | \ConsoleKit\Colors::YELLOW), '', false); 342 | $IblockProperty = new \CIBlockProperty(); 343 | $dbIblockProperty = $IblockProperty->GetList(array(), 344 | array('IBLOCK_CODE' => $code, 'CODE' => $propertyCode)); 345 | if ($arIblockProperty = $dbIblockProperty->Fetch()) { 346 | $do = false; 347 | } else { 348 | $this->error('Property with code = "' . $propertyCode . '" not exist.'); 349 | } 350 | } 351 | } 352 | 353 | if (!empty($code) && !empty($propertyCode)) { 354 | $params['iblockCode'] = $code; 355 | $params['propertyCode'] = $propertyCode; 356 | } else { 357 | throw new Exception("Ошибка генерации params"); 358 | } 359 | 360 | # get description options 361 | $desc = (isset($options['d'])) ? $options['d'] : ""; 362 | 363 | $autoTag = "delete"; 364 | $this->_save( 365 | $this->generateObject->generateDeleteCode($params), 366 | $this->generateObject->generateAddCode($params) 367 | , $desc, 368 | $autoTag 369 | ); 370 | 371 | } 372 | 373 | /** 374 | * 375 | * 376 | * Highloadblock 377 | * 378 | * 379 | */ 380 | 381 | /** 382 | * genHlblockAdd 383 | * @param array $args 384 | * @param array $options 385 | */ 386 | public function genHlblockAdd(array $args, array $options = array()) 387 | { 388 | $dialog = new \ConsoleKit\Widgets\Dialog($this->console); 389 | $hlId = (isset($options['id'])) ? $options['id'] : false; 390 | 391 | if (!$hlId) { 392 | $do = true; 393 | while ($do) { 394 | $desk = "Put id Highloadblock - no default/required"; 395 | $hlId = $dialog->ask($desk . PHP_EOL . $this->color('[HLBLOCK_ID]:', \ConsoleKit\Colors::YELLOW), '', 396 | false); 397 | $hlblock = \Bitrix\Highloadblock\HighloadBlockTable::getById($hlId)->fetch(); 398 | if ($hlblock) { 399 | $do = false; 400 | } else { 401 | $this->error('Highloadblock with id = "' . $hlId . '" not exist.'); 402 | } 403 | } 404 | } 405 | 406 | # get description options 407 | $desc = (isset($options['d'])) ? $options['d'] : ""; 408 | 409 | $autoTag = "add"; 410 | $this->_save( 411 | $this->generateObject->generateAddCode($hlId), 412 | $this->generateObject->generateDeleteCode($hlId) 413 | , $desc, 414 | $autoTag 415 | ); 416 | 417 | } 418 | 419 | /** 420 | * genHlblockDelete 421 | * @param array $args 422 | * @param array $options 423 | */ 424 | public function genHlblockDelete(array $args, array $options = array()) 425 | { 426 | $dialog = new \ConsoleKit\Widgets\Dialog($this->console); 427 | $hlId = (isset($options['id'])) ? $options['id'] : false; 428 | 429 | if (!$hlId) { 430 | $do = true; 431 | while ($do) { 432 | $desk = "Put id Highloadblock - no default/required"; 433 | $hlId = $dialog->ask($desk . PHP_EOL . $this->color('[HLBLOCK_ID]:', \ConsoleKit\Colors::YELLOW), '', 434 | false); 435 | $hlblock = \Bitrix\Highloadblock\HighloadBlockTable::getById($hlId)->fetch(); 436 | if ($hlblock) { 437 | $do = false; 438 | } else { 439 | $this->error('Highloadblock with id = "' . $hlId . '" not exist.'); 440 | } 441 | } 442 | } 443 | 444 | # get description options 445 | $desc = (isset($options['d'])) ? $options['d'] : ""; 446 | 447 | $autoTag = "delete"; 448 | $this->_save( 449 | $this->generateObject->generateDeleteCode($hlId), 450 | $this->generateObject->generateAddCode($hlId) 451 | , $desc, 452 | $autoTag 453 | ); 454 | 455 | } 456 | 457 | /** 458 | * genHlblockFieldAdd 459 | * @param array $args 460 | * @param array $options 461 | */ 462 | public function genHlblockFieldAdd(array $args, array $options = array()) 463 | { 464 | $dialog = new \ConsoleKit\Widgets\Dialog($this->console); 465 | $hlId = (isset($options['hlblockid'])) ? $options['hlblockid'] : false; 466 | 467 | if (!$hlId) { 468 | $do = true; 469 | while ($do) { 470 | $desk = "Put id Highloadblock - no default/required"; 471 | $hlId = $dialog->ask($desk . PHP_EOL . $this->color('[HLBLOCK_ID]:', \ConsoleKit\Colors::YELLOW), '', 472 | false); 473 | $hlblock = \Bitrix\Highloadblock\HighloadBlockTable::getById($hlId)->fetch(); 474 | if ($hlblock) { 475 | $do = false; 476 | } else { 477 | $this->error('Highloadblock with id = "' . $hlId . '" not exist.'); 478 | } 479 | } 480 | } 481 | 482 | $hlFieldId = (isset($options['hlFieldId'])) ? $options['hlFieldId'] : false; 483 | if (!$hlFieldId) { 484 | $do = true; 485 | while ($do) { 486 | $desk = "Put id HighloadblockField (UserField) - no default/required"; 487 | $hlFieldId = $dialog->ask($desk . PHP_EOL . $this->color('[USER_FIELD_ID]:', 488 | \ConsoleKit\Colors::YELLOW), '', false); 489 | $userFieldData = \CUserTypeEntity::GetByID($hlFieldId); 490 | if ($userFieldData === false || empty($userFieldData)) { 491 | $this->error('UserField with id = "' . $hlFieldId . '" not exist.'); 492 | } else { 493 | $do = false; 494 | } 495 | } 496 | } 497 | 498 | # get description options 499 | $desc = (isset($options['d'])) ? $options['d'] : ""; 500 | 501 | # set 502 | $autoTag = "add"; 503 | $this->_save( 504 | $this->generateObject->generateAddCode(array("hlblockId" => $hlId, "hlFieldId" => $hlFieldId)), 505 | $this->generateObject->generateDeleteCode(array("hlblockId" => $hlId, "hlFieldId" => $hlFieldId)) 506 | , $desc, 507 | $autoTag 508 | ); 509 | } 510 | 511 | 512 | /** 513 | * genHlblockFieldDelete 514 | * @param array $args 515 | * @param array $options 516 | */ 517 | public function genHlblockFieldDelete(array $args, array $options = array()) 518 | { 519 | $dialog = new \ConsoleKit\Widgets\Dialog($this->console); 520 | $hlId = (isset($options['hlblockid'])) ? $options['hlblockid'] : false; 521 | 522 | if (!$hlId) { 523 | $do = true; 524 | while ($do) { 525 | $desk = "Put id Highloadblock - no default/required"; 526 | $hlId = $dialog->ask($desk . PHP_EOL . $this->color('[HLBLOCK_ID]:', \ConsoleKit\Colors::YELLOW), '', 527 | false); 528 | $hlblock = \Bitrix\Highloadblock\HighloadBlockTable::getById($hlId)->fetch(); 529 | if ($hlblock) { 530 | $do = false; 531 | } else { 532 | $this->error('Highloadblock with id = "' . $hlId . '" not exist.'); 533 | } 534 | } 535 | } 536 | 537 | $hlFieldId = (isset($options['hlFieldId'])) ? $options['hlFieldId'] : false; 538 | if (!$hlFieldId) { 539 | $do = true; 540 | while ($do) { 541 | $desk = "Put id HighloadblockField (UserField) - no default/required"; 542 | $hlFieldId = $dialog->ask($desk . PHP_EOL . $this->color('[USER_FIELD_ID]:', 543 | \ConsoleKit\Colors::YELLOW), '', false); 544 | $userFieldData = \CUserTypeEntity::GetByID($hlFieldId); 545 | if ($userFieldData === false || empty($userFieldData)) { 546 | $this->error('UserField with id = "' . $hlFieldId . '" not exist.'); 547 | } else { 548 | $do = false; 549 | } 550 | } 551 | } 552 | 553 | # get description options 554 | $desc = (isset($options['d'])) ? $options['d'] : ""; 555 | 556 | # set 557 | $autoTag = "delete"; 558 | $this->_save( 559 | $this->generateObject->generateDeleteCode(array("hlblockId" => $hlId, "hlFieldId" => $hlFieldId)), 560 | $this->generateObject->generateAddCode(array("hlblockId" => $hlId, "hlFieldId" => $hlFieldId)) 561 | , $desc, 562 | $autoTag 563 | ); 564 | } 565 | 566 | 567 | /** 568 | * 569 | * 570 | * Group ! 571 | * 572 | * 573 | */ 574 | /** 575 | * genGroupAdd 576 | * @param array $args 577 | * @param array $options 578 | */ 579 | public function genGroupAdd(array $args, array $options = array()) 580 | { 581 | $group = new \CGroup(); 582 | $dialog = new \ConsoleKit\Widgets\Dialog($this->console); 583 | $groupId = (isset($options['id'])) ? $options['id'] : false; 584 | 585 | if (!$groupId) { 586 | $do = true; 587 | while ($do) { 588 | $desk = "Put id Group - no default/required"; 589 | 590 | $groupId = $dialog->ask($desk . PHP_EOL . $this->color('[GROUP_ID]:', \ConsoleKit\Colors::YELLOW), '', 591 | false); 592 | 593 | $groupDbRes = $group->GetList($by = 'id', $order = 'desc', array('ID' => $groupId)); 594 | if ($groupDbRes === false || !$groupDbRes->SelectedRowsCount()) { 595 | $this->error('Group with id = "' . $groupId . '" not exist.'); 596 | } else { 597 | $do = false; 598 | } 599 | 600 | } 601 | } 602 | # get description options 603 | $desc = (isset($options['d'])) ? $options['d'] : ""; 604 | 605 | $autoTag = "add"; 606 | $this->_save( 607 | $this->generateObject->generateAddCode($groupId), 608 | $this->generateObject->generateDeleteCode($groupId) 609 | , $desc, 610 | $autoTag 611 | ); 612 | } 613 | 614 | /** 615 | * genGroupDelete 616 | * @param array $args 617 | * @param array $options 618 | */ 619 | public function genGroupDelete(array $args, array $options = array()) 620 | { 621 | $group = new \CGroup(); 622 | $dialog = new \ConsoleKit\Widgets\Dialog($this->console); 623 | $groupId = (isset($options['id'])) ? $options['id'] : false; 624 | 625 | if (!$groupId) { 626 | $do = true; 627 | while ($do) { 628 | $desk = "Put id Group - no default/required"; 629 | 630 | $groupId = $dialog->ask($desk . PHP_EOL . $this->color('[GROUP_ID]:', \ConsoleKit\Colors::YELLOW), '', 631 | false); 632 | 633 | $groupDbRes = $group->GetList($by = 'id', $order = 'desc', array('ID' => $groupId)); 634 | if ($groupDbRes === false || !$groupDbRes->SelectedRowsCount()) { 635 | $this->error('Group with id = "' . $groupId . '" not exist.'); 636 | } else { 637 | $do = false; 638 | } 639 | 640 | } 641 | } 642 | # get description options 643 | $desc = (isset($options['d'])) ? $options['d'] : ""; 644 | 645 | $autoTag = "delete"; 646 | $this->_save( 647 | $this->generateObject->generateDeleteCode($groupId), 648 | $this->generateObject->generateAddCode($groupId) 649 | , $desc, 650 | $autoTag 651 | ); 652 | } 653 | 654 | /** 655 | * genSiteAdd 656 | * @param array $args 657 | * @param array $options 658 | */ 659 | public function genSiteAdd(array $args, array $options = array()) 660 | { 661 | $dialog = new \ConsoleKit\Widgets\Dialog($this->console); 662 | $siteId = (isset($options['id'])) ? $options['id'] : false; 663 | 664 | if (!$siteId) { 665 | $do = true; 666 | while ($do) { 667 | $desk = "Put id Site - no default/required"; 668 | 669 | $siteId = $dialog->ask($desk . PHP_EOL . $this->color('[SITE_ID]:', \ConsoleKit\Colors::YELLOW), '', 670 | false); 671 | 672 | $obSite = new \CSite; 673 | $dbSite = $obSite->GetList($by = "sort", $order = "desc", array('ID' => $siteId)); 674 | if ($dbSite === false || !$dbSite->SelectedRowsCount()) { 675 | $this->error('Site with id = "' . $siteId . '" not exist.'); 676 | } else { 677 | $do = false; 678 | } 679 | 680 | } 681 | } 682 | # get description options 683 | $desc = (isset($options['d'])) ? $options['d'] : ""; 684 | 685 | $autoTag = "add"; 686 | $this->_save( 687 | $this->generateObject->generateAddCode($siteId), 688 | $this->generateObject->generateDeleteCode($siteId) 689 | , $desc, 690 | $autoTag 691 | ); 692 | } 693 | 694 | /** 695 | * 696 | * Language 697 | * 698 | */ 699 | 700 | /** 701 | * genSiteAdd 702 | * @param array $args 703 | * @param array $options 704 | */ 705 | public function genLanguageAdd(array $args, array $options = array()) 706 | { 707 | $dialog = new \ConsoleKit\Widgets\Dialog($this->console); 708 | $langId = (isset($options['id'])) ? $options['id'] : false; 709 | 710 | if (!$langId) { 711 | $do = true; 712 | while ($do) { 713 | $desk = "Put id Lang - no default/required"; 714 | $langId = $dialog->ask($desk . PHP_EOL . $this->color('[LANG_ID]:', \ConsoleKit\Colors::YELLOW), '', 715 | false); 716 | $langQuery = new \CLanguage(); 717 | $lang = $langQuery->GetList($by = "lid", $order = "desc", array('LID' => $langId)); 718 | if ($lang === false || !$lang->SelectedRowsCount()) { 719 | $this->error('Language with id = "' . $langId . '" not exist.'); 720 | } else { 721 | $do = false; 722 | } 723 | } 724 | } 725 | # get description options 726 | $desc = (isset($options['d'])) ? $options['d'] : ""; 727 | 728 | $autoTag = "add"; 729 | $this->_save( 730 | $this->generateObject->generateAddCode($langId), 731 | $this->generateObject->generateDeleteCode($langId) 732 | , $desc, 733 | $autoTag 734 | ); 735 | } 736 | 737 | 738 | 739 | /** 740 | * genSiteDelete 741 | * @param array $args 742 | * @param array $options 743 | */ 744 | public function genSiteDelete(array $args, array $options = array()) 745 | { 746 | $dialog = new \ConsoleKit\Widgets\Dialog($this->console); 747 | $siteId = (isset($options['id'])) ? $options['id'] : false; 748 | 749 | if (!$siteId) { 750 | $do = true; 751 | while ($do) { 752 | $desk = "Put id Site - no default/required"; 753 | 754 | $siteId = $dialog->ask($desk . PHP_EOL . $this->color('[SITE_ID]:', \ConsoleKit\Colors::YELLOW), '', 755 | false); 756 | 757 | $obSite = new \CSite; 758 | $dbSite = $obSite->GetList($by = "sort", $order = "desc", array('ID' => $siteId)); 759 | if ($dbSite === false || !$dbSite->SelectedRowsCount()) { 760 | $this->error('Site with id = "' . $siteId . '" not exist.'); 761 | } else { 762 | $do = false; 763 | } 764 | 765 | } 766 | } 767 | # get description options 768 | $desc = (isset($options['d'])) ? $options['d'] : ""; 769 | 770 | $autoTag = "delete"; 771 | $this->_save( 772 | $this->generateObject->generateDeleteCode($siteId), 773 | $this->generateObject->generateAddCode($siteId) 774 | , $desc, 775 | $autoTag 776 | ); 777 | } 778 | 779 | 780 | /** 781 | * 782 | * 783 | * MultiCommands ! 784 | * 785 | * @param array $args 786 | * @param array $options 787 | * @return bool 788 | * @throws Exception 789 | */ 790 | public function multiCommands(array $args, array $options = array()) 791 | { 792 | $dialog = new \ConsoleKit\Widgets\Dialog($this->console); 793 | $do = true; 794 | while ($do) { 795 | 796 | $headers = $this->getMultiHeaders(); 797 | if (!empty($headers)) { 798 | $this->padding(implode(PHP_EOL, $headers)); 799 | } 800 | $currentCommand = $this->getMultiCurrentCommand(); 801 | if (is_null($currentCommand)) { 802 | $desk = "Put generation commands:"; 803 | $command = $dialog->ask($desk . " " . $this->color('php bim gen >', \ConsoleKit\Colors::MAGENTA), '', 804 | false); 805 | if (!empty($command)) { 806 | if ($command != self::END_LOOP_SYMBOL) { 807 | $this->setMulti(true); 808 | $this->setMultiCurrentCommand($command); 809 | $this->execute(array($command)); 810 | } else { 811 | $do = false; 812 | } 813 | } else { 814 | $do = false; 815 | } 816 | } else { 817 | $ask = $dialog->ask("You want to repeat command (" . $this->color($currentCommand, 818 | \ConsoleKit\Colors::MAGENTA) . ")", 'Y', true); 819 | if (strtolower($ask) == "y") { 820 | 821 | $this->setMulti(true); 822 | $this->setMultiCurrentCommand($currentCommand); 823 | $this->execute(array($currentCommand)); 824 | 825 | } else { 826 | $this->setMultiCurrentCommand(null); 827 | } 828 | } 829 | } 830 | 831 | $addItems = $this->getMultiAddReturn(); 832 | if (empty($addItems)) { 833 | return true; 834 | } 835 | 836 | # get description options 837 | $desc = (isset($options['d'])) ? $options['d'] : ""; 838 | if (empty($desc)) { 839 | $desk = "Type Description of migration file. Example: #TASK-124"; 840 | $desc = $dialog->ask($desk . PHP_EOL . $this->color('Description:', \ConsoleKit\Colors::BLUE), "", false); 841 | } 842 | 843 | $up = $this->getMultiAddReturn(); 844 | $down = $this->getMultiDeleteReturn(); 845 | 846 | if (count($up) == count($down)) { 847 | foreach (array("add", "delete") as $it) { 848 | 849 | $i = 0; 850 | foreach ($up[$it] as $row) { 851 | # set 852 | $tmpDesc = $desc . " #" . $it; 853 | $migrationName = $this->getMigrationName() + ($i * 60); 854 | $this->saveTemplate($migrationName, 855 | $this->setTemplate( 856 | $migrationName, 857 | $row, 858 | $down[$it][$i], 859 | $tmpDesc, 860 | get_current_user() 861 | ), $it); 862 | $i++; 863 | } 864 | } 865 | } 866 | } 867 | 868 | 869 | /** 870 | * 871 | * 872 | * Other 873 | * 874 | * 875 | */ 876 | 877 | /** 878 | * createOther 879 | * @param array $args 880 | * @param array $options 881 | */ 882 | public function createOther(array $args, array $options = array()) 883 | { 884 | # get description options 885 | $desc = (isset($options['d'])) ? $options['d'] : ""; 886 | 887 | $up_data = array(); 888 | $down_data = array(); 889 | 890 | $name_method = "other"; 891 | 892 | $this->_save( 893 | $this->setTemplateMethod(strtolower($name_method), 'create', $up_data), 894 | $this->setTemplateMethod(strtolower($name_method), 'create', $down_data, "down") 895 | , $desc 896 | ); 897 | } 898 | 899 | /** 900 | * _save 901 | * @param $up_content 902 | * @param $down_content 903 | * @param bool $tag 904 | * @param $desc 905 | */ 906 | private function _save($up_content, $down_content, $desc, $tag = false) 907 | { 908 | if (!$this->isMulti()) { 909 | 910 | if (empty($desc)) { 911 | $dialog = new \ConsoleKit\Widgets\Dialog($this->console); 912 | $desk = "Type Description of migration file. Example: #TASK-124"; 913 | $desc = $dialog->ask($desk . PHP_EOL . $this->color('Description:', \ConsoleKit\Colors::BLUE), "", 914 | false); 915 | } 916 | 917 | if ($tag) { 918 | $desc = $desc . " #" . $tag; 919 | } 920 | 921 | $name_migration = $this->getMigrationName(); 922 | $this->saveTemplate($name_migration, 923 | $this->setTemplate( 924 | $name_migration, 925 | $up_content, 926 | $down_content, 927 | $desc, 928 | get_current_user() 929 | ), $tag); 930 | 931 | } else { 932 | 933 | $db = debug_backtrace(); 934 | $this->setMultiHeaders($this->color('>', \ConsoleKit\Colors::YELLOW) . " " . $db[1]['function']); 935 | $this->setMultiAddReturn($up_content, $tag); 936 | $this->setMultiDeleteReturn($down_content, $tag); 937 | 938 | } 939 | } 940 | 941 | /** 942 | * @return null 943 | */ 944 | public function getGenerateObject() 945 | { 946 | return $this->generateObject; 947 | } 948 | 949 | /** 950 | * @param null $generateObject 951 | */ 952 | public function setGenerateObject($generateObject) 953 | { 954 | $this->generateObject = $generateObject; 955 | } 956 | 957 | /** 958 | * @return boolean 959 | */ 960 | public function isMulti() 961 | { 962 | return $this->isMulti; 963 | } 964 | 965 | /** 966 | * @param boolean $isMulti 967 | */ 968 | public function setMulti($isMulti) 969 | { 970 | $this->isMulti = $isMulti; 971 | } 972 | 973 | /** 974 | * @return array 975 | */ 976 | public function getMultiAddReturn() 977 | { 978 | return (array)$this->multiAddReturn; 979 | } 980 | 981 | /** 982 | * @param array $multiAddReturn 983 | */ 984 | public function setMultiAddReturn($multiAddReturn, $type = "add") 985 | { 986 | $this->multiAddReturn[$type][] = $multiAddReturn; 987 | } 988 | 989 | /** 990 | * @return array 991 | */ 992 | public function getMultiDeleteReturn() 993 | { 994 | return (array)$this->multiDeleteReturn; 995 | } 996 | 997 | /** 998 | * @param array $multiDeleteReturn 999 | */ 1000 | public function setMultiDeleteReturn($multiDeleteReturn, $type = "add") 1001 | { 1002 | $this->multiDeleteReturn[$type][] = $multiDeleteReturn; 1003 | } 1004 | 1005 | /** 1006 | * @return array 1007 | */ 1008 | public function getMultiHeaders() 1009 | { 1010 | return $this->multiHeaders; 1011 | } 1012 | 1013 | /** 1014 | * @param $multiHeaders 1015 | * @internal param array $multiHeders 1016 | */ 1017 | public function setMultiHeaders($multiHeaders) 1018 | { 1019 | $this->multiHeaders[] = $multiHeaders; 1020 | } 1021 | 1022 | /** 1023 | * @return null 1024 | */ 1025 | public function getMultiCurrentCommand() 1026 | { 1027 | return $this->multiCurrentCommand; 1028 | } 1029 | 1030 | /** 1031 | * @param null $multiCurrentCommand 1032 | */ 1033 | public function setMultiCurrentCommand($multiCurrentCommand) 1034 | { 1035 | $this->multiCurrentCommand = $multiCurrentCommand; 1036 | } 1037 | 1038 | } 1039 | --------------------------------------------------------------------------------