Last active
March 22, 2023 19:20
-
-
Save w1cerg/8b5eb841bfe30d434ac91cc8e4210d7c to your computer and use it in GitHub Desktop.
Bitrix
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* ################################ | |
* ## Page ## | |
* ################################ | |
*/ | |
$isAdminSection = function() { | |
$requestedDir = \Bitrix\Main\Context::getCurrent()->getRequest()->getRequestedPageDirectory(); | |
return (substr($requestedDir, 0, strlen("/bitrix/admin/")) == "/bitrix/admin/" | |
|| substr($requestedDir, 0, strlen("/bitrix/updates/")) == "/bitrix/updates/" | |
|| (defined("ADMIN_SECTION") && ADMIN_SECTION == true) | |
|| (defined("BX_PUBLIC_TOOLS") && BX_PUBLIC_TOOLS === true) | |
); | |
}; | |
// Или | |
$isAdminSection = function() { | |
return Bitrix\Main\Context::getCurrent()->getRequest()->isAdminSection() | |
}; | |
$isSystemSection = function() { | |
$requestedDir = Context::getCurrent()->getRequest()->getRequestedPageDirectory(); | |
return $isAdminSection() | |
|| substr($requestedDir, 0, strlen("/bitrix/tools")) === "/bitrix/tools"; | |
} | |
$isEditModeActive = $GLOBALS['APPLICATION']->GetShowIncludeAreas(); | |
$isCurPage = function ($path) { | |
return ( CSite::InDir( $path ) ); | |
}; | |
/* | |
* ################################ | |
* ## User ## | |
* ################################ | |
*/ | |
$isAuthorized = $GLOBALS['USER']->IsAuthorized(); | |
$isCurUserAdmin = $GLOBALS['USER']->IsAdmin(); | |
$isCurUserInGroup = CSite::InGroup( array(1) ); | |
$isUserAdminById = function($userId) | |
{ | |
$userGroups = CUser::GetUserGroup( $userId ); | |
return in_array(ADMIN_USER_GROUP_ID, $userGroups); | |
}; | |
/* | |
* ################################ | |
* ## Datetime ## | |
* ################################ | |
*/ | |
// при работе в getList с датой, значение можно передавать | |
// 1. строкой в формате из настроек сайта | |
// см. https://dev.1c-bitrix.ru/api_help/main/general/date_time.php | |
// https://dev.1c-bitrix.ru/api_help/main/reference/cdatabase/dateformattophp.php | |
// https://dev.1c-bitrix.ru/api_help/main/reference/csite/getdateformat.php | |
$format = $DB->DateFormatToPHP(CSite::GetDateFormat("FULL")); | |
$filterByDate = date($format, time()); | |
// 2. или можно передавать объект класса \Bitrix\Main\Type\DateTime | |
// см. https://dev.1c-bitrix.ru/api_d7/bitrix/main/type/datetime/index.php | |
$filterByDate = new \Bitrix\Main\Type\DateTime(); | |
ElementTable::getList([ | |
'filter' => [ | |
'>TIMESTAMP_X' => $filterByDate | |
] | |
]); | |
/* | |
* ################################ | |
* ## D7 ORM ## | |
* ################################ | |
*/ | |
// Запрос разделов с дополнительными данными: | |
// - ELEMENT_CNT | |
// - Доступ к UF_ свойствам | |
$productIds = ['1', '2']; // списко ID товаров, можно и не использовать | |
/** @var \Bitrix\Main\ORM\Query\Query $querySection */ | |
$querySectionElement = \Bitrix\Iblock\SectionElementTable::query() | |
->registerRuntimeField(new \Bitrix\Main\Entity\ReferenceField( | |
'IBLOCK_SECTION_EXT', | |
\Bitrix\Iblock\Model\Section::compileEntityByIblock(IBLOCK_ID__CATALOG), | |
['=this.IBLOCK_SECTION_ID' => 'ref.ID'], | |
['join_type' => 'LEFT'] | |
)) | |
->registerRuntimeField('ELEMENT_CNT', [ | |
"expression" => array("count(%s)", "IBLOCK_ELEMENT_ID"), | |
"data_type" => "integer", | |
]) | |
->setSelect([ | |
'ID' => 'IBLOCK_SECTION_ID', | |
'NAME' => 'IBLOCK_SECTION_EXT.NAME', | |
'SECTION_PAGE_URL' => 'IBLOCK_SECTION_EXT.IBLOCK.SECTION_PAGE_URL', | |
'CODE' => 'IBLOCK_SECTION_EXT.CODE', | |
'ELEMENT_CNT', // количество записей в разделе | |
'UF_CH_NAME' => 'IBLOCK_SECTION_EXT.UF_CH_NAME' // получаем пользовательское свойство UF_ | |
]) | |
->setFilter([ | |
'IBLOCK_ELEMENT_ID' => $productIds, | |
]) | |
->setGroup(['IBLOCK_SECTION_ID']) | |
->setOrder([ | |
'ELEMENT_CNT' => 'DESC', | |
'IBLOCK_SECTION_EXT.DEPTH_LEVEL' => 'ASC', | |
'IBLOCK_SECTION_EXT.SORT' => 'ASC' | |
]); | |
// Получение разделов самого верхнего (корневого) уровня для указанных | |
$sectionIds = ['233', '332']; | |
$resSection = \Bitrix\Iblock\SectionTable::query() | |
->setSelect([ | |
'ID', | |
'ROOT_SECTION_ID' => 'ROOT_SECTION.ID', | |
'ROOT_SECTION_NAME' => 'ROOT_SECTION.NAME', | |
]) | |
->whereIn('ID', $sectionIds) | |
->where('ROOT_SECTION.DEPTH_LEVEL', '1') | |
// ->whereNull('ROOT_SECTION.IBLOCK_SECTION_ID') // Или можно так | |
->registerRuntimeField(new Reference( | |
'ROOT_SECTION', | |
\Bitrix\Iblock\SectionTable::class, | |
[ | |
'=this.IBLOCK_ID' => 'ref.IBLOCK_ID', | |
'>this.LEFT_MARGIN' => 'ref.LEFT_MARGIN', | |
'<this.RIGHT_MARGIN' => 'ref.RIGHT_MARGIN' | |
] | |
)) | |
->exec(); | |
// Получение всех дочерних разделов для указанного | |
$sectionIds = ['233', '332']; | |
$resSection = \Bitrix\Iblock\SectionTable::query() | |
->setSelect([ | |
'ID', | |
'CHILD_SECTION_ID' => 'CHILD_SECTION.ID', | |
'CHILD_SECTION_NAME' => 'CHILD_SECTION.NAME', | |
]) | |
->whereIn('ID', $sectionIds) | |
->whereNotNull('CHILD_SECTION_ID') // это нужно для ситуации когда нет дочерних, иначе будет ID = 233, CHILD = null | |
->registerRuntimeField(new Reference( | |
'CHILD_SECTION', | |
\Bitrix\Iblock\SectionTable::class, | |
[ | |
'=this.IBLOCK_ID' => 'ref.IBLOCK_ID', | |
'<this.LEFT_MARGIN' => 'ref.LEFT_MARGIN', | |
'>this.RIGHT_MARGIN' => 'ref.RIGHT_MARGIN' | |
] | |
)) | |
->exec(); | |
// Reference поле с дополнительным условием <> '' | |
class ElementTable extends \Bitrix\Main\ORM\Data\DataManager | |
{ | |
new \Bitrix\Main\ORM\Fields\Relations\Reference( | |
'CATEGORY', | |
CategoryTable::class, | |
Query::filter() | |
->where('ref.CODE', '<>', '') | |
->whereColumn('this.CATEGORY_CODE', 'ref.CODE') | |
), | |
} | |
// Получение данных свойства COLOR из инфоблока | |
$catalogEntity = \Bitrix\Iblock\IblockTable::compileEntity('catalog'); | |
$dataClass = $catalogEntity->getDataClass(); | |
// Или через ID инфоблока | |
$catalogIblock = \Bitrix\Iblock\Iblock::wakeUp(12); | |
$dataClass = $catalogIblock->getEntityDataClass() | |
$element = $dataClass::query() | |
->setSelect(['ID', 'NAME', 'COLOR_VALUE' => 'COLOR.VALUE']) | |
->setFilter(['ACTIVE' => 'Y']) | |
->setOrder(['ID' => 'desc']) | |
->setLimit(1) | |
->fetch(); | |
/* | |
* ################################ | |
* ## D7 Events ## | |
* ################################ | |
*/ | |
$eventManager = \Bitrix\Main\EventManager::getInstance(); | |
if ($eventsList = $eventManager->findEventHandlers('module_name', 'OnWhenYouNeedToFire')) { | |
$event = new \Bitrix\Main\Entity\Event('module_name', 'OnWhenYouNeedToFire'); | |
$event->send(); | |
/** @var Bitrix\Main\EventResult $eventResult */ | |
foreach($event->getResults() as $eventResult) | |
{ | |
if($eventResult->getType() == \Bitrix\Main\EventResult::SUCCESS) { | |
if ($eventResultData = $eventResult->getParameters()) { | |
if (isset($eventResultData['VALUE']) && $eventResultData['VALUE'] != $value) { | |
$value = $eventResultData['VALUE']; | |
} | |
} | |
} elseif($eventResult->getType() == \Bitrix\EventResult::ERROR) { | |
if ($eventResultData = $eventResult->getParameters()) { | |
if (isset($eventResultData) && $eventResultData instanceof \Bitrix\Sale\ResultError) { | |
/** @var ResultError $errorMsg */ | |
$errorMsg = $eventResultData; | |
} | |
} | |
} | |
} | |
} | |
/* | |
* ################################ | |
* ## D7 Debug ## | |
* ################################ | |
*/ | |
// Запись в файл логов | |
\Bitrix\Main\Diag\Debug::writeToFile(['ID' => $id, 'fields' => $fields], "varName", "/local/logs/debug.log"); | |
// Или \Bitrix\Main\Diag\Debug::writeToFile для вывода через var_dump (для булевых значений) | |
// Время выполнения: вернет массив ['test' -> ['start' => %timestamp%, 'time' => %timestamp of end%]] | |
\Bitrix\Main\Diag\Debug::startTimeLabel('test'); | |
\Bitrix\Main\Diag\Debug::endTimeLabel('test'); | |
\Bitrix\Main\Diag\Debug::getTimeLabels(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment