From a584e3d51ef62ef6238e96ad1848acadceec7034 Mon Sep 17 00:00:00 2001 From: shoman4eg Date: Mon, 20 Jul 2026 02:35:19 +0200 Subject: [PATCH 1/3] =?UTF-8?q?=D0=9F=D1=80=D0=B0=D0=B2=D0=BA=D0=B0=20?= =?UTF-8?q?=D1=84=D0=BE=D1=80=D0=BC=D0=B0=D1=82=D0=B8=D1=80=D0=BE=D0=B2?= =?UTF-8?q?=D0=B0=D0=BD=D0=B8=D1=8F=20=D0=BA=D0=BE=D0=B4-=D0=B1=D0=BB?= =?UTF-8?q?=D0=BE=D0=BA=D0=BE=D0=B2:=20=D0=BF=D1=80=D0=BE=D0=B1=D0=B5?= =?UTF-8?q?=D0=BB=D1=8B=20=D0=B2=D0=BC=D0=B5=D1=81=D1=82=D0=BE=20=D1=82?= =?UTF-8?q?=D0=B0=D0=B1=D0=BE=D0=B2,=20=D1=81=D1=82=D0=B8=D0=BB=D1=8C=20?= =?UTF-8?q?=D1=81=D0=BA=D0=BE=D0=B1=D0=BE=D0=BA,=20<=3Fphp,=20=D1=81=D1=85?= =?UTF-8?q?=D0=B5=D0=BC=D1=8B=20=D0=BF=D0=B0=D0=BF=D0=BE=D0=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pages/advanced/datetime.md | 6 +- pages/advanced/debug.md | 6 +- pages/advanced/geolocation.md | 10 +- pages/advanced/http-client.md | 74 ++-- pages/advanced/images.md | 18 +- pages/advanced/localization.md | 9 +- pages/advanced/logger.md | 12 +- pages/advanced/multisite.md | 51 +-- pages/advanced/numerator.md | 4 +- pages/advanced/quality-monitor.md | 3 +- pages/advanced/stepper.md | 9 +- pages/advanced/user-consent.md | 24 +- pages/cms-basics/admin-panel.md | 2 +- pages/cms-basics/breadcrumbs.md | 2 +- pages/cms-basics/includes.md | 6 +- pages/cms-basics/mail.md | 53 +-- pages/cms-basics/menu.md | 291 +++++++------- pages/cms-basics/page-navigation.md | 6 +- pages/cms-basics/page-templates.md | 166 ++++---- pages/cms-basics/site-templates.md | 4 +- pages/cms-basics/user-groups.md | 16 +- pages/cms-basics/userfields.md | 6 +- pages/cms-basics/users.md | 59 +-- pages/database/nosql.md | 6 +- pages/database/postgresql/compatible-code.md | 9 +- pages/database/postgresql/migration.md | 100 +++-- pages/database/sql-helper-and-expression.md | 7 +- pages/database/transactions.md | 4 +- pages/framework/autoloading.md | 12 +- pages/framework/background-jobs.md | 22 +- pages/framework/components.md | 375 +++++++++--------- pages/framework/controllers.md | 32 +- pages/framework/events.md | 20 +- pages/framework/extensions.md | 285 +++++++------ pages/framework/messenger.md | 132 +++--- pages/framework/pre-post-filters.md | 10 +- pages/framework/request-response.md | 5 +- pages/framework/results-and-errors.md | 3 +- pages/framework/routing.md | 7 +- pages/framework/service-locator.md | 3 +- pages/framework/sessions.md | 23 +- pages/framework/settings.md | 40 +- pages/framework/validation.md | 72 ++-- pages/get-started/create-component.md | 34 +- pages/get-started/create-controller.md | 63 +-- pages/get-started/create-module.md | 15 +- pages/get-started/install-distr.md | 2 +- pages/modules/architecture.md | 42 +- .../availability-prices-subscription.md | 52 +-- .../modules/catalog/bundles-sets-discounts.md | 36 +- pages/modules/catalog/catalog-settings.md | 40 +- pages/modules/catalog/export-import.md | 141 ++----- pages/modules/catalog/inventory-management.md | 45 +-- pages/modules/catalog/overview.md | 12 +- pages/modules/catalog/performance.md | 36 +- pages/modules/catalog/products-and-offers.md | 78 ++-- pages/modules/iblocks/api.md | 152 +++---- pages/modules/iblocks/architecture.md | 6 +- pages/modules/iblocks/overview.md | 3 +- pages/modules/iblocks/performance.md | 15 +- pages/orm/annotations.md | 3 +- pages/orm/collections.md | 54 ++- pages/orm/entity-operations.md | 27 +- pages/orm/entity-relations.md | 71 ++-- pages/orm/objects.md | 12 +- pages/orm/orm-concepts.md | 22 +- pages/orm/querying-data.md | 46 +-- pages/performance/caching.md | 48 +-- pages/performance/composite-site.md | 6 +- pages/performance/hot-and-cold-session.md | 2 +- pages/security/access-control.md | 2 +- pages/security/captcha.md | 18 +- pages/security/cipher.md | 7 +- pages/security/cryptofield.md | 19 +- pages/security/csrf-ssrf.md | 22 +- pages/security/secure-cookies.md | 4 +- pages/security/sql-injection.md | 4 +- pages/security/xss.md | 8 +- pages/ui/dialogs-messagebox.md | 110 ++--- pages/ui/hint.md | 4 +- 80 files changed, 1425 insertions(+), 1840 deletions(-) diff --git a/pages/advanced/datetime.md b/pages/advanced/datetime.md index d3ce198..0f70850 100644 --- a/pages/advanced/datetime.md +++ b/pages/advanced/datetime.md @@ -230,8 +230,7 @@ echo $diff->days; // 9 ```php use Bitrix\Main\Type\Date; -if (Date::isCorrect('31.02.2025', 'd.m.Y')) -{ +if (Date::isCorrect('31.02.2025', 'd.m.Y')) { // Код не выполнится, так как дата неверна } ``` @@ -296,8 +295,7 @@ $dt3 = new DateTime('2025-11-25 14:30:15+03:00', \DateTime::ATOM); use Bitrix\Main\Type\DateTime; $dt = DateTime::tryParse($request['DATE'], 'd.m.Y H:i'); - if ($dt === null) - { + if ($dt === null) { // Строка имеет неверный формат } ``` diff --git a/pages/advanced/debug.md b/pages/advanced/debug.md index 331fa62..523cd98 100644 --- a/pages/advanced/debug.md +++ b/pages/advanced/debug.md @@ -130,8 +130,7 @@ $connection->stopTracker(); $queries = $tracker->getQueries(); // Перебираем все запросы, которые были выполнены в отслеживаемом участке кода -foreach ($queries as $query) -{ +foreach ($queries as $query) { echo 'SQL: ' . $query->getSql() . '
'; echo 'Время: ' . round($query->getTime(), 5) . ' сек.
'; } @@ -158,8 +157,7 @@ $connection->stopTracker(); $queries = $tracker->getQueries(); -foreach ($queries as $query) -{ +foreach ($queries as $query) { echo 'SQL: ' . $query->getSql() . '
'; echo 'Время: ' . round($query->getTime(), 5) . ' сек.
'; } diff --git a/pages/advanced/geolocation.md b/pages/advanced/geolocation.md index d309fa6..c4a892c 100644 --- a/pages/advanced/geolocation.md +++ b/pages/advanced/geolocation.md @@ -129,8 +129,7 @@ $pos = \Bitrix\Main\Service\GeoIp\Manager::getGeoPosition('92.50.195.50'); $lat = \Bitrix\Main\Service\GeoIp\Manager::getGeoPositionLatitude('92.50.195.50'); $lon = \Bitrix\Main\Service\GeoIp\Manager::getGeoPositionLongitude('92.50.195.50'); -if ($lat !== '' && $lon !== '') -{ +if ($lat !== '' && $lon !== '') { echo "Координаты: $lat, $lon"; } ``` @@ -161,15 +160,12 @@ $geoResult = \Bitrix\Main\Service\GeoIp\Manager::getDataResult( ['countryName', 'cityName', 'latitude', 'longitude'] ); -if ($geoResult && $geoResult->isSuccess()) -{ +if ($geoResult && $geoResult->isSuccess()) { $data = $geoResult->getGeoData(); echo $data->cityName; // Калининград echo $data->countryName; // Россия echo $data->latitude; // 54.70649 -} -else -{ +} else { echo 'Нет данных для этого IP'; } ``` diff --git a/pages/advanced/http-client.md b/pages/advanced/http-client.md index 6ffc3d1..de9a290 100644 --- a/pages/advanced/http-client.md +++ b/pages/advanced/http-client.md @@ -83,6 +83,7 @@ return [ ```php use Bitrix\Main\Config\Configuration; + print_r(Configuration::getValue('http_client_options')); ``` @@ -108,13 +109,10 @@ $http = new HttpClient([ $result = $http->get('https://1c-bitrix.ru/'); -if ($result !== false) -{ +if ($result !== false) { var_dump($http->getStatus()); var_dump($http->getHeaders()); -} -else -{ +} else { var_dump($http->getError()); } ``` @@ -283,16 +281,13 @@ $body->write(http_build_query($data, '', '&')); $request = new Request(Method::POST, $uri, [], $body); -try -{ +try { $response = $http->sendRequest($request); var_dump($response->getStatusCode()); var_dump($response->getHeaders()); var_dump((string)$response->getBody()); -} -catch (ClientException $e) -{ +} catch (ClientException $e) { var_dump($e->getMessage()); } ``` @@ -328,8 +323,8 @@ $data = [ 'k1' => 'v1', 'k2' => 'v2', 'k3' => [ - 'resource' => $res, // ссылка на открытый файл - 'filename' => 'pic.jpg', // имя файла, которое увидит сервер + 'resource' => $res, // ссылка на открытый файл + 'filename' => 'pic.jpg', // имя файла, которое увидит сервер ], ]; @@ -349,16 +344,13 @@ $request = new Request(Method::POST, $uri, $headers, $body); // Закрываем файл после использования fclose($res); -try -{ +try { $response = $http->sendRequest($request); var_dump($response->getStatusCode()); var_dump($response->getHeaders()); var_dump((string)$response->getBody()); -} -catch (ClientException $e) -{ +} catch (ClientException $e) { var_dump($e->getMessage()); } ``` @@ -388,22 +380,16 @@ $http = new HttpClient([ $uri = new Uri('http://1с-битрикс.рф/'); $request = new Request(Method::GET, $uri); -try -{ - do - { +try { + do { $response = $http->sendRequest($request); - if ($response->hasHeader('Location')) - { + if ($response->hasHeader('Location')) { $location = $response->getHeader('Location')[0]; $request = $request->withUri(new Uri($location)); } - } - while ($response->hasHeader('Location')); -} -catch (ClientException $e) -{ + } while ($response->hasHeader('Location')); +} catch (ClientException $e) { var_dump($e->getMessage()); } ``` @@ -439,21 +425,16 @@ $urls = [ 'https://www.1c-bitrix.ru/', ]; -foreach ($urls as $url) -{ +foreach ($urls as $url) { $request = new Request(Method::GET, new Uri($url)); $http->sendAsyncRequest($request); } -try -{ - foreach ($http->wait() as $response) - { +try { + foreach ($http->wait() as $response) { var_dump($response->getStatusCode()); } -} -catch (ClientException $e) -{ +} catch (ClientException $e) { var_dump($e->getMessage()); } ``` @@ -467,22 +448,17 @@ catch (ClientException $e) ```php $promises = []; -foreach ($urls as $url) -{ +foreach ($urls as $url) { $request = new Request(Method::GET, new Uri($url)); $promises[] = $http->sendAsyncRequest($request); } -foreach ($promises as $promise) -{ - try - { +foreach ($promises as $promise) { + try { $response = $promise->wait(); var_dump($promise->getRequest()->getUri()->getHost()); var_dump($response->getStatusCode()); - } - catch (ClientException $e) - { + } catch (ClientException $e) { var_dump($e->getMessage()); } } @@ -497,8 +473,7 @@ foreach ($promises as $promise) Callback-функции позволяют строить цепочки обработки без блокирующих вызовов `wait()`. ```php -foreach ($urls as $url) -{ +foreach ($urls as $url) { $request = new Request(Method::GET, new Uri($url)); $promise = $http->sendAsyncRequest($request); @@ -650,8 +625,7 @@ return [ public function format($message, array $context = []): string { // Игнорировать запросы push-сервера - if ($this->request->getUri()->getPort() === 1337) - { + if ($this->request->getUri()->getPort() === 1337) { return ''; } diff --git a/pages/advanced/images.md b/pages/advanced/images.md index 5b8fe89..636dab6 100644 --- a/pages/advanced/images.md +++ b/pages/advanced/images.md @@ -156,8 +156,7 @@ $orientation = $exif['Orientation'] ?? 1; Вызовите метод `load()`, чтобы загрузить изображение в память: ```php -if ($image->load()) -{ +if ($image->load()) { // изображение успешно загружено и готово к обработке } ``` @@ -218,8 +217,7 @@ use Bitrix\Main\File\Image\Rectangle; $image = new Image('/home/bitrix/www/sticker.gif'); -if ($image->load()) -{ +if ($image->load()) { // Исходный прямоугольник по текущим размерам изображения $source = new Rectangle($image->getWidth(), $image->getHeight()); @@ -227,8 +225,7 @@ if ($image->load()) $destination = new Rectangle(400, 400); // Корректируем $destination с учетом режима пропорций - if ($source->resize($destination, Image::RESIZE_PROPORTIONAL)) - { + if ($source->resize($destination, Image::RESIZE_PROPORTIONAL)) { $image->resize($source, $destination); } } @@ -252,8 +249,7 @@ use Bitrix\Main\File\Image\Mask; $image = new Image('/home/bitrix/www/sticker.gif'); -if ($image->load()) -{ +if ($image->load()) { $image->filter(Mask::createSharpen(15)); } ``` @@ -270,8 +266,7 @@ use Bitrix\Main\File\Image\ImageWatermark; $image = new Image('/home/bitrix/www/sticker.gif'); -if ($image->load()) -{ +if ($image->load()) { $watermark = new ImageWatermark("/home/bitrix/www/watermark.png"); $watermark->setAlpha(70); // прозрачность 70% $image->drawWatermark($watermark); @@ -301,8 +296,7 @@ use Bitrix\Main\File\Image; $image = new Image('/home/bitrix/www/sticker.gif'); -if ($image->load()) -{ +if ($image->load()) { // ... после обработки $image->saveAs("/home/bitrix/www/resized_sticker.gif", 95, Image::FORMAT_GIF); // Освобождаем память diff --git a/pages/advanced/localization.md b/pages/advanced/localization.md index a389191..f4e484b 100644 --- a/pages/advanced/localization.md +++ b/pages/advanced/localization.md @@ -155,7 +155,9 @@ Loc::loadMessages($_SERVER['DOCUMENT_ROOT'] . '/local/myscript.php'); Метод `getMessage` возвращает сообщение по коду. ```php -\Bitrix\Main\Localization\Loc::getMessage($code, $replace, $language) +use Bitrix\Main\Localization\Loc; + +Loc::getMessage($code, $replace, $language) ``` - `$code` — код сообщения. Должен быть уникальным. @@ -167,7 +169,7 @@ Loc::loadMessages($_SERVER['DOCUMENT_ROOT'] . '/local/myscript.php'); В коде замените статичный текст на вызов метода `getMessage` с кодом языкового сообщения. ```php - + ``` **Пример.** Сообщение в языковом файле содержит шаблоны, вместо которых можно подставить данные. @@ -183,8 +185,7 @@ $MESS['WELCOME_TEXT'] = 'Привет, #NAME#! Количество новых В параметре `$replace` укажем, на что заменить шаблоны. ```php - 'Алексей', '#NUM#' => 5]); + 'Алексей', '#NUM#' => 5]); ?> ``` Результат — сообщение с текстом `Привет, Алексей! Количество новых сообщений: 5`. diff --git a/pages/advanced/logger.md b/pages/advanced/logger.md index a439fe3..2d484c0 100644 --- a/pages/advanced/logger.md +++ b/pages/advanced/logger.md @@ -225,8 +225,7 @@ class MyClass implements Log\LoggerAwareInterface public function doSomething() { - if ($this->logger) - { + if ($this->logger) { $this->logger->error('Error!'); } } @@ -256,16 +255,14 @@ class MyClass implements Log\LoggerAwareInterface public function doSomething() { - if ($logger = $this->getLogger()) - { + if ($logger = $this->getLogger()) { $logger->error('Error!'); } } protected function getLogger() { - if ($this->logger === null) - { + if ($this->logger === null) { $logger = Diag\Logger::create('myClassLogger', [$this]); $this->setLogger($logger); } @@ -469,8 +466,7 @@ return [ public function format($message, array $context = []): string { // Игнорируем запросы к push-серверу - if ($this->request->getUri()->getPort() === 1337) - { + if ($this->request->getUri()->getPort() === 1337) { return ''; } diff --git a/pages/advanced/multisite.md b/pages/advanced/multisite.md index 59f891d..9fbb43a 100644 --- a/pages/advanced/multisite.md +++ b/pages/advanced/multisite.md @@ -301,63 +301,46 @@ Bitrix Framework поддерживает два режима многосайт Создание символических ссылок - Символические ссылки успешно созданы."; } - } - else - { + } else { $strError = 'Указанный путь не содержит папку bitrix.'; } - } - else - { + } else { $strError = 'Неверно указан путь или ошибка прав доступа.'; } - if ($strError) - { + if ($strError) { echo '' . $strError . '
Путь: ' . htmlspecialchars($full_path); } } ?>
Путь к папке с ядром:
-

+

@@ -383,7 +366,7 @@ Bitrix Framework поддерживает два режима многосайт - `.access.php` — ограничивает доступ к публичной части сайта. Добавьте файл, если он есть на основном сайте. Файл содержит строку, которая разрешает всем пользователям просматривать корень сайта. ```php - + ``` #### Настроить виртуальные хосты @@ -701,12 +684,10 @@ setcookie("PHPSESSID", "", time() - 3600, '/', '.site.ru'); function MyOnBeforePrologHandler() { global $USER; - if (!is_object($USER)) - { + if (!is_object($USER)) { $USER = new CUser(); } - if (!$USER->IsAdmin()) - { + if (!$USER->IsAdmin()) { include($_SERVER["DOCUMENT_ROOT"] . "/coming-soon/underconstruction.html"); die(); } diff --git a/pages/advanced/numerator.md b/pages/advanced/numerator.md index c617cb9..1a951fc 100644 --- a/pages/advanced/numerator.md +++ b/pages/advanced/numerator.md @@ -117,9 +117,9 @@ $settings = Numerator::getSettingsFields('DOCUMENT'); ['settingName' => 'year', 'value' => 'year', 'title' => 'В пределах года',],], ], ['settingName' => 'timezone', 'type' => 'array', 'values' => [...]], - ..., + // ..., ], - ..., + // ..., ], 'settingsWords' => [ 'Bitrix_Main_Numerator_Generator_SequentNumberGenerator' => ['{NUMBER}' => 'Последовательный номер',], diff --git a/pages/advanced/quality-monitor.md b/pages/advanced/quality-monitor.md index 7f5382a..63d9628 100644 --- a/pages/advanced/quality-monitor.md +++ b/pages/advanced/quality-monitor.md @@ -153,8 +153,7 @@ class ProjectQualityTests { $path = $_SERVER['DOCUMENT_ROOT'] . '/favicon.ico'; - if (file_exists($path)) - { + if (file_exists($path)) { return [ 'STATUS' => true, 'MESSAGE' => [ diff --git a/pages/advanced/stepper.md b/pages/advanced/stepper.md index cf8e8cf..f33b603 100644 --- a/pages/advanced/stepper.md +++ b/pages/advanced/stepper.md @@ -31,8 +31,7 @@ class ExampleStepper extends Stepper // За один запуск обработаем один шаг и увеличим счетчик прогресса. public function execute(array &$option) { - if (empty($option)) - { + if (empty($option)) { $option['steps'] = 0; // сколько обработано $option['count'] = 100; // всего шагов } @@ -81,8 +80,7 @@ protected $deleteFile = true; ```php // Запустить через 120 секунд - if (\Bitrix\Main\Loader::includeModule('mycompany.mymodule')) - { + if (\Bitrix\Main\Loader::includeModule('mycompany.mymodule')) { \MyCompany\MyModule\Stepper\ExampleStepper::bind(120); } ``` @@ -192,8 +190,7 @@ public function execute(array &$option) ```php public function execute(array &$option) { - if (empty($option)) - { + if (empty($option)) { // Инициализация при первом запуске $option['steps'] = 0; // количество выполненных шагов $option['count'] = $this->calculateTotalItems(); // общее количество шагов diff --git a/pages/advanced/user-consent.md b/pages/advanced/user-consent.md index eef9129..0f76ce5 100644 --- a/pages/advanced/user-consent.md +++ b/pages/advanced/user-consent.md @@ -72,11 +72,7 @@ description: 'Пользовательские соглашения. Продв В файле параметров компонента `.parameters.php` объявите параметр `'USER_CONSENT' => []`. ```php - [ @@ -110,8 +106,8 @@ $arComponentParameters = [
- - IncludeComponent( + + IncludeComponent( 'bitrix:main.userconsent.request', '', [ @@ -125,7 +121,7 @@ $arComponentParameters = [ ], ] ); ?> - + ``` @@ -149,8 +145,8 @@ $arComponentParameters = [
- - IncludeComponent( + + IncludeComponent( 'bitrix:main.userconsent.request', '', [ @@ -165,7 +161,7 @@ $arComponentParameters = [ ], ] ); ?> - + ``` @@ -1086,11 +1099,11 @@ new BX.ExampleComponent({ ```javascript BX.ajax.runComponentAction(this.componentName, action, { - mode: 'class', - signedParameters: this.signedParameters, - data: data - }).then(function (response) { - // Обработка ответа + mode: 'class', + signedParameters: this.signedParameters, + data: data + }).then(function (response) { + // Обработка ответа }); ``` diff --git a/pages/framework/controllers.md b/pages/framework/controllers.md index 8e910be..d49f7e9 100644 --- a/pages/framework/controllers.md +++ b/pages/framework/controllers.md @@ -447,8 +447,7 @@ final class Post extends Controller public function listAction(\Bitrix\Main\Engine\CurrentUser $user) { $isGuest = empty($user->getId()); - if ($isGuest) - { + if ($isGuest) { $this->addError( new \Bitrix\Main\Error('Need authenticated') ); @@ -536,8 +535,7 @@ final class Post extends Controller public function getAction(string $code) { $post = \MyPost::query()->where('CODE', $code)->fetchObject(); - if (!$post) - { + if (!$post) { $this->addError( new \Bitrix\Main\Error('Not found post') ); @@ -902,19 +900,19 @@ public function viewAction(string $code): \Bitrix\Main\Engine\Response\Component ```json { - "html": "HTML код компонента", - "assets": { - // списки используемых ресурсов - "js": [], - "css": [], - "strings": [], - }, - "additionalParams": { - // дополнительные параметры респонса, если указан аргумент $additionalResponseParams - }, - "componentResult": { - // результат работы компонента, если указан аргумент $dataKeys - } + "html": "HTML код компонента", + "assets": { + // списки используемых ресурсов + "js": [], + "css": [], + "strings": [], + }, + "additionalParams": { + // дополнительные параметры респонса, если указан аргумент $additionalResponseParams + }, + "componentResult": { + // результат работы компонента, если указан аргумент $dataKeys + } } ``` diff --git a/pages/framework/events.md b/pages/framework/events.md index d36618d..b03292a 100644 --- a/pages/framework/events.md +++ b/pages/framework/events.md @@ -200,8 +200,7 @@ final class TicketService $result = new Result(); $error = $this->canClose($ticketId, $closeReason); - if ($error) - { + if ($error) { return $result->addError($error); } @@ -215,20 +214,14 @@ final class TicketService $event = new BeforeTicketCloseEvent($ticketId, $closeReason); $event->send(); - foreach ($event->getResults() as $result) - { - if ($result->getType() === EventResult::ERROR) - { + foreach ($event->getResults() as $result) { + if ($result->getType() === EventResult::ERROR) { return new Error( (string)($result->getParameters()['message'] ?? 'Unknown'), ); - } - elseif ($result->getType() === EventResult::SUCCESS) - { + } elseif ($result->getType() === EventResult::SUCCESS) { // Обработка успешного результата - } - elseif ($result->getType() === EventResult::UNDEFINED) - { + } elseif ($result->getType() === EventResult::UNDEFINED) { // Обработка неопределенного результата } } @@ -245,8 +238,7 @@ final class BeforeTicketCloseEventHandler { public static function handle(BeforeTicketCloseEvent $event): EventResult { - if (self::hasOpenTasks($event->ticketId)) - { + if (self::hasOpenTasks($event->ticketId)) { return new EventResult( EventResult::ERROR, parameters: [ diff --git a/pages/framework/extensions.md b/pages/framework/extensions.md index be0b0aa..f24730e 100644 --- a/pages/framework/extensions.md +++ b/pages/framework/extensions.md @@ -81,8 +81,8 @@ description: 'Расширения. Документация по Bitrix Framewo ```javascript module.exports = { - input: './src/app.js', - output: './dist/app.bundle.js', + input: './src/app.js', + output: './dist/app.bundle.js', }; ``` @@ -97,52 +97,52 @@ description: 'Расширения. Документация по Bitrix Framewo ```javascript module.exports = { - // Файл, для которого необходимо выполнить сборку. - // Необходимо указать относительный путь - input: string, - - // Путь к бандлу, который будет создан в результате сборки. - // Обычно это ./dist/.bundle.js - // Необходимо указать относительный путь - output: string || {js: string, css: string}, - - // Неймспейс, в который будут добавлены все экспорты из файла, - // указанного в input. Например, 'BX.Main.Filter' - namespace: string, - - // Списки файлов для принудительного объединения. - // Файлы будут объединены без проверок на дублирование кода. - // sourcemap's объединяются автоматически. - // Необходимо указать относительные пути - concat: { - js: Array, - css: Array, - }, - - // Разрешает или запрещает сборщику модифицировать config.php. - // По умолчанию true (разрешено) - adjustConfigPhp: boolean, - - // Разрешает или запрещает сборщику удалять неиспользуемый код. - // По умолчанию true (включено) - treeshake: boolean, - - // Разрешает или запрещает пересобирать бандлы, - // если сборка запущена не в корне текущего расширения. - // По умолчанию `false` (разрешено) - 'protected': boolean, - - plugins: { - // Переопределяет параметры Babel. - // Можно указать собственные параметры Babel - // https://babeljs.io/docs/en/options - // Если указать false, то код будет собран без транспиляции - babel: boolean | Object, - - // Дополнительные плагины Rollup, - // которые будут выполняться при сборке бандлов - custom: Array, - }, + // Файл, для которого необходимо выполнить сборку. + // Необходимо указать относительный путь + input: string, + + // Путь к бандлу, который будет создан в результате сборки. + // Обычно это ./dist/.bundle.js + // Необходимо указать относительный путь + output: string || {js: string, css: string}, + + // Неймспейс, в который будут добавлены все экспорты из файла, + // указанного в input. Например, 'BX.Main.Filter' + namespace: string, + + // Списки файлов для принудительного объединения. + // Файлы будут объединены без проверок на дублирование кода. + // sourcemap's объединяются автоматически. + // Необходимо указать относительные пути + concat: { + js: Array, + css: Array, + }, + + // Разрешает или запрещает сборщику модифицировать config.php. + // По умолчанию true (разрешено) + adjustConfigPhp: boolean, + + // Разрешает или запрещает сборщику удалять неиспользуемый код. + // По умолчанию true (включено) + treeshake: boolean, + + // Разрешает или запрещает пересобирать бандлы, + // если сборка запущена не в корне текущего расширения. + // По умолчанию `false` (разрешено) + 'protected': boolean, + + plugins: { + // Переопределяет параметры Babel. + // Можно указать собственные параметры Babel + // https://babeljs.io/docs/en/options + // Если указать false, то код будет собран без транспиляции + babel: boolean | Object, + + // Дополнительные плагины Rollup, + // которые будут выполняться при сборке бандлов + custom: Array, + }, // Определяет правила обработки путей к изображениям в CSS. // Доступно с версии 3.0.0 cssImages: { @@ -220,16 +220,14 @@ description: 'Расширения. Документация по Bitrix Framewo - Базовая конфигурация. ```php - if (!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED !== true) - { - die(); - } + './dist/loader.bundle.css', - 'js' => './dist/loader.bundle.js', - 'rel' => [ - 'main.core' - ] + 'css' => './dist/loader.bundle.css', + 'js' => './dist/loader.bundle.js', + 'rel' => [ + 'main.core' + ] ]; ``` @@ -237,49 +235,49 @@ description: 'Расширения. Документация по Bitrix Framewo - Все параметры. ```php - ... + // ... return [ - // Путь к `css` файлу или массив путей - // Рекомендуем указывать относительный путь - 'css' => String | Array, - - // Путь к `js` файлу или массив путей к `js` файлам - // Рекомендуем указывать относительный путь - 'js' => String | Array, - - // Список зависимостей - // Необходимо указать имена расширений, которые должны быть - // подключены перед подключением текущего расширения - // Зависимости подключаются рекурсивно и с учетом указанного порядка - 'rel' => String | Array, - - // Путь к файлу с языковыми фразами или массив путей. - // Файл `lang//config.php` подключается автоматически, - // здесь его можно не указывать - 'lang' => String | Array, - - // Запрещает подключать `main.core` автоматически как зависимость. - // По умолчанию `false` — `main.core` подключается. - // При сборке бандла значение параметра устанавливается автоматически, - // если в коде нет прямой зависимости на `main.core` - 'skip_core' => Boolean, - - // Обработчик, который вызывается перед подключением расширения на странице. - // В качестве первого параметра будет передан массив конфигурации расширения. - // Обработчик может модифицировать этот массив и вернуть из функции. - // Это полезно, когда необходимо добавить в языковые фразы - // какие-то данные с сервера - 'oninit' => Function, - - // Дополнительные языковые фразы. - // Это полезно для передачи вычисляемых значений языковых фраз. - // Принимает массив. В качестве ключей необходимо указывать идентификаторы языковых фраз - 'lang_additional' => Array, - // Параметр доступен с версии 20.5.100 модуля main. - // Параметр позволяет указать настройки, - // которые могут быть получены в JS - // с помощью метода Extension.getSettings(). - 'settings' => Array + // Путь к `css` файлу или массив путей + // Рекомендуем указывать относительный путь + 'css' => String | Array, + + // Путь к `js` файлу или массив путей к `js` файлам + // Рекомендуем указывать относительный путь + 'js' => String | Array, + + // Список зависимостей + // Необходимо указать имена расширений, которые должны быть + // подключены перед подключением текущего расширения + // Зависимости подключаются рекурсивно и с учетом указанного порядка + 'rel' => String | Array, + + // Путь к файлу с языковыми фразами или массив путей. + // Файл `lang//config.php` подключается автоматически, + // здесь его можно не указывать + 'lang' => String | Array, + + // Запрещает подключать `main.core` автоматически как зависимость. + // По умолчанию `false` — `main.core` подключается. + // При сборке бандла значение параметра устанавливается автоматически, + // если в коде нет прямой зависимости на `main.core` + 'skip_core' => Boolean, + + // Обработчик, который вызывается перед подключением расширения на странице. + // В качестве первого параметра будет передан массив конфигурации расширения. + // Обработчик может модифицировать этот массив и вернуть из функции. + // Это полезно, когда необходимо добавить в языковые фразы + // какие-то данные с сервера + 'oninit' => Function, + + // Дополнительные языковые фразы. + // Это полезно для передачи вычисляемых значений языковых фраз. + // Принимает массив. В качестве ключей необходимо указывать идентификаторы языковых фраз + 'lang_additional' => Array, + // Параметр доступен с версии 20.5.100 модуля main. + // Параметр позволяет указать настройки, + // которые могут быть получены в JS + // с помощью метода Extension.getSettings(). + 'settings' => Array ]; ``` @@ -292,29 +290,29 @@ description: 'Расширения. Документация по Bitrix Framewo ```javascript declare module 'main.loader' { - type loaderOptions = { - target?: HTMLElement, - size?: number, - mode?: 'absolute' | 'inline' | 'custom', - offset?: { - top?: string, - left?: string - }, - color?: string - }; + type loaderOptions = { + target?: HTMLElement, + size?: number, + mode?: 'absolute' | 'inline' | 'custom', + offset?: { + top?: string, + left?: string + }, + color?: string + }; - class Loader - { - constructor(options?: loaderOptions); - readonly layout: HTMLElement; - readonly circle: HTMLElement; - createLayout(): HTMLElement; - show(target?: HTMLElement): Promise; - hide(): Promise; - isShown(): boolean; - setOptions(options: loaderOptions): void; - destroy(): void; - } + class Loader + { + constructor(options?: loaderOptions); + readonly layout: HTMLElement; + readonly circle: HTMLElement; + createLayout(): HTMLElement; + show(target?: HTMLElement): Promise; + hide(): Promise; + isShown(): boolean; + setOptions(options: loaderOptions): void; + destroy(): void; + } } ``` @@ -324,33 +322,26 @@ declare module 'main.loader' Если структура `src` имеет вид: -- `src` - - - `entity` - - - `column.js` - - - `row.js` - - - `app.js` +``` +src/ +├── entity/ +│ ├── column.js +│ └── row.js +└── app.js +``` Директория `test` должна иметь следующую структуру: -- `test` - - - `entity` - - - `column` - - - `column.test.js` - - - `row` - - - `row.test.js` - - - `app` - - - `app.test.js` +``` +test/ +├── entity/ +│ ├── column/ +│ │ └── column.test.js +│ └── row/ +│ └── row.test.js +└── app/ + └── app.test.js +``` ## Использование расширений @@ -381,8 +372,8 @@ declare module 'main.loader' ```javascript import {Runtime} from 'main.core'; Runtime.loadExtension('main.loader').then((exports) => { - // Код, который использует `main.loader` - // В `exports` будут все экспорты из `main.loader` + // Код, который использует `main.loader` + // В `exports` будут все экспорты из `main.loader` }); ``` diff --git a/pages/framework/messenger.md b/pages/framework/messenger.md index 5194f40..84078db 100644 --- a/pages/framework/messenger.md +++ b/pages/framework/messenger.md @@ -53,23 +53,23 @@ use Bitrix\Main\Messenger\Entity\MessageInterface; class MyMessage extends AbstractMessage { - public function __construct( - public readonly string $text, // string — допустимый тип, сериализуется автоматически - public readonly int $superId // int — допустимый тип, сериализуется автоматически - ) {} - - public function jsonSerialize(): mixed // метод вернет массив простых типов - { - return [ - 'text' => $this->text, - 'superId' => $this->superId, - ]; - } - - public static function createFromData(array $data): MessageInterface - { - return new static(...$data); - } + public function __construct( + public readonly string $text, // string — допустимый тип, сериализуется автоматически + public readonly int $superId // int — допустимый тип, сериализуется автоматически + ) {} + + public function jsonSerialize(): mixed // метод вернет массив простых типов + { + return [ + 'text' => $this->text, + 'superId' => $this->superId, + ]; + } + + public static function createFromData(array $data): MessageInterface + { + return new static(...$data); + } } ``` @@ -83,13 +83,13 @@ use Bitrix\Main\Messenger\Receiver\AbstractReceiver; class MyReceiver extends AbstractReceiver { - /** - * @param MyMessage $message - */ - protected function process(MessageInterface $message): void - { - $this->superNotifier->send($message->text); - } + /** + * @param MyMessage $message + */ + protected function process(MessageInterface $message): void + { + $this->superNotifier->send($message->text); + } } ``` @@ -101,17 +101,17 @@ class MyReceiver extends AbstractReceiver [ - 'value' => [ - 'queues' => [ // список очередей - 'first_queue' => [ // очередь с именем 'first_queue' - 'handler' => \Bitrix\MyModule\Internals\Messenger\Receiver\MyReceiver::class, - ], - ], - ], - 'readonly' => true, // защита от перезаписи настроек через API - ], + ... // другие настройки, в том числе брокеров + 'messenger' => [ + 'value' => [ + 'queues' => [ // список очередей + 'first_queue' => [ // очередь с именем 'first_queue' + 'handler' => \Bitrix\MyModule\Internals\Messenger\Receiver\MyReceiver::class, + ], + ], + ], + 'readonly' => true, // защита от перезаписи настроек через API + ], ]; ``` @@ -148,35 +148,35 @@ $message->send('first_queue'); ```php return [ - 'messenger' => [ - 'value' => [ - 'run_mode' => 'web', // web, cli - 'brokers' => [ - 'default' => [ - 'type' => DbBroker::TYPE_CODE, // сейчас один тип — db - 'params' => [ - 'table' => MessengerMessageTable::class, - ] - ], - 'db_calendar' => [ - 'type' => 'db', - 'params' => [ - 'table' => 'b_calendar_messages', - 'module' => 'calendar', - ], - ], - ], - 'queues' => [ - 'first_queue' => [ - 'handler' => MyReceiver::class, - ], - 'google_section_sync' => [ - 'broker' => 'db_calendar', - 'handler' => GoogleSectionReceiver::class, - ], - ], - ], - 'readonly' => true, + 'messenger' => [ + 'value' => [ + 'run_mode' => 'web', // web, cli + 'brokers' => [ + 'default' => [ + 'type' => DbBroker::TYPE_CODE, // сейчас один тип — db + 'params' => [ + 'table' => MessengerMessageTable::class, + ] + ], + 'db_calendar' => [ + 'type' => 'db', + 'params' => [ + 'table' => 'b_calendar_messages', + 'module' => 'calendar', + ], + ], + ], + 'queues' => [ + 'first_queue' => [ + 'handler' => MyReceiver::class, + ], + 'google_section_sync' => [ + 'broker' => 'db_calendar', + 'handler' => GoogleSectionReceiver::class, + ], + ], + ], + 'readonly' => true, ]; ``` @@ -218,7 +218,7 @@ php bitrix.php messenger:consume ```php return [ - ... + ... 'messenger' => [ 'value' => [ 'queues' => [ @@ -588,7 +588,7 @@ interface ProcessingParamInterface ```php $message->setData([ 'task_id' => 123, - 'external_id' => 'trk-042' + 'external_id' => 'trk-042', ]); ``` diff --git a/pages/framework/pre-post-filters.md b/pages/framework/pre-post-filters.md index b4c9e0f..820c94b 100644 --- a/pages/framework/pre-post-filters.md +++ b/pages/framework/pre-post-filters.md @@ -121,16 +121,14 @@ final class RedirectGuestToLogin extends Base public function onBeforeAction(Event $event) { $isAuthorized = $this->getAction()->getController()->getCurrentUser()?->getId() > 0; - if ($isAuthorized) - { - return; - } + if ($isAuthorized) { + return; + } $requestUri = Application::getInstance() ->getContext() ->getRequest() - ->getRequestUri() - ; + ->getRequestUri(); \LocalRedirect('/login/?backurl=' . urlencode($requestUri)); } diff --git a/pages/framework/request-response.md b/pages/framework/request-response.md index 3a4f039..9f3fb1d 100644 --- a/pages/framework/request-response.md +++ b/pages/framework/request-response.md @@ -264,7 +264,8 @@ $response->setContent('Hello, world!'); // установить контент - [Zip/Archive](https://docs.1c-bitrix.ru/api/classes/Bitrix-Main-Engine-Response-Zip-Archive.html) — работает с архивом. Для NGINX можно использовать расширение mod_zip для создания архивов без нагрузки на PHP. ```php - use \Bitrix\Main\Engine\Response; + use Bitrix\Main\Engine\Response; + $archive = new Response\Zip\Archive('archive.zip'); $archive->addEntry(Response\Zip\ArchiveEntry::createFromFileId($fileId)); ``` @@ -320,7 +321,7 @@ $response->setStatus('301 Moved Permanently'); - `toJson()` — создает объект с форматом `OUTPUT_JSON_FORMAT`. ```php -use \Bitrix\Main\Engine\Response\Converter; +use Bitrix\Main\Engine\Response\Converter; // Преобразование строки: первая буква в нижний регистр + camelCase $converter = new Converter(Converter::LC_FIRST | Converter::TO_CAMEL); diff --git a/pages/framework/results-and-errors.md b/pages/framework/results-and-errors.md index b54edb9..1947491 100644 --- a/pages/framework/results-and-errors.md +++ b/pages/framework/results-and-errors.md @@ -122,8 +122,7 @@ function updateUserInDatabase(int $userId, array $fields): array function updateUserWithTypedResult(int $userId, array $fields): UserUpdateResult { $result = new UserUpdateResult(); - if ($userId <= 0) - { + if ($userId <= 0) { $result->addError(new Error('Invalid user ID', 100)); return $result; } diff --git a/pages/framework/routing.md b/pages/framework/routing.md index d7b843c..e2c2f8f 100644 --- a/pages/framework/routing.md +++ b/pages/framework/routing.md @@ -48,7 +48,7 @@ try_files $uri $uri/ /bitrix/routing_index.php; 'value' => [ 'config' => ['web.php'], // Можно добавить другие файлы: 'api.php', 'admin.php' ], - 'readonly' => true, // Защищает настройки от изменений + 'readonly' => true, // Защищает настройки от изменений ], ``` @@ -74,9 +74,7 @@ try_files $uri $uri/ /bitrix/routing_index.php; use Bitrix\Main\Routing\RoutingConfigurator; return static function (RoutingConfigurator $routes) { - $routes->any('/blog', static fn() => 'my blog'); // использует замыкание - }; ``` @@ -236,8 +234,7 @@ class PostViewAction extends \Bitrix\Main\Engine\Action implements \Bitrix\Main\ ```php $app = \Bitrix\Main\Application::getInstance(); -if ($app->hasCurrentRoute()) -{ +if ($app->hasCurrentRoute()) { $code = $app->getCurrentRoute()->getParameterValue('code'); } ``` diff --git a/pages/framework/service-locator.md b/pages/framework/service-locator.md index 64c4e93..73eb163 100644 --- a/pages/framework/service-locator.md +++ b/pages/framework/service-locator.md @@ -11,8 +11,7 @@ Service Locator — это шаблон проектирования для уп ```php $serviceLocator = \Bitrix\Main\DI\ServiceLocator::getInstance(); -if ($serviceLocator->has('someService')) -{ +if ($serviceLocator->has('someService')) { $someService = $serviceLocator->get('someService'); } ``` diff --git a/pages/framework/sessions.md b/pages/framework/sessions.md index 9435cdd..5ff5b07 100644 --- a/pages/framework/sessions.md +++ b/pages/framework/sessions.md @@ -11,9 +11,8 @@ description: 'Сессии. Документация по Bitrix Framework: пр ```php $session = \Bitrix\Main\Application::getInstance()->getSession(); -if (!$session->has('foo')) -{ - $session->set('foo', 'bar'); +if (!$session->has('foo')) { + $session->set('foo', 'bar'); } echo $session['foo']; //bar ``` @@ -95,7 +94,7 @@ define('BX_SECURITY_SESSION_VIRTUAL', true); ```php // bitrix/.settings.php return [ - //... + // ... 'session' => [ 'value' => [ 'mode' => 'default', @@ -114,6 +113,7 @@ return [ ```php // bitrix/.settings.php return [ + // ... 'session' => [ 'value' => [ 'mode' => 'default', @@ -136,7 +136,7 @@ return [ ```php // bitrix/.settings.php return [ - //... + // ... 'session' => [ 'value' => [ 'mode' => 'default', @@ -174,6 +174,7 @@ return [ ```php // bitrix/.settings.php return [ + // ... 'session' => [ 'value' => [ 'mode' => 'default', @@ -198,7 +199,7 @@ return [ ```php // bitrix/.settings.php return [ - //... + // ... 'session' => [ 'value' => [ 'mode' => 'default', @@ -219,7 +220,7 @@ return [ ```php // bitrix/.settings.php return [ - //... + // ... 'session' => [ 'value' => [ 'mode' => 'default', @@ -251,7 +252,7 @@ return [ ```php // bitrix/.settings.php return [ - //... + // ... 'session' => [ 'value' => [ 'mode' => 'default', @@ -272,7 +273,7 @@ return [ ```php // bitrix/.settings.php return [ -//... + // ... 'session' => [ 'value' => [ 'lifetime' => (int), @@ -280,7 +281,7 @@ return [ 'regenerateIdAfterLogin' => (bool), 'ignoreSessionStartErrors' => (bool), 'handlers' => [ - //... + // ... ], ] ] @@ -307,7 +308,7 @@ return [ ```php return [ - //... + // ... 'session' => [ 'value' => [ 'mode' => 'separated', diff --git a/pages/framework/settings.md b/pages/framework/settings.md index b182908..2917612 100644 --- a/pages/framework/settings.md +++ b/pages/framework/settings.md @@ -315,12 +315,12 @@ description: 'Конфигурация ядра. Документация по B 'className' => '\\Bitrix\\Main\\Diag\\FileLogger', // Класс логгера 'constructorParams' => ['/home/bitrix/www/log.txt'], // Путь к файлу с параметрами конструктора 'level' => \Psr\Log\LogLevel::DEBUG, // Уровень логирования: DEBUG, INFO, ERROR и так далее - 'formatter' => 'formatter.Arguments', // Опционально: ID форматтера из сервис-локатора + 'formatter' => 'formatter.Arguments', // Опционально: ID форматтера из сервис-локатора ], // Здесь можно добавить другие логгеры // 'my.component' => [ - ... - ], + // ... + // ], ], 'readonly' => true, // Защищает настройки от изменений во время выполнения ], @@ -337,7 +337,7 @@ description: 'Конфигурация ядра. Документация по B 'value' => [ 'config' => ['web.php'], // Можно добавить другие файлы: 'api.php', 'admin.php' ], - 'readonly' => true, // Защищает настройки от изменений + 'readonly' => true, // Защищает настройки от изменений ], ``` @@ -350,18 +350,18 @@ description: 'Конфигурация ядра. Документация по B Пример конфигурации для `memcache`: ```php - 'session' => [ - 'value' => [ - 'mode' => 'default', // Режим работы с сессиями - 'handlers' => [ - 'general' => [ - 'type' => 'memcache', // Тип хранилища - 'port' => '11211', // Порт сервера - 'host' => '127.0.0.1', // Хост сервера - ], +'session' => [ + 'value' => [ + 'mode' => 'default', // Режим работы с сессиями + 'handlers' => [ + 'general' => [ + 'type' => 'memcache', // Тип хранилища + 'port' => '11211', // Порт сервера + 'host' => '127.0.0.1', // Хост сервера ], - ] + ], ] +] ``` Подробнее в статье [Сессии](./sessions#%D0%BA%D0%BE%D0%BD%D1%84%D0%B8%D0%B3%D1%83%D1%80%D0%B0%D1%86%D0%B8%D1%8F-%D1%85%D1%80%D0%B0%D0%BD%D0%B5%D0%BD%D0%B8%D1%8F-%D0%B4%D0%B0%D0%BD%D0%BD%D1%8B%D1%85). @@ -371,12 +371,12 @@ description: 'Конфигурация ядра. Документация по B Секция `crypto` хранит ключ для шифрования конфиденциальных данных. Всегда используйте уникальный ключ. ```php - 'crypto' => [ - 'value' => [ - 'crypto_key' => 'mysupersecretphrase', // Рекомендуется использовать 32-символьную строку из a-z0-9 - ], - 'readonly' => true, - ] +'crypto' => [ + 'value' => [ + 'crypto_key' => 'mysupersecretphrase', // Рекомендуется использовать 32-символьную строку из a-z0-9 + ], + 'readonly' => true, +] ``` Подробнее в статье [Cookie-файлы](./cookies#%D1%88%D0%B8%D1%84%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%BD%D1%8B%D0%B5-cookie). diff --git a/pages/framework/validation.md b/pages/framework/validation.md index 86b6564..9b2c609 100644 --- a/pages/framework/validation.md +++ b/pages/framework/validation.md @@ -12,8 +12,7 @@ description: 'Валидация. Документация по Bitrix Framework ```php public function __construct(int $userId) { - if ($userId <= 0) - { + if ($userId <= 0) { throw new \Exception(); } $this->userId = $userId; @@ -92,8 +91,7 @@ public function __construct(int $userId) $user->setPhone($phone); $result = $this->validation->validate($user); - if (!$result->isSuccess()) - { + if (!$result->isSuccess()) { return $result; } @@ -125,6 +123,7 @@ class Buyer #[Validatable] public ?Order $order; } + class Order { #[PositiveNumber] @@ -132,6 +131,7 @@ class Order #[Validatable] public ?Payment $payment; } + class Payment { #[NotEmpty] @@ -139,6 +139,7 @@ class Payment #[NotEmpty(errorMessage: 'Custom message error')] public string $systemCode; } + // validation /** @var \Bitrix\Main\Validation\ValidationService $validationService */ $validationService = \Bitrix\Main\DI\ServiceLocator::getInstance()->get('main.validation.service'); @@ -146,22 +147,22 @@ $buyer = new Buyer(); $buyer->id = 0; $result1 = $validationService->validate($buyer); // "id: Значение поля меньше допустимого" -foreach ($result1->getErrors() as $error) -{ +foreach ($result1->getErrors() as $error) { echo $error->getCode() . ': ' . $error->getMessage(). PHP_EOL; } echo PHP_EOL; + $buyer->id = 1; $order = new Order(); $order->id = -1; $buyer->order = $order; $result2 = $validationService->validate($buyer); // "order.id: Значение поля меньше допустимого" -foreach ($result2->getErrors() as $error) -{ +foreach ($result2->getErrors() as $error) { echo $error->getCode() . ': ' . $error->getMessage(). PHP_EOL; } echo PHP_EOL; + $buyer->order->id = 123; $payment = new Payment(); $payment->status = ''; @@ -170,8 +171,7 @@ $buyer->order->payment = $payment; $result3 = $validationService->validate($buyer); // "order.payment.status: Значение поля не может быть пустым" // "order.payment.systemCode: Custom message error" -foreach ($result3->getErrors() as $error) -{ +foreach ($result3->getErrors() as $error) { echo $error->getCode() . ': ' . $error->getMessage(). PHP_EOL; } ``` @@ -202,8 +202,7 @@ final class UserSettingsDto #[ElementsType(Type::Integer)] // Используем элемент перечисления public array $favoriteIds = [] ) - { - } + {} } // Пример использования @@ -235,8 +234,7 @@ final class TagDto #[Length(max: 20)] public string $name ) - { - } + {} } final class ArticleDto @@ -246,8 +244,7 @@ final class ArticleDto #[ElementsType(TagDto::class)] public array $tags = [] ) - { - } + {} } // Использование @@ -293,8 +290,7 @@ final class CreateUserDto #[NotEmpty] public ?string $passwordRepeat, ) - { - } + {} } ``` @@ -325,8 +321,7 @@ class UserController extends Controller $dto->passwordRepeat = (string)$this->getRequest()->get('passwordRepeat'); $result = $this->validation->validate($dto); - if (!$result->isSuccess()) - { + if (!$result->isSuccess()) { $this->addErrors($result->getErrors()); return false; @@ -420,8 +415,7 @@ use Bitrix\Main\Validation\Validator\EmailValidator; $email = 'bitrix@bitrix.ru'; $validator = new EmailValidator(); $result = $validator->validate($email); -if (!$result->isSuccess()) -{ +if (!$result->isSuccess()) { // ... } ``` @@ -439,14 +433,12 @@ class User #[PositiveNumber(errorMessage: 'Invalid ID!')] public readonly int $id ) - { - } + {} } $user = new User(-150); /** @var \Bitrix\Main\Validation\ValidationService $service */ $result = $service->validate($user); -foreach ($result->getErrors() as $error) -{ +foreach ($result->getErrors() as $error) { echo $error->getMessage(); } // output: 'Invalid ID!' @@ -462,14 +454,12 @@ class User #[PositiveNumber] public readonly int $id ) - { - } + {} } $user = new User(-150); /** @var \Bitrix\Main\Validation\ValidationService $service */ $result = $service->validate($user); -foreach ($result->getErrors() as $error) -{ +foreach ($result->getErrors() as $error) { echo $error->getMessage(); } // output: 'Значение поля меньше допустимого' @@ -481,8 +471,7 @@ foreach ($result->getErrors() as $error) ```php $errors = $service->validate($dto)->getErrors(); -foreach ($errors as $error) -{ +foreach ($errors as $error) { $failedValidator = $error->getFailedValidator(); // ... } @@ -581,13 +570,12 @@ final class Min implements ValidatorInterface public function __construct( private readonly int $min ) - { - } + {} + public function validate(mixed $value): ValidationResult { $result = new ValidationResult(); - if (!is_numeric($value)) - { + if (!is_numeric($value)) { $result->addError( new ValidationError( Loc::getMessage('MAIN_VALIDATION_MIN_NOT_A_NUMBER'), @@ -596,8 +584,7 @@ final class Min implements ValidatorInterface ); return $result; } - if ($value < $this->min) - { + if ($value < $this->min) { $result->addError( new ValidationError( Loc::getMessage('MAIN_VALIDATION_MIN_LESS_THAN_MIN'), @@ -631,8 +618,7 @@ class NotOne implements PropertyValidationAttributeInterface public function validateProperty(mixed $propertyValue): ValidationResult { $result = new ValidationResult(); - if ($propertyValue === 1) - { + if ($propertyValue === 1) { $result->addError(new ValidationError('Значение не должно быть равно 1')); } return $result; @@ -660,8 +646,7 @@ final class Range extends AbstractPropertyValidationAttribute private readonly int $max, protected ?string $errorMessage = null ) - { - } + {} protected function getValidators(): array { @@ -693,8 +678,7 @@ class NotOne extends AbstractClassValidationAttribute $result = new ValidationResult(); $properties = (new ReflectionClass($object))->getProperties(); - if (count($properties) > 2) - { + if (count($properties) > 2) { $result->addError(new ValidationError('Класс содержит слишком много свойств')); } return $result; diff --git a/pages/get-started/create-component.md b/pages/get-started/create-component.md index 12cc422..dd8df6f 100644 --- a/pages/get-started/create-component.md +++ b/pages/get-started/create-component.md @@ -31,10 +31,10 @@ description: 'Создание компонента. Пошаговое руко ├── .parameters.php // Параметры компонента ├── class.php // Логика компонента ├── templates/ -│ ├── .default/ -│ │ ├── template.php // Шаблон вывода -│ │ ├── script.js // Логика для карточки -│ │ └── style.css // Стили карточки +│ └── .default/ +│ ├── template.php // Шаблон вывода +│ ├── script.js // Логика для карточки +│ └── style.css // Стили карточки └── lang/ └── ru/ └── messages.php // Локализация @@ -139,13 +139,11 @@ class UserCardComponent extends CBitrixComponent public function executeComponent() { // Кешируем результат, чтобы не делать постоянные запросы к базе - if ($this->startResultCache()) - { + if ($this->startResultCache()) { $this->initResult(); // Если ничего не найдено, отменяем кеширование - if (empty($this->arResult)) - { + if (empty($this->arResult)) { $this->abortResultCache(); ShowError('Пользователь не найден'); @@ -164,8 +162,7 @@ class UserCardComponent extends CBitrixComponent private function initResult(): void { $userId = (int)$this->arParams['USER_ID']; - if ($userId < 1) - { + if ($userId < 1) { return; } @@ -176,10 +173,9 @@ class UserCardComponent extends CBitrixComponent 'PERSONAL_PHOTO', ]) ->where('ID', $userId) - ->fetch() - ; - if (empty($user)) - { + ->fetch(); + + if (empty($user)) { return; } @@ -189,8 +185,7 @@ class UserCardComponent extends CBitrixComponent ]; // Получаем путь до аватара, если он указан - if (!empty($user['PERSONAL_PHOTO'])) - { + if (!empty($user['PERSONAL_PHOTO'])) { $this->arResult['PERSONAL_PHOTO_SRC'] = \CFile::GetPath($user['PERSONAL_PHOTO']); } } @@ -344,19 +339,16 @@ $MESS['USER_CARD_EMAIL_LABEL'] = 'E-mail:'; ```php SetTitle(''); -?> -IncludeComponent( "my:user.card", "", - Array( + [ "SHOW_EMAIL" => "Y", "USER_ID" => "1" /* или "USER_ID" => $USER->GetID() для текущего пользователя */ - ) + ] ); require($_SERVER['DOCUMENT_ROOT'] . '/bitrix/footer.php'); diff --git a/pages/get-started/create-controller.md b/pages/get-started/create-controller.md index 818eda3..dfde504 100644 --- a/pages/get-started/create-controller.md +++ b/pages/get-started/create-controller.md @@ -133,7 +133,6 @@ BX.ajax.runAction('my:module.user.like', { /* данные */ }); ```php getRequest()->getCookie(self::COOKIE_NAME); - if (empty($cookieValue)) - { + if (empty($cookieValue)) { return []; } $value = Json::decode($cookieValue); - if (!is_array($value)) - { + if (!is_array($value)) { return []; } return $value; - } - catch (ArgumentException) - { + } catch (ArgumentException) { return []; } } @@ -220,7 +214,6 @@ class LikeService ```php addError(new Error('Неверный ID пользователя')); return null; @@ -270,12 +263,9 @@ class User extends Controller // Если лайка нет — добавляем, иначе удаляем $isLikeAction = !$service->isLiked($likedUserId); - if ($isLikeAction) - { + if ($isLikeAction) { $service->likeUser($likedUserId); - } - else - { + } else { $service->dislikeUser($likedUserId); } @@ -300,9 +290,7 @@ class User extends Controller - Класс `my-user-card__like-text--liked` определяет внешний вид активного лайка. ```php -
@@ -468,16 +455,12 @@ BX.ready(() => { ```php startResultCache()) - { + if ($this->startResultCache()) { $this->initResult(); // в случае если ничего не найдено, отменяем кеширование - if (empty($this->arResult)) - { + if (empty($this->arResult)) { $this->abortResultCache(); ShowError('Пользователь не найден'); @@ -534,8 +514,7 @@ class UserCardComponent extends CBitrixComponent private function initResult(): void { $userId = (int)$this->arParams['USER_ID']; - if ($userId < 1) - { + if ($userId < 1) { return; } @@ -547,10 +526,9 @@ class UserCardComponent extends CBitrixComponent 'PERSONAL_PHOTO', ]) ->where('ID', $userId) - ->fetch() - ; - if (empty($user)) - { + ->fetch(); + + if (empty($user)) { return; } @@ -561,8 +539,7 @@ class UserCardComponent extends CBitrixComponent ]; // получаем путь до аватарки, в случае если она указана - if (!empty($user['PERSONAL_PHOTO'])) - { + if (!empty($user['PERSONAL_PHOTO'])) { $this->arResult['PERSONAL_PHOTO_SRC'] = \CFile::GetPath($user['PERSONAL_PHOTO']); } } diff --git a/pages/get-started/create-module.md b/pages/get-started/create-module.md index 23a1b9b..7b848cf 100644 --- a/pages/get-started/create-module.md +++ b/pages/get-started/create-module.md @@ -146,8 +146,7 @@ class my_module extends CModule { include __DIR__ . '/version.php'; - if (isset($arModuleVersion['VERSION'], $arModuleVersion['VERSION_DATE'])) - { + if (isset($arModuleVersion['VERSION'], $arModuleVersion['VERSION_DATE'])) { $this->MODULE_VERSION = $arModuleVersion['VERSION']; $this->MODULE_VERSION_DATE = $arModuleVersion['VERSION_DATE']; } @@ -160,8 +159,7 @@ class my_module extends CModule { global $USER, $APPLICATION; - if (!$USER->IsAdmin()) - { + if (!$USER->IsAdmin()) { return; } @@ -180,8 +178,7 @@ class my_module extends CModule { global $USER, $APPLICATION; - if (!$USER->IsAdmin()) - { + if (!$USER->IsAdmin()) { return; } @@ -253,8 +250,7 @@ class my_module extends CModule ```php false, ), // настройки обработки ошибок - 'exception_handling' => array + 'exception_handling' => array ( 'value' => array ( 'debug' => false, // режим отладки 'handled_errors_types' => 4437, // типы обрабатываемых ошибок diff --git a/pages/modules/architecture.md b/pages/modules/architecture.md index c20975d..f0aa672 100644 --- a/pages/modules/architecture.md +++ b/pages/modules/architecture.md @@ -49,8 +49,7 @@ Bitrix Framework состоит из модулей. Модуль — это а MODULE_VERSION = $arModuleVersion['VERSION']; $this->MODULE_VERSION_DATE = $arModuleVersion['VERSION_DATE'] ?? null; } @@ -254,8 +251,7 @@ class vendor_modulename extends CModule $errors = $db->executeSqlBatch( __DIR__ . '/' . $db->getType() . '/install.sql' ); - if (!empty($errors)) - { + if (!empty($errors)) { $APPLICATION->ThrowException( join(',', $errors) ); @@ -273,8 +269,7 @@ class vendor_modulename extends CModule $errors = $db->executeSqlBatch( __DIR__ . '/' . $db->getType() . '/uninstall.sql' ); - if (!empty($errors)) - { + if (!empty($errors)) { $APPLICATION->ThrowException( join(',', $errors) ); @@ -384,8 +379,7 @@ class company_module extends CModule public function InstallDB(array $params = []) { - if (($params['createDemoData'] ?? 'N') === 'Y') - { + if (($params['createDemoData'] ?? 'N') === 'Y') { // Создание демонстрационных данных модуля } @@ -396,15 +390,13 @@ class company_module extends CModule { global $APPLICATION; - if (!check_bitrix_sessid()) - { + if (!check_bitrix_sessid()) { return false; } $step = (int)($_REQUEST['step'] ?? 1); - if ($step < 2) - { + if ($step < 2) { $APPLICATION->IncludeAdminFile( 'Установка модуля', __DIR__ . '/install_step1.php' @@ -504,8 +496,7 @@ class company_module extends CModule public function DoUninstall() { - if (!check_bitrix_sessid()) - { + if (!check_bitrix_sessid()) { return false; } @@ -513,8 +504,7 @@ class company_module extends CModule $step = (int)($_REQUEST['step'] ?? 1); - if ($step < 2) - { + if ($step < 2) { $APPLICATION->IncludeAdminFile( 'Удаление модуля', __DIR__ . '/uninstall_step1.php' @@ -540,8 +530,7 @@ class company_module extends CModule public function UnInstallDB(array $params = []) { - if (($params['savedata'] ?? 'N') === 'Y') - { + if (($params['savedata'] ?? 'N') === 'Y') { return true; } @@ -559,8 +548,7 @@ class company_module extends CModule @@ -780,8 +768,7 @@ return [ ```php 'news'])->Fetch()['ID']; // Дальнейшая работа с инфоблоком } @@ -811,8 +798,7 @@ return [ 0 && \Bitrix\Main\Loader::includeModule('iblock')) - { + if ($iblockId > 0 && \Bitrix\Main\Loader::includeModule('iblock')) { // Работа с инфоблоком, который выбран в настройках модуля } ``` diff --git a/pages/modules/catalog/availability-prices-subscription.md b/pages/modules/catalog/availability-prices-subscription.md index cdaaed9..3cd3946 100644 --- a/pages/modules/catalog/availability-prices-subscription.md +++ b/pages/modules/catalog/availability-prices-subscription.md @@ -38,8 +38,7 @@ $result = \Bitrix\Catalog\Model\Product::update($productId, [ 'CAN_BUY_ZERO' => 'N', ]); -if (!$result->isSuccess()) -{ +if (!$result->isSuccess()) { throw new \RuntimeException(implode('; ', $result->getErrorMessages())); } ``` @@ -71,8 +70,7 @@ $result = \Bitrix\Catalog\Model\Product::update($offerId, [ 'CAN_BUY_ZERO' => 'N', ]); -if (!$result->isSuccess()) -{ +if (!$result->isSuccess()) { throw new \RuntimeException(implode('; ', $result->getErrorMessages())); } ``` @@ -102,8 +100,7 @@ $result = \Bitrix\Catalog\Model\Product::update($productId, [ 'NEGATIVE_AMOUNT_TRACE' => 'Y', ]); -if (!$result->isSuccess()) -{ +if (!$result->isSuccess()) { throw new \RuntimeException(implode('; ', $result->getErrorMessages())); } ``` @@ -127,8 +124,7 @@ $productRow = \Bitrix\Catalog\ProductTable::getList([ 'limit' => 1, ])->fetch(); -if (!$productRow) -{ +if (!$productRow) { throw new \RuntimeException('Товар не найден'); } ``` @@ -200,15 +196,12 @@ $price = \Bitrix\Catalog\Model\Price::getList([ ], ])->fetch(); -if ($price) -{ +if ($price) { $result = \Bitrix\Catalog\Model\Price::update((int)$price['ID'], [ 'PRICE' => 1350.00, 'CURRENCY' => 'RUB', ]); -} -else -{ +} else { $result = \Bitrix\Catalog\Model\Price::add([ 'PRODUCT_ID' => $productId, 'CATALOG_GROUP_ID' => $basePriceTypeId, @@ -217,8 +210,7 @@ else ]); } -if (!$result->isSuccess()) -{ +if (!$result->isSuccess()) { throw new \RuntimeException(implode('; ', $result->getErrorMessages())); } ``` @@ -249,8 +241,7 @@ $result = \Bitrix\Catalog\Model\Price::add([ 'QUANTITY_TO' => 9, ]); -if (!$result->isSuccess()) -{ +if (!$result->isSuccess()) { throw new \RuntimeException(implode('; ', $result->getErrorMessages())); } @@ -263,8 +254,7 @@ $result = \Bitrix\Catalog\Model\Price::add([ 'QUANTITY_TO' => null, ]); -if (!$result->isSuccess()) -{ +if (!$result->isSuccess()) { throw new \RuntimeException(implode('; ', $result->getErrorMessages())); } ``` @@ -292,8 +282,7 @@ $quantityPrice = \CCatalogProduct::GetNearestQuantityPrice( $userGroups ); -if ($quantityPrice) -{ +if ($quantityPrice) { echo $quantityPrice['PRICE']; } ``` @@ -336,8 +325,7 @@ $optimalPrice = \CCatalogProduct::GetOptimalPrice( SITE_ID ); -if ($optimalPrice) -{ +if ($optimalPrice) { echo $optimalPrice['RESULT_PRICE']['DISCOUNT_PRICE']; } ``` @@ -421,8 +409,7 @@ $subscribeId = $subscribeManager->addSubscribe([ 'USER_ID' => 15, ]); -if (!$subscribeId) -{ +if (!$subscribeId) { $error = current($subscribeManager->getErrors()); $message = $error ? $error->getMessage() : 'Не удалось добавить подписку'; @@ -452,8 +439,7 @@ $subscribeRow = \Bitrix\Catalog\SubscribeTable::getList([ 'limit' => 1, ])->fetch(); -if ($subscribeRow) -{ +if ($subscribeRow) { $subscribeId = (int)$subscribeRow['ID']; } ``` @@ -467,8 +453,7 @@ if ($subscribeRow) ```php $subscribeManager = new \Bitrix\Catalog\Product\SubscribeManager; -if (!$subscribeManager->deactivateSubscription([$subscribeId])) -{ +if (!$subscribeManager->deactivateSubscription([$subscribeId])) { $error = current($subscribeManager->getErrors()); $message = $error ? $error->getMessage() : 'Не удалось отключить подписку'; @@ -481,8 +466,7 @@ if (!$subscribeManager->deactivateSubscription([$subscribeId])) ```php $subscribeManager = new \Bitrix\Catalog\Product\SubscribeManager; -if (!$subscribeManager->deleteManySubscriptions([$subscribeId], $productId)) -{ +if (!$subscribeManager->deleteManySubscriptions([$subscribeId], $productId)) { $error = current($subscribeManager->getErrors()); $message = $error ? $error->getMessage() : 'Не удалось удалить подписку'; @@ -502,8 +486,7 @@ $unsubscribed = $subscribeManager->unSubscribe([ 'productId' => $productId, ]); -if (!$unsubscribed) -{ +if (!$unsubscribed) { $error = current($subscribeManager->getErrors()); $message = $error ? $error->getMessage() : 'Не удалось отписать пользователя'; @@ -526,8 +509,7 @@ if (!$unsubscribed) Если нужно вручную поставить активные подписки товара в очередь отправки, вызовите `runAgentToSendNotice()`. ```php -if (!\Bitrix\Catalog\SubscribeTable::runAgentToSendNotice($productId)) -{ +if (!\Bitrix\Catalog\SubscribeTable::runAgentToSendNotice($productId)) { throw new \RuntimeException('Не удалось поставить уведомления в очередь'); } ``` diff --git a/pages/modules/catalog/bundles-sets-discounts.md b/pages/modules/catalog/bundles-sets-discounts.md index f4f2af3..db0a8a9 100644 --- a/pages/modules/catalog/bundles-sets-discounts.md +++ b/pages/modules/catalog/bundles-sets-discounts.md @@ -32,8 +32,7 @@ $result = \Bitrix\Catalog\Model\Product::update($productId, [ 'TYPE' => \Bitrix\Catalog\ProductTable::TYPE_SET, ]); -if (!$result->isSuccess()) -{ +if (!$result->isSuccess()) { throw new \RuntimeException(implode('; ', $result->getErrorMessages())); } ``` @@ -78,8 +77,7 @@ $setId = \CCatalogProductSet::add([ ], ]); -if (!$setId) -{ +if (!$setId) { $errors = \CCatalogProductSet::getErrors(); $message = $errors ? $errors[0]['text'] : 'Не удалось создать комплект'; @@ -126,8 +124,7 @@ $isUpdated = \CCatalogProductSet::update($setId, [ ], ]); -if (!$isUpdated) -{ +if (!$isUpdated) { $errors = \CCatalogProductSet::getErrors(); $message = $errors ? $errors[0]['text'] : 'Не удалось обновить комплект'; @@ -173,8 +170,7 @@ $groupId = \CCatalogProductSet::add([ ], ]); -if (!$groupId) -{ +if (!$groupId) { $errors = \CCatalogProductSet::getErrors(); $message = $errors ? $errors[0]['text'] : 'Не удалось создать набор'; @@ -216,8 +212,7 @@ $isUpdated = \CCatalogProductSet::update($groupId, [ ], ]); -if (!$isUpdated) -{ +if (!$isUpdated) { $errors = \CCatalogProductSet::getErrors(); $message = $errors ? $errors[0]['text'] : 'Не удалось обновить набор'; @@ -232,8 +227,7 @@ if (!$isUpdated) Комплект или набор можно удалить с помощью `CCatalogProductSet::delete()`. В метод передайте идентификатор комплекта или набора. В примере удаляется комплект по `$setId`. ```php -if (!\CCatalogProductSet::delete($setId)) -{ +if (!\CCatalogProductSet::delete($setId)) { $errors = \CCatalogProductSet::getErrors(); $message = $errors ? $errors[0]['text'] : 'Не удалось удалить комплект или набор'; @@ -311,8 +305,7 @@ $discountId = \CCatalogDiscount::Add([ ], ]); -if (!$discountId) -{ +if (!$discountId) { global $APPLICATION; $exception = $APPLICATION->GetException(); $message = $exception ? $exception->GetString() : 'Не удалось создать скидку'; @@ -350,8 +343,7 @@ $couponResult = \Bitrix\Catalog\DiscountCouponTable::add([ 'TYPE' => \Bitrix\Catalog\DiscountCouponTable::TYPE_ONE_ORDER, ]); -if (!$couponResult->isSuccess()) -{ +if (!$couponResult->isSuccess()) { throw new \RuntimeException(implode('; ', $couponResult->getErrorMessages())); } @@ -373,13 +365,11 @@ if (!$couponResult->isSuccess()) {% endnote %} ```php -if (!\Bitrix\Main\Loader::includeModule('sale')) -{ +if (!\Bitrix\Main\Loader::includeModule('sale')) { throw new \RuntimeException('Не удалось подключить модуль sale'); } -if (!\Bitrix\Sale\DiscountCouponsManager::add('SALE-10-PRODUCT')) -{ +if (!\Bitrix\Sale\DiscountCouponsManager::add('SALE-10-PRODUCT')) { throw new \RuntimeException('Не удалось добавить купон в расчет'); } ``` @@ -409,13 +399,11 @@ $discounts = \CCatalogDiscount::GetDiscountByProduct( SITE_ID ); -if ($discounts === false) -{ +if ($discounts === false) { throw new \RuntimeException('Не удалось получить скидки товара'); } -foreach ($discounts as $discount) -{ +foreach ($discounts as $discount) { echo $discount['NAME'] . "\n"; } ``` diff --git a/pages/modules/catalog/catalog-settings.md b/pages/modules/catalog/catalog-settings.md index 052bcef..ac6373b 100644 --- a/pages/modules/catalog/catalog-settings.md +++ b/pages/modules/catalog/catalog-settings.md @@ -28,8 +28,7 @@ description: 'Базовые настройки каталога. Модуль ```php $basePriceType = \Bitrix\Catalog\GroupTable::getBasePriceType(); -if (!$basePriceType) -{ +if (!$basePriceType) { throw new \RuntimeException('Базовый тип цен не найден'); } @@ -69,8 +68,7 @@ $wholesalePriceTypeId = \CCatalogGroup::Add([ ], ]); -if (!$wholesalePriceTypeId) -{ +if (!$wholesalePriceTypeId) { global $APPLICATION; $exception = $APPLICATION->GetException(); $message = $exception ? $exception->GetString() : 'Не удалось создать тип цены'; @@ -114,8 +112,7 @@ $accessRows = \Bitrix\Catalog\GroupAccessTable::getList([ ], ])->fetchAll(); -foreach ($accessRows as $row) -{ +foreach ($accessRows as $row) { if ($row['ACCESS'] === 'ACCESS_VIEW') { echo "Группа {$row['GROUP_ID']} видит цену\n"; } @@ -156,8 +153,7 @@ $result = \Bitrix\Catalog\Model\Vat::add([ 'SORT' => 100, ]); -if (!$result->isSuccess()) -{ +if (!$result->isSuccess()) { throw new \RuntimeException(implode('; ', $result->getErrorMessages())); } @@ -188,8 +184,7 @@ $result = \Bitrix\Catalog\Model\Product::update($productId, [ 'VAT_INCLUDED' => 'Y', ]); -if (!$result->isSuccess()) -{ +if (!$result->isSuccess()) { throw new \RuntimeException(implode('; ', $result->getErrorMessages())); } ``` @@ -233,22 +228,19 @@ $productRow = \Bitrix\Catalog\ProductTable::getList([ 'limit' => 1, ])->fetch(); -if (!$productRow) -{ +if (!$productRow) { throw new \RuntimeException('Товар не найден в каталоге'); } $vatRate = null; -if ((int)$productRow['VAT_ID'] > 0) -{ +if ((int)$productRow['VAT_ID'] > 0) { $vatRow = \Bitrix\Catalog\VatTable::getList([ 'select' => ['ID', 'NAME', 'RATE', 'ACTIVE'], 'filter' => ['=ID' => (int)$productRow['VAT_ID']], 'limit' => 1, ])->fetch(); - if ($vatRow) - { + if ($vatRow) { $vatRate = (float)$vatRow['RATE']; } } @@ -280,8 +272,7 @@ $result = \Bitrix\Catalog\MeasureTable::add([ 'IS_DEFAULT' => 'N', ]); -if (!$result->isSuccess()) -{ +if (!$result->isSuccess()) { throw new \RuntimeException(implode('; ', $result->getErrorMessages())); } @@ -321,8 +312,7 @@ $result = \Bitrix\Catalog\Model\Product::update($productId, [ 'MEASURE' => $measureId, ]); -if (!$result->isSuccess()) -{ +if (!$result->isSuccess()) { throw new \RuntimeException(implode('; ', $result->getErrorMessages())); } ``` @@ -361,15 +351,12 @@ $ratioRow = \Bitrix\Catalog\MeasureRatioTable::getList([ ])->fetch(); // Обновляем существующий коэффициент или создаем новый -if ($ratioRow) -{ +if ($ratioRow) { // У товара есть коэффициент -- обновляем его $result = \Bitrix\Catalog\MeasureRatioTable::update((int)$ratioRow['ID'], [ 'RATIO' => $ratioValue, ]); -} -else -{ +} else { // У товара нет коэффициента -- создаем новый $result = \Bitrix\Catalog\MeasureRatioTable::add([ 'PRODUCT_ID' => $productId, @@ -379,8 +366,7 @@ else } // Проверяем результат -if (!$result->isSuccess()) -{ +if (!$result->isSuccess()) { throw new \RuntimeException(implode('; ', $result->getErrorMessages())); } ``` diff --git a/pages/modules/catalog/export-import.md b/pages/modules/catalog/export-import.md index 32dae40..d252743 100644 --- a/pages/modules/catalog/export-import.md +++ b/pages/modules/catalog/export-import.md @@ -67,29 +67,19 @@ $productIblockId = (int)$IBLOCK_ID; $exportFile = (string)$SETUP_FILE_NAME; $allowedDirectory = '/upload/export/'; -if ($productIblockId <= 0) -{ +if ($productIblockId <= 0) { $strExportErrorMessage = 'Не выбран инфоблок каталога'; -} -elseif ($exportFile === '') -{ +} elseif ($exportFile === '') { $strExportErrorMessage = 'Не указан файл экспорта'; -} -elseif (strncmp($exportFile, $allowedDirectory, strlen($allowedDirectory)) !== 0) -{ +} elseif (strncmp($exportFile, $allowedDirectory, strlen($allowedDirectory)) !== 0) { $strExportErrorMessage = 'Файл экспорта должен находиться в /upload/export/'; -} -else -{ +} else { $filePath = $_SERVER['DOCUMENT_ROOT'] . $exportFile; $file = fopen($filePath, 'wb'); - if (!$file) - { + if (!$file) { $strExportErrorMessage = 'Не удалось открыть файл экспорта'; - } - else - { + } else { fputcsv($file, ['ID', 'XML_ID', 'NAME'], ';'); $elementsIterator = \CIBlockElement::GetList( @@ -103,8 +93,7 @@ else ['ID', 'XML_ID', 'NAME'] ); - while ($element = $elementsIterator->Fetch()) - { + while ($element = $elementsIterator->Fetch()) { fputcsv( $file, [ @@ -144,37 +133,29 @@ else ```php $errorMessage = ''; -if ($STEP > 1) -{ +if ($STEP > 1) { $IBLOCK_ID = (int)$IBLOCK_ID; - if ($IBLOCK_ID <= 0) - { + if ($IBLOCK_ID <= 0) { $errorMessage .= 'Инфоблок не выбран.
'; } - if ((string)$SETUP_FILE_NAME === '') - { + if ((string)$SETUP_FILE_NAME === '') { $errorMessage .= 'Не указан файл данных.
'; } - if ($ACTION === 'EXPORT_SETUP' && (string)$SETUP_PROFILE_NAME === '') - { + if ($ACTION === 'EXPORT_SETUP' && (string)$SETUP_PROFILE_NAME === '') { $errorMessage .= 'Не указано имя профиля.
'; } - if ($errorMessage !== '') - { + if ($errorMessage !== '') { $STEP = 1; } } -if ((int)$STEP === 1) -{ +if ((int)$STEP === 1) { $SETUP_FIELDS_LIST = 'IBLOCK_ID,SETUP_FILE_NAME'; -} -elseif ((int)$STEP === 2) -{ +} elseif ((int)$STEP === 2) { $FINITE = true; } ``` @@ -220,8 +201,7 @@ $exportProfileId = \CCatalogExport::Add([ 'SETUP_VARS' => $setupVars, ]); -if (!$exportProfileId) -{ +if (!$exportProfileId) { throw new \RuntimeException('Не удалось создать профиль экспорта'); } ``` @@ -237,8 +217,7 @@ if (!$exportProfileId) ```php $agentCall = \CCatalogExport::PreGenerateExport($exportProfileId); -if ($agentCall === false) -{ +if ($agentCall === false) { throw new \RuntimeException('Не удалось запустить экспорт по профилю'); } ``` @@ -257,8 +236,7 @@ $profilesIterator = \CCatalogExport::GetList( ['IN_MENU' => 'Y'] ); -while ($profile = $profilesIterator->Fetch()) -{ +while ($profile = $profilesIterator->Fetch()) { echo $profile['ID'] . ': ' . $profile['NAME'] . "\n"; } @@ -290,8 +268,7 @@ $updatedExportProfileId = \CCatalogExport::Update($exportProfileId, [ ]), ]); -if (!$updatedExportProfileId) -{ +if (!$updatedExportProfileId) { throw new \RuntimeException('Не удалось обновить профиль экспорта'); } @@ -325,44 +302,30 @@ $productIblockId = (int)$IBLOCK_ID; $dataFile = (string)$URL_DATA_FILE; $allowedDirectory = '/upload/import/'; -if ($productIblockId <= 0) -{ +if ($productIblockId <= 0) { $strImportErrorMessage = 'Не выбран инфоблок каталога'; -} -elseif ($dataFile === '') -{ +} elseif ($dataFile === '') { $strImportErrorMessage = 'Не указан файл импорта'; -} -elseif (strncmp($dataFile, $allowedDirectory, strlen($allowedDirectory)) !== 0) -{ +} elseif (strncmp($dataFile, $allowedDirectory, strlen($allowedDirectory)) !== 0) { $strImportErrorMessage = 'Файл импорта должен находиться в /upload/import/'; -} -elseif (!is_readable($_SERVER['DOCUMENT_ROOT'] . $dataFile)) -{ +} elseif (!is_readable($_SERVER['DOCUMENT_ROOT'] . $dataFile)) { $strImportErrorMessage = 'Файл импорта недоступен для чтения'; -} -else -{ +} else { $file = fopen($_SERVER['DOCUMENT_ROOT'] . $dataFile, 'rb'); $element = new \CIBlockElement; - if (!$file) - { + if (!$file) { $strImportErrorMessage = 'Не удалось открыть файл импорта'; - } - else - { + } else { fgetcsv($file, 0, ';'); // пропускаем строку заголовков - while (($row = fgetcsv($file, 0, ';')) !== false) - { + while (($row = fgetcsv($file, 0, ';')) !== false) { [$xmlId, $name] = array_pad($row, 2, ''); $xmlId = trim((string)$xmlId); $name = trim((string)$name); - if ($xmlId === '' || $name === '') - { + if ($xmlId === '' || $name === '') { $strImportErrorMessage = 'В файле импорта есть строка без XML_ID или названия'; break; } @@ -378,14 +341,11 @@ else ['ID'] )->Fetch(); - if ($elementRow) - { + if ($elementRow) { $result = $element->Update((int)$elementRow['ID'], [ 'NAME' => $name, ]); - } - else - { + } else { $result = $element->Add([ 'IBLOCK_ID' => $productIblockId, 'XML_ID' => $xmlId, @@ -394,8 +354,7 @@ else ]); } - if (!$result) - { + if (!$result) { $strImportErrorMessage = $element->LAST_ERROR ?: 'Не удалось сохранить элемент каталога'; break; } @@ -429,37 +388,29 @@ else ```php $errorMessage = ''; -if ($STEP > 1) -{ +if ($STEP > 1) { $IBLOCK_ID = (int)$IBLOCK_ID; - if ($IBLOCK_ID <= 0) - { + if ($IBLOCK_ID <= 0) { $errorMessage .= 'Инфоблок не выбран.
'; } - if ((string)$URL_DATA_FILE === '') - { + if ((string)$URL_DATA_FILE === '') { $errorMessage .= 'Не указан файл импорта.
'; } - if ($ACTION === 'IMPORT_SETUP' && (string)$SETUP_PROFILE_NAME === '') - { + if ($ACTION === 'IMPORT_SETUP' && (string)$SETUP_PROFILE_NAME === '') { $errorMessage .= 'Не указано имя профиля.
'; } - if ($errorMessage !== '') - { + if ($errorMessage !== '') { $STEP = 1; } } -if ((int)$STEP === 1) -{ +if ((int)$STEP === 1) { $SETUP_FIELDS_LIST = 'IBLOCK_ID,URL_DATA_FILE'; -} -elseif ((int)$STEP === 2) -{ +} elseif ((int)$STEP === 2) { $FINITE = true; } ``` @@ -485,8 +436,7 @@ $importProfileId = \CCatalogImport::Add([ ]), ]); -if (!$importProfileId) -{ +if (!$importProfileId) { throw new \RuntimeException('Не удалось создать профиль импорта'); } ``` @@ -502,8 +452,7 @@ if (!$importProfileId) ```php $agentCall = \CCatalogImport::PreGenerateImport($importProfileId); -if ($agentCall === false) -{ +if ($agentCall === false) { throw new \RuntimeException('Не удалось запустить импорт по профилю'); } ``` @@ -522,8 +471,7 @@ $profilesIterator = \CCatalogImport::GetList( ['FILE_NAME' => 'furniture_csv'] ); -while ($profile = $profilesIterator->Fetch()) -{ +while ($profile = $profilesIterator->Fetch()) { echo $profile['ID'] . ': ' . $profile['NAME'] . "\n"; } @@ -533,8 +481,7 @@ $updatedImportProfileId = \CCatalogImport::Update($importProfileId, [ 'NAME' => 'Импорт мебели из CSV по расписанию', ]); -if (!$updatedImportProfileId) -{ +if (!$updatedImportProfileId) { throw new \RuntimeException('Не удалось обновить профиль импорта'); } @@ -584,15 +531,13 @@ if (!$updatedImportProfileId) ```php $profile = \CCatalogExport::GetByID($exportProfileId); -if (!$profile) -{ +if (!$profile) { throw new \RuntimeException('Профиль экспорта не найден'); } $exportFile = '/upload/export/furniture.csv'; -if (!is_readable($_SERVER['DOCUMENT_ROOT'] . $exportFile)) -{ +if (!is_readable($_SERVER['DOCUMENT_ROOT'] . $exportFile)) { throw new \RuntimeException('Файл экспорта не найден'); } ``` diff --git a/pages/modules/catalog/inventory-management.md b/pages/modules/catalog/inventory-management.md index 4bfc021..a44c168 100644 --- a/pages/modules/catalog/inventory-management.md +++ b/pages/modules/catalog/inventory-management.md @@ -10,8 +10,7 @@ description: 'Складской учет. Модуль Торговый кат Перед выполнением примеров подключите модуль `catalog` и проверьте права пользователя на изменение данных каталога и складских документов. ```php -if (!\Bitrix\Main\Loader::includeModule('catalog')) -{ +if (!\Bitrix\Main\Loader::includeModule('catalog')) { throw new \RuntimeException('Не удалось подключить модуль catalog'); } ``` @@ -71,8 +70,7 @@ $storeId = \CCatalogStore::Add([ 'SORT' => 100, ]); -if (!$storeId) -{ +if (!$storeId) { global $APPLICATION; $exception = $APPLICATION->GetException(); $message = $exception ? $exception->GetString() : 'Не удалось создать склад'; @@ -168,8 +166,7 @@ $contractorId = \CCatalogContractor::add([ 'KPP' => '770001001', ]); -if (!$contractorId) -{ +if (!$contractorId) { global $APPLICATION; $exception = $APPLICATION->GetException(); $message = $exception ? $exception->GetString() : 'Не удалось создать поставщика-юрлицо'; @@ -198,8 +195,7 @@ $contractorId = \CCatalogContractor::add([ 'INN' => '390000000000', ]); -if (!$contractorId) -{ +if (!$contractorId) { global $APPLICATION; $exception = $APPLICATION->GetException(); $message = $exception ? $exception->GetString() : 'Не удалось создать поставщика-физлицо'; @@ -248,8 +244,7 @@ $storeProductId = \CCatalogStoreProduct::Add([ 'AMOUNT' => 12, ]); -if (!$storeProductId) -{ +if (!$storeProductId) { global $APPLICATION; $exception = $APPLICATION->GetException(); $message = $exception ? $exception->GetString() : 'Не удалось записать остаток на складе'; @@ -269,8 +264,7 @@ $storeProductResult = \CCatalogStoreProduct::UpdateFromForm([ 'AMOUNT' => 15, // числовое значение остатка ]); -if (!$storeProductResult) -{ +if (!$storeProductResult) { global $APPLICATION; $exception = $APPLICATION->GetException(); $message = $exception ? $exception->GetString() : 'Не удалось обновить остаток на складе'; @@ -299,8 +293,7 @@ $barcodeResult = \Bitrix\Catalog\StoreBarcodeTable::add([ 'CREATED_BY' => $responsibleUserId, ]); -if (!$barcodeResult->isSuccess()) -{ +if (!$barcodeResult->isSuccess()) { throw new \RuntimeException(implode('; ', $barcodeResult->getErrorMessages())); } @@ -322,13 +315,11 @@ $barcodeRow = \Bitrix\Catalog\StoreBarcodeTable::getList([ 'limit' => 1, ])->fetch(); -if (!$barcodeRow) -{ +if (!$barcodeRow) { throw new \RuntimeException('Штрихкод не найден'); } -if ((int)$barcodeRow['PRODUCT_ID'] !== $productId) -{ +if ((int)$barcodeRow['PRODUCT_ID'] !== $productId) { throw new \RuntimeException('Штрихкод относится к другому товару'); } ``` @@ -458,8 +449,7 @@ $documentId = \CCatalogDocs::add([ ], ]); -if (!$documentId) -{ +if (!$documentId) { global $APPLICATION; $exception = $APPLICATION->GetException(); $message = $exception ? $exception->GetString() : 'Не удалось создать документ'; @@ -613,8 +603,7 @@ $documentRows = \Bitrix\Catalog\StoreDocumentElementTable::getList([ ```php $conducted = \CCatalogDocs::conductDocument($documentId, $responsibleUserId); -if (!$conducted) -{ +if (!$conducted) { global $APPLICATION; $exception = $APPLICATION->GetException(); $message = $exception ? $exception->GetString() : 'Не удалось провести документ'; @@ -634,8 +623,7 @@ if (!$conducted) ```php $cancelled = \CCatalogDocs::cancellationDocument($documentId, $responsibleUserId); -if (!$cancelled) -{ +if (!$cancelled) { global $APPLICATION; $exception = $APPLICATION->GetException(); $message = $exception ? $exception->GetString() : 'Не удалось отменить проведение документа'; @@ -669,8 +657,7 @@ $storeRows = \Bitrix\Catalog\StoreProductTable::getList([ ], ])->fetchAll(); -foreach ($storeRows as $row) -{ +foreach ($storeRows as $row) { echo $row['STORE_TITLE'] . ': ' . $row['AMOUNT'] . "\n"; } ``` @@ -735,8 +722,7 @@ $storeProductRow = \Bitrix\Catalog\StoreProductTable::getList([ 'limit' => 1, ])->fetch(); -if (!$storeProductRow) -{ +if (!$storeProductRow) { throw new \RuntimeException('Остаток товара на складе не найден'); } @@ -814,8 +800,7 @@ $documentRows = \Bitrix\Catalog\StoreDocumentElementTable::getList([ $documentElementIds = array_column($documentRows, 'ID'); $batchRows = []; -if (!empty($documentElementIds)) -{ +if (!empty($documentElementIds)) { $batchRows = \Bitrix\Catalog\StoreBatchDocumentElementTable::getList([ 'select' => [ 'PRODUCT_BATCH_ID', diff --git a/pages/modules/catalog/overview.md b/pages/modules/catalog/overview.md index 474e73e..945ffa9 100644 --- a/pages/modules/catalog/overview.md +++ b/pages/modules/catalog/overview.md @@ -153,16 +153,14 @@ $catalogCreated = \CCatalog::Add([ 'SKU_PROPERTY_ID' => 0, ]); -if (!$catalogCreated) -{ +if (!$catalogCreated) { throw new \RuntimeException('Не удалось создать торговый каталог'); } // Получить базовый тип цены для добавления цены товара $basePriceType = \Bitrix\Catalog\GroupTable::getBasePriceType(); -if (!$basePriceType) -{ +if (!$basePriceType) { throw new \RuntimeException('Базовый тип цен не найден'); } @@ -179,8 +177,7 @@ $productResult = \Bitrix\Catalog\Model\Product::add([ ]); // Проверить результат создания товара -if (!$productResult->isSuccess()) -{ +if (!$productResult->isSuccess()) { throw new \RuntimeException(implode('; ', $productResult->getErrorMessages())); } @@ -193,8 +190,7 @@ $priceResult = \Bitrix\Catalog\Model\Price::add([ ]); // Проверить результат создания цены -if (!$priceResult->isSuccess()) -{ +if (!$priceResult->isSuccess()) { throw new \RuntimeException(implode('; ', $priceResult->getErrorMessages())); } ``` diff --git a/pages/modules/catalog/performance.md b/pages/modules/catalog/performance.md index 6ee7e3b..72712ba 100644 --- a/pages/modules/catalog/performance.md +++ b/pages/modules/catalog/performance.md @@ -39,8 +39,7 @@ description: 'Производительность и частые ошибки. Неверный подход: ```php -foreach ($productIds as $productId) -{ +foreach ($productIds as $productId) { $price = \Bitrix\Catalog\PriceTable::getList([ 'select' => ['PRICE', 'CURRENCY'], 'filter' => ['=PRODUCT_ID' => $productId], @@ -69,8 +68,7 @@ $priceIterator = \Bitrix\Catalog\PriceTable::getList([ ], ]); -while ($price = $priceIterator->fetch()) -{ +while ($price = $priceIterator->fetch()) { $priceMap[(int)$price['PRODUCT_ID']] = $price; } ``` @@ -233,8 +231,7 @@ $result = \Bitrix\Catalog\Model\Price::update($priceId, [ 'CURRENCY' => 'RUB', ]); -if (!$result->isSuccess()) -{ +if (!$result->isSuccess()) { throw new \RuntimeException(implode('; ', $result->getErrorMessages())); } ``` @@ -262,8 +259,7 @@ $result = \Bitrix\Catalog\Model\Price::recountPricesFromBase([ 'PRODUCT_ID' => $productId, ]); -if (!$result->isSuccess()) -{ +if (!$result->isSuccess()) { throw new \RuntimeException(implode('; ', $result->getErrorMessages())); } ``` @@ -325,13 +321,11 @@ $iterator = \CIBlockElement::GetList( Подключайте модули `iblock` и `catalog` до обращения к таблицам каталога: ```php -if (!\Bitrix\Main\Loader::includeModule('iblock')) -{ +if (!\Bitrix\Main\Loader::includeModule('iblock')) { throw new \Bitrix\Main\SystemException('Модуль iblock не установлен.'); } -if (!\Bitrix\Main\Loader::includeModule('catalog')) -{ +if (!\Bitrix\Main\Loader::includeModule('catalog')) { throw new \Bitrix\Main\SystemException('Модуль catalog не установлен.'); } ``` @@ -353,8 +347,7 @@ $result = \Bitrix\Catalog\Model\Product::add([ 'QUANTITY' => 100, ]); -if (!$result->isSuccess()) -{ +if (!$result->isSuccess()) { throw new \RuntimeException(implode('; ', $result->getErrorMessages())); } ``` @@ -387,8 +380,7 @@ if (!$result->isSuccess()) $limit = 500; $offset = 0; -do -{ +do { $rows = \Bitrix\Catalog\ProductTable::getList([ 'select' => ['ID', 'QUANTITY', 'TYPE'], 'order' => ['ID' => 'ASC'], @@ -396,14 +388,12 @@ do 'offset' => $offset, ])->fetchAll(); - foreach ($rows as $row) - { + foreach ($rows as $row) { // Обработать товар } $offset += $limit; -} -while (!empty($rows)); +} while (!empty($rows)); ``` ### Неверная передача параметров в GetOptimalPriceList @@ -422,8 +412,7 @@ while (!empty($rows)); $currentPage = (int)($_GET['PAGEN_1'] ?? 1); $pageCount = (int)$arResult['NAV_RESULT']->NavPageCount; -if ($currentPage > $pageCount) -{ +if ($currentPage > $pageCount) { \CHTTP::SetStatus('404 Not Found'); require $_SERVER['DOCUMENT_ROOT'] . '/404.php'; exit; @@ -437,8 +426,7 @@ if ($currentPage > $pageCount) ```php $catalogInfo = \CCatalogSKU::getInfoByIBlock($iblockId); -if (!$catalogInfo) -{ +if (!$catalogInfo) { return; } diff --git a/pages/modules/catalog/products-and-offers.md b/pages/modules/catalog/products-and-offers.md index 822544c..062ded1 100644 --- a/pages/modules/catalog/products-and-offers.md +++ b/pages/modules/catalog/products-and-offers.md @@ -42,8 +42,7 @@ $productIblockId = $iblock->Add([ 'LID' => ['s1'], ]); -if (!$productIblockId) -{ +if (!$productIblockId) { throw new \RuntimeException($iblock->getLastError()->getMessage()); } ``` @@ -78,8 +77,7 @@ $result = \CCatalog::Add([ 'SKU_PROPERTY_ID' => 0, ]); -if (!$result) -{ +if (!$result) { throw new \RuntimeException('Не удалось создать торговый каталог'); } ``` @@ -117,8 +115,7 @@ $productId = $element->Add([ 'ACTIVE' => 'Y', ]); -if (!$productId) -{ +if (!$productId) { throw new \RuntimeException($element->LAST_ERROR); } @@ -131,8 +128,7 @@ $result = \Bitrix\Catalog\Model\Product::add([ 'SUBSCRIBE' => 'Y', ]); -if (!$result->isSuccess()) -{ +if (!$result->isSuccess()) { throw new \RuntimeException(implode('; ', $result->getErrorMessages())); } ``` @@ -167,8 +163,7 @@ $result = \Bitrix\Catalog\Model\Price::add([ 'CURRENCY' => 'RUB', ]); -if (!$result->isSuccess()) -{ +if (!$result->isSuccess()) { throw new \RuntimeException(implode('; ', $result->getErrorMessages())); } ``` @@ -200,8 +195,7 @@ $serviceId = $element->Add([ 'ACTIVE' => 'Y', ]); -if (!$serviceId) -{ +if (!$serviceId) { throw new \RuntimeException($element->LAST_ERROR); } @@ -210,8 +204,7 @@ $productResult = \Bitrix\Catalog\Model\Product::add([ 'TYPE' => \Bitrix\Catalog\ProductTable::TYPE_SERVICE, ]); -if (!$productResult->isSuccess()) -{ +if (!$productResult->isSuccess()) { throw new \RuntimeException(implode('; ', $productResult->getErrorMessages())); } @@ -222,8 +215,7 @@ $priceResult = \Bitrix\Catalog\Model\Price::add([ 'CURRENCY' => 'RUB', ]); -if (!$priceResult->isSuccess()) -{ +if (!$priceResult->isSuccess()) { throw new \RuntimeException(implode('; ', $priceResult->getErrorMessages())); } ``` @@ -276,8 +268,7 @@ $productIblockId = $iblock->Add([ 'LID' => ['s1'], // массив кодов сайтов для привязки ]); -if (!$productIblockId) -{ +if (!$productIblockId) { throw new \RuntimeException($iblock->getLastError()->getMessage()); } @@ -290,8 +281,7 @@ $offerIblockId = $iblock->Add([ 'LID' => ['s1'], ]); -if (!$offerIblockId) -{ +if (!$offerIblockId) { throw new \RuntimeException($iblock->getLastError()->getMessage()); } ``` @@ -330,8 +320,7 @@ $skuPropertyId = $property->Add([ 'MULTIPLE' => 'N', ]); -if (!$skuPropertyId) -{ +if (!$skuPropertyId) { throw new \RuntimeException($property->LAST_ERROR); } ``` @@ -364,8 +353,7 @@ $productCatalogCreated = \CCatalog::Add([ 'SKU_PROPERTY_ID' => 0, ]); -if (!$productCatalogCreated) -{ +if (!$productCatalogCreated) { throw new \RuntimeException('Не удалось создать каталог товаров'); } @@ -378,8 +366,7 @@ $offerCatalogCreated = \CCatalog::Add([ 'SKU_PROPERTY_ID' => $skuPropertyId, ]); -if (!$offerCatalogCreated) -{ +if (!$offerCatalogCreated) { throw new \RuntimeException('Не удалось создать каталог торговых предложений'); } ``` @@ -399,8 +386,7 @@ $productId = $element->Add([ 'ACTIVE' => 'Y', ]); -if (!$productId) -{ +if (!$productId) { throw new \RuntimeException($element->LAST_ERROR); } @@ -409,8 +395,7 @@ $result = \Bitrix\Catalog\Model\Product::add([ 'TYPE' => \Bitrix\Catalog\ProductTable::TYPE_SKU, ]); -if (!$result->isSuccess()) -{ +if (!$result->isSuccess()) { throw new \RuntimeException(implode('; ', $result->getErrorMessages())); } ``` @@ -443,8 +428,7 @@ $offerId = $element->Add([ ], ]); -if (!$offerId) -{ +if (!$offerId) { throw new \RuntimeException($element->LAST_ERROR); } @@ -457,8 +441,7 @@ $result = \Bitrix\Catalog\Model\Product::add([ 'SUBSCRIBE' => 'Y', ]); -if (!$result->isSuccess()) -{ +if (!$result->isSuccess()) { throw new \RuntimeException(implode('; ', $result->getErrorMessages())); } ``` @@ -481,8 +464,7 @@ $result = \Bitrix\Catalog\Model\Price::add([ 'CURRENCY' => 'RUB', ]); -if (!$result->isSuccess()) -{ +if (!$result->isSuccess()) { throw new \RuntimeException(implode('; ', $result->getErrorMessages())); } ``` @@ -521,8 +503,7 @@ $offers = $offersByProduct[$productId] ?? []; ```php $skuInfo = \CCatalogSKU::GetInfoByProductIBlock($productIblockId); -if (!$skuInfo) -{ +if (!$skuInfo) { throw new \RuntimeException('Инфоблок не связан с торговыми предложениями'); } @@ -538,8 +519,7 @@ $offersIterator = \CIBlockElement::GetList( ['ID', 'NAME'] ); -while ($offer = $offersIterator->Fetch()) -{ +while ($offer = $offersIterator->Fetch()) { echo $offer['ID'] . ': ' . $offer['NAME'] . "\n"; } ``` @@ -576,8 +556,7 @@ $updated = $element->Update($productId, [ 'ACTIVE' => 'Y', ]); -if (!$updated) -{ +if (!$updated) { throw new \RuntimeException($element->LAST_ERROR); } ``` @@ -595,8 +574,7 @@ $result = \Bitrix\Catalog\Model\Product::update($productId, [ 'SUBSCRIBE' => 'Y', ]); -if (!$result->isSuccess()) -{ +if (!$result->isSuccess()) { throw new \RuntimeException(implode('; ', $result->getErrorMessages())); } ``` @@ -626,8 +604,7 @@ if (!$result->isSuccess()) Для простого товара без предложений используйте `CIBlockElement::Delete()`. В метод передайте идентификатор элемента инфоблока. ```php -if (!\CIBlockElement::Delete($productId)) -{ +if (!\CIBlockElement::Delete($productId)) { global $APPLICATION; $exception = $APPLICATION->GetException(); $message = $exception ? $exception->GetString() : 'Не удалось удалить товар'; @@ -658,10 +635,8 @@ $offersByProduct = \CCatalogSKU::getOffersList( $offers = $offersByProduct[$productId] ?? []; -foreach ($offers as $offer) -{ - if (!\CIBlockElement::Delete((int)$offer['ID'])) - { +foreach ($offers as $offer) { + if (!\CIBlockElement::Delete((int)$offer['ID'])) { global $APPLICATION; $exception = $APPLICATION->GetException(); $message = $exception ? $exception->GetString() : 'Не удалось удалить торговое предложение'; @@ -670,8 +645,7 @@ foreach ($offers as $offer) } } -if (!\CIBlockElement::Delete($productId)) -{ +if (!\CIBlockElement::Delete($productId)) { global $APPLICATION; $exception = $APPLICATION->GetException(); $message = $exception ? $exception->GetString() : 'Не удалось удалить родительский товар'; diff --git a/pages/modules/iblocks/api.md b/pages/modules/iblocks/api.md index 1bf8e6b..9025b99 100644 --- a/pages/modules/iblocks/api.md +++ b/pages/modules/iblocks/api.md @@ -59,8 +59,7 @@ $result = $iblockType->Add([ ], ]); -if (!$result) -{ +if (!$result) { throw new \Exception($iblockType->getLastError()->getMessage()); } ``` @@ -107,8 +106,7 @@ $result = $iblock->Add([ ], ]); -if (!$result) -{ +if (!$result) { throw new \Exception($iblock->getLastError()->getMessage()); } @@ -181,12 +179,11 @@ $result = $authorProp->Add([ 'IBLOCK_ID' => $iblockId, 'NAME' => 'Автор', 'CODE' => 'AUTHOR', - 'PROPERTY_TYPE' => 'S', // строка - 'MULTIPLE' => 'N', // одно значение + 'PROPERTY_TYPE' => 'S', // строка + 'MULTIPLE' => 'N', // одно значение ]); -if (!$result) -{ +if (!$result) { throw new \Exception($authorProp->getLastError()->getMessage()); } @@ -198,11 +195,10 @@ $result = $tagsProp->Add([ 'NAME' => 'Теги', 'CODE' => 'TAGS', 'PROPERTY_TYPE' => 'S', - 'MULTIPLE' => 'Y', // несколько значений + 'MULTIPLE' => 'Y', // несколько значений ]); -if (!$result) -{ +if (!$result) { throw new \Exception($tagsProp->getLastError()->getMessage()); } ``` @@ -218,8 +214,8 @@ $property->Add([ 'IBLOCK_ID' => $iblockId, 'NAME' => 'Фото', 'CODE' => 'PHOTO', - 'PROPERTY_TYPE' => 'F', // файл - 'MULTIPLE' => 'N', // один файл + 'PROPERTY_TYPE' => 'F', // файл + 'MULTIPLE' => 'N', // один файл ]); // Галерея — несколько файлов @@ -246,12 +242,11 @@ $result = $property->Add([ 'IBLOCK_ID' => $iblockId, 'NAME' => 'Источник', 'CODE' => 'SOURCE', - 'PROPERTY_TYPE' => 'L', // список + 'PROPERTY_TYPE' => 'L', // список 'MULTIPLE' => 'N', ]); -if (!$result) -{ +if (!$result) { throw new \Exception($property->getLastError()->getMessage()); } @@ -264,7 +259,7 @@ $enum->Add([ 'PROPERTY_ID' => $propId, 'VALUE' => 'РИА Новости', 'SORT' => 10, - 'XML_ID' => 'ria', // уникальный код, только латиница + 'XML_ID' => 'ria', // уникальный код, только латиница ]); $enum->Add([ @@ -293,13 +288,12 @@ $result = $property->Add([ 'IBLOCK_ID' => $iblockId, 'NAME' => 'Итог', 'CODE' => 'SUMMARY', - 'PROPERTY_TYPE' => 'S', // строка - 'USER_TYPE' => 'HTML', // специальное поле для редактирования текста или кода HTML + 'PROPERTY_TYPE' => 'S', // строка + 'USER_TYPE' => 'HTML', // специальное поле для редактирования текста или кода HTML 'MULTIPLE' => 'N', ]); -if (!$result) -{ +if (!$result) { throw new \Exception($property->getLastError()->getMessage()); } ``` @@ -330,16 +324,15 @@ $result = $property->Add([ 'IBLOCK_ID' => $iblockId, 'NAME' => 'Рубрика', 'CODE' => 'CATEGORY', - 'PROPERTY_TYPE' => 'S', // в базе — строка, хранит UF_XML_ID - 'USER_TYPE' => 'directory', // выпадающий список из Highload-блока + 'PROPERTY_TYPE' => 'S', // в базе — строка, хранит UF_XML_ID + 'USER_TYPE' => 'directory', // выпадающий список из Highload-блока 'MULTIPLE' => 'N', 'USER_TYPE_SETTINGS' => [ 'TABLE_NAME' => 'b_news_categories', // название таблицы Highload-блока ], ]); -if (!$result) -{ +if (!$result) { throw new \Exception($property->getLastError()->getMessage()); } ``` @@ -414,8 +407,7 @@ $section = $sectionNewsClass::query() ->where('CODE', 'events') ->setLimit(1) ->fetchObject(); -if ($section) -{ +if ($section) { echo "Раздел: " . $section->getName(); // Мероприятия echo "Активен: " . ($section->getActive() ? 'да' : 'нет'); } @@ -435,8 +427,7 @@ $parentSection = $sectionNewsClass::query() ->setLimit(1) ->fetchObject(); -if ($parentSection) -{ +if ($parentSection) { // создаем вложенный раздел Выставки $exhibitionSection = $sectionNewsClass::createObject() ->setIblockId($iblockId) @@ -461,8 +452,7 @@ $sections = $sectionNewsClass::query() ->setOrder(['NAME' => 'ASC']) ->setLimit(10) ->fetchCollection(); -foreach ($sections as $item) -{ +foreach ($sections as $item) { echo $item->getName() . "\n"; } ``` @@ -483,11 +473,9 @@ $exhibitionSection = $sectionNewsClass::query() ->setLimit(1) ->fetchObject(); -if ($exhibitionSection) -{ +if ($exhibitionSection) { $parent = $exhibitionSection->getParentSection(); // метод возвращает объект родителя - if ($parent) - { + if ($parent) { echo "Родительский раздел: " . $parent->getName(); // Мероприятия } } @@ -514,18 +502,15 @@ $exhibitionSection = $sectionNewsClass::query() ->setLimit(1) ->fetchObject(); -if ($exhibitionSection) -{ +if ($exhibitionSection) { $exhibitionSection ->setName('Выставки 2025-2026') // изменим название раздела ->setActive(false); // и деактивируем его $result = $exhibitionSection->save(); - if (!$result->isSuccess()) - { - foreach ($result->getErrors() as $error) - { + if (!$result->isSuccess()) { + foreach ($result->getErrors() as $error) { echo $error->getMessage() . "\n"; } } @@ -565,8 +550,7 @@ $conferenceSection = $sectionNewsClass::query() ->setLimit(1) ->fetchObject(); -if ($conferenceSection) -{ +if ($conferenceSection) { $manager = $conferenceSection->get('UF_MANAGER'); // строка echo "Ответственный: " . $manager; // Ирина Сидорова } @@ -602,8 +586,7 @@ $conferenceSection = $sectionNewsClass::query() ->setLimit(1) ->fetchObject(); -if ($conferenceSection) -{ +if ($conferenceSection) { $conferenceSection->delete(); // элементы останутся в базе, но исчезнут из дерева } ``` @@ -659,10 +642,8 @@ $element = $elementNewsClass::createObject() $result = $element->save(); -if (!$result->isSuccess()) -{ - foreach ($result->getErrors() as $error) - { +if (!$result->isSuccess()) { + foreach ($result->getErrors() as $error) { echo $error->getMessage() . "\n"; } return; @@ -691,8 +672,7 @@ $parentSection = $sectionNewsClass::query() ->setLimit(1) ->fetchObject(); -if ($parentSection) -{ +if ($parentSection) { $element = $elementNewsClass::createObject() ->setName('Конференция по кибербезопасности') ->setCode('cybersec-conf-2026') @@ -726,8 +706,8 @@ if ($parentSection) $element = $elementNewsClass::createObject() ->setName('Новость с автором и источником') ->setCode('news-author-source') - ->set('AUTHOR', 'Светлана Пирогова') // строка — текст напрямую - ->set('SOURCE', 1); // список — идентификатор значения «РИА Новости» + ->set('AUTHOR', 'Светлана Пирогова') // строка — текст напрямую + ->set('SOURCE', 1); // список — идентификатор значения «РИА Новости» $element->save(); ``` @@ -878,8 +858,7 @@ $element = $elementNewsClass::query() ->setLimit(1) ->fetchObject(); -if ($element) -{ +if ($element) { echo $element->getName(); // Обновление системы безопасности } ``` @@ -897,10 +876,9 @@ $element = $elementNewsClass::query() echo $element->get('AUTHOR')?->getValue(); // Светлана Пирогова $source = $element->get('SOURCE'); -if ($source) -{ - echo $source->getItem()->getValue(); // РИА Новости - echo $source->getItem()->getXmlId(); // ria +if ($source) { + echo $source->getItem()->getValue(); // РИА Новости + echo $source->getItem()->getXmlId(); // ria } ``` @@ -914,8 +892,7 @@ $element = $elementNewsClass::query() ->setLimit(1) ->fetchObject(); -foreach ($element->get('TAGS')->getAll() as $tag) -{ +foreach ($element->get('TAGS')->getAll() as $tag) { echo $tag->getValue() . "\n"; } ``` @@ -933,8 +910,7 @@ $element = $elementNewsClass::query() ->fetchObject(); $photo = $element->get('PHOTO'); -if ($photo) -{ +if ($photo) { $fileId = $photo->getValue(); // идентификатор сохраненного файла $desc = $photo->getDescription(); // описание $path = \CFile::GetPath($fileId); @@ -951,15 +927,12 @@ $element = $elementNewsClass::query() ->setLimit(1) ->fetchObject(); -if ($element) -{ +if ($element) { $gallery = $element->get('GALLERY'); - if ($gallery) - { + if ($gallery) { // коллекция PropertyValueCollection - foreach ($gallery->getAll() as $other) - { + foreach ($gallery->getAll() as $other) { $fileId = $other->getValue(); $description = $other->getDescription(); @@ -1001,8 +974,7 @@ $elements = ->fetchCollection() ; -foreach ($elements as $element) -{ +foreach ($elements as $element) { echo $element->getName() . ': ' . $element->get('SOURCE')->getValue() . "\n"; } ``` @@ -1145,8 +1117,7 @@ $element = $elementNewsClass::query() ->where('CODE', 'security-update') ->fetchObject(); -if ($element) -{ +if ($element) { $element ->setName('Критическое обновление') ->removeAll('TAGS') @@ -1175,8 +1146,7 @@ $element = $elementNewsClass::query() ->where('CODE', 'security-update') // символьный код элемента Обновление системы безопасности ->fetchObject(); -if ($element) -{ +if ($element) { $element->delete(); \CIBlockElement::UpdateSearch($element->getId()); } @@ -1344,8 +1314,8 @@ $news = $elementNewsClass::query() ->setSelect([ 'ID', 'NAME', - 'AUTHOR', // строка — напрямую - 'SOURCE.VALUE', // список — VALUE, а не SOURCE + 'AUTHOR', // строка — напрямую + 'SOURCE.VALUE', // список — VALUE, а не SOURCE 'DATE_ACTIVE_FROM', 'SECTION_' => 'IBLOCK_SECTION', // подгружаем раздел за один запрос ]) @@ -1354,8 +1324,7 @@ $news = $elementNewsClass::query() ->setLimit(10) ->fetchCollection(); -foreach ($news as $item) -{ +foreach ($news as $item) { $arResult['NEWS'][] = [ 'ID' => $item->getId(), 'NAME' => $item->getName(), @@ -1378,15 +1347,14 @@ $element = $elementNewsClass::query() ->setSelect([ 'ID', 'NAME', 'AUTHOR', 'PHOTO.VALUE', 'PHOTO.DESCRIPTION', - 'SUMMARY', // HTML-свойство + 'SUMMARY', // HTML-свойство 'SECTION_' => 'IBLOCK_SECTION', ]) ->where('CODE', $arParams['ELEMENT_CODE'] ?? '') ->setLimit(1) ->fetchObject(); -if ($element) -{ +if ($element) { $arResult['ITEM'] = [ 'ID' => $element->getId(), 'NAME' => $element->getName(), @@ -1396,8 +1364,7 @@ if ($element) // Фото $photo = $element->get('PHOTO'); - if ($photo) - { + if ($photo) { $arResult['ITEM']['PHOTO'] = [ 'SRC' => \CFile::GetPath($photo->getValue()), 'ALT' => $photo->getDescription(), @@ -1406,8 +1373,7 @@ if ($element) // Раздел $section = $element->getIblockSection(); - if ($section) - { + if ($section) { $arResult['ITEM']['SECTION_NAME'] = $section->getName(); $arResult['ITEM']['SECTION_CODE'] = $section->getCode(); } @@ -1427,15 +1393,12 @@ $elements = $elementNewsClass::query() ->setLimit(5) ->fetchCollection(); -foreach ($elements as $item) -{ +foreach ($elements as $item) { $text = $item->getDetailText(); - if ($text) - { + if ($text) { $preview = strip_tags($text); $preview = mb_substr($preview, 0, 300); - if (mb_strlen($text) > mb_strlen($preview)) - { + if (mb_strlen($text) > mb_strlen($preview)) { $preview .= '…'; } } else { @@ -1467,14 +1430,13 @@ if (!$sourceId) return; $similar = $elementNewsClass::query() ->setSelect(['ID', 'NAME', 'CODE']) ->where('ACTIVE', 'Y') - ->where('SOURCE.VALUE', $sourceId) // фильтр по идентификатору источника + ->where('SOURCE.VALUE', $sourceId) // фильтр по идентификатору источника ->whereNot('ID', $current->getId()) ->setLimit(5) ->fetchCollection(); $arResult['MORE_FROM_SOURCE'] = []; -foreach ($similar as $item) -{ +foreach ($similar as $item) { $arResult['MORE_FROM_SOURCE'][] = [ 'NAME' => $item->getName(), 'URL' => '/news/' . $item->getCode() . '/', // единый URL-паттерн diff --git a/pages/modules/iblocks/architecture.md b/pages/modules/iblocks/architecture.md index 84ac0f5..3b2b597 100644 --- a/pages/modules/iblocks/architecture.md +++ b/pages/modules/iblocks/architecture.md @@ -38,8 +38,7 @@ use Bitrix\Iblock\Elements\ElementClothesTable; $collection = ElementClothesTable::getList()->fetchCollection(); // 2. Collection: работаем с набором -foreach ($collection as $element) -{ +foreach ($collection as $element) { // 3. Object: меняем каждую запись $element->setSort(100); } @@ -155,8 +154,7 @@ $items = ElementClothesTable::query() ```php use Bitrix\Iblock\Elements\ElementClothesTable; -if (ElementClothesTable::getEntity()->hasField('BRAND')) -{ +if (ElementClothesTable::getEntity()->hasField('BRAND')) { // Свойство BRAND доступно в карте класса } ``` diff --git a/pages/modules/iblocks/overview.md b/pages/modules/iblocks/overview.md index 28dc274..fab9917 100644 --- a/pages/modules/iblocks/overview.md +++ b/pages/modules/iblocks/overview.md @@ -143,8 +143,7 @@ $element->save(); $existingElement = $entityClass::getByPrimary($element->getId()) ->fetchObject(); -if ($existingElement) -{ +if ($existingElement) { // Работать со свойствами элемента $value = $existingElement->getSomeProperty(); } diff --git a/pages/modules/iblocks/performance.md b/pages/modules/iblocks/performance.md index 80ecaaa..7439486 100644 --- a/pages/modules/iblocks/performance.md +++ b/pages/modules/iblocks/performance.md @@ -73,12 +73,10 @@ description: 'Производительность и частые ошибки. function updateActiveElementsStat() { $cache = new \CPHPCache(); - if ($cache->InitCache(3600, 'active_elements_count', '/stats/')) - { + if ($cache->InitCache(3600, 'active_elements_count', '/stats/')) { $count = $cache->GetVars()['count']; } else { - if ($cache->StartDataCache()) - { + if ($cache->StartDataCache()) { // Выбираем только ID и дату начала активности $iterator = \Bitrix\Iblock\ElementTable::getList([ 'select' => ['ID', 'DATE_ACTIVE_FROM'], @@ -91,8 +89,7 @@ function updateActiveElementsStat() ]); $count = 0; - while ($element = $iterator->fetch()) - { + while ($element = $iterator->fetch()) { $count++; } @@ -127,8 +124,7 @@ $taggedCache->clearByTag('iblock_id_123'); ```php $row = $result->Fetch(); -if ($row) -{ +if ($row) { $row['NAME'] = \Bitrix\Main\Text\HtmlFilter::encode($row['NAME']); } ``` @@ -376,8 +372,7 @@ CIBlockElement::GetList( Чтобы исправить проблему, в шаблоне компонента до вывода HTML установите код 404: ```php -if (!$arResult['ELEMENT']) -{ +if (!$arResult['ELEMENT']) { \CHTTP::SetStatus('404 Not Found'); require $_SERVER['DOCUMENT_ROOT'].'/404.php'; exit; diff --git a/pages/orm/annotations.md b/pages/orm/annotations.md index f039066..019a7df 100644 --- a/pages/orm/annotations.md +++ b/pages/orm/annotations.md @@ -61,8 +61,6 @@ namespace Bitrix\Main { ```php class MyClass { - // ... - private function getName(EO_User $user): string { return CUser::FormatName( @@ -74,6 +72,7 @@ class MyClass ], ); } + // ... } ``` diff --git a/pages/orm/collections.md b/pages/orm/collections.md index 2d9f885..08314ae 100644 --- a/pages/orm/collections.md +++ b/pages/orm/collections.md @@ -31,6 +31,7 @@ $books = \Bitrix\Main\Test\Typography\BookTable::getList() ```php // Файл bitrix/modules/main/lib/test/typography/books.php namespace Bitrix\Main\Test\Typography; + class Books extends EO_Book_Collection { } @@ -41,13 +42,14 @@ class Books extends EO_Book_Collection ```php // Файл bitrix/modules/main/lib/test/typography/booktable.php namespace Bitrix\Main\Test\Typography; + class BookTable extends Bitrix\Main\ORM\Data\DataManager { public static function getCollectionClass() { return Books::class; } - //... + // ... } ``` @@ -68,8 +70,7 @@ class Books extends EO_Book_Collection ```php $books = \Bitrix\Main\Test\Typography\BookTable::getList() ->fetchCollection(); -foreach ($books as $book) -{ +foreach ($books as $book) { // ... } ``` @@ -119,8 +120,8 @@ $book2 = \Bitrix\Main\Test\Typography\Book::wakeUp(2); $books = \Bitrix\Main\Test\Typography\BookTable::query() ->addSelect('*') ->whereIn('ID', [2, 3, 4]) - ->fetchCollection() -; + ->fetchCollection(); + var_dump($books->has($book1)); // false var_dump($books->has($book2)); // true ``` @@ -131,8 +132,8 @@ var_dump($books->has($book2)); // true $books = \Bitrix\Main\Test\Typography\BookTable::query() ->addSelect('*') ->whereIn('ID', [2, 3, 4]) - ->fetchCollection() -; + ->fetchCollection(); + var_dump($books->hasByPrimary(1)); // false var_dump($books->hasByPrimary(2)); // true ``` @@ -143,8 +144,8 @@ var_dump($books->hasByPrimary(2)); // true $books = \Bitrix\Main\Test\Typography\BookTable::query() ->addSelect('*') ->whereIn('ID', [2, 3, 4]) - ->fetchCollection() -; + ->fetchCollection(); + $isEmpty = $books->isEmpty(); ``` @@ -157,8 +158,8 @@ $book1 = \Bitrix\Main\Test\Typography\Book::wakeUp(1); $books = \Bitrix\Main\Test\Typography\BookTable::query() ->addSelect('*') ->whereIn('ID', [2, 3, 4]) - ->fetchCollection() -; + ->fetchCollection(); + $books->add($book1); // или $books[] = $book1; @@ -187,16 +188,16 @@ $books->removeByPrimary(2); Метод `save()` сохраняет новые объекты одним запросом к базе данных. ```php -use \Bitrix\Main\Test\Typography\Books; -use \Bitrix\Main\Test\Typography\Book; +use Bitrix\Main\Test\Typography\Books; +use Bitrix\Main\Test\Typography\Book; $books = new Books; $books[] = (new Book)->setTitle('Title 112'); $books[] = (new Book)->setTitle('Title 113'); $books[] = (new Book) ->setTitle('Title 114') - ->setIsbn('114-000') -; + ->setIsbn('114-000'); + $books->save(true); // INSERT INTO ... (`TITLE`, `ISBN`) VALUES // ('Title 112', DEFAULT), @@ -211,12 +212,12 @@ $books->save(true); Метод `save()` сохраняет измененные объекты одним запросом `UPDATE`. ```php -use \Bitrix\Main\Test\Typography\PublisherTable; -use \Bitrix\Main\Test\Typography\BookTable; +use Bitrix\Main\Test\Typography\PublisherTable; +use Bitrix\Main\Test\Typography\BookTable; + $books = BookTable::getList()->fetchCollection(); $publisher = PublisherTable::wakeUpObject(254); -foreach ($books as $book) -{ +foreach ($books as $book) { $book->setPublisher($publisher); } $books->save(); @@ -274,10 +275,8 @@ $books->fill(\Bitrix\Main\ORM\Fields\FieldTypeMask::FLAT); ```php $books = \Bitrix\Main\Test\Typography\BookTable::getList() ->fetchCollection(); -$books->walk(static function($book) -{ - if ($book->getPrice() > 1000) - { +$books->walk(static function($book) { + if ($book->getPrice() > 1000) { $book->setActive(false); } }); @@ -292,8 +291,7 @@ $saveResult = \Bitrix\Main\Test\Typography\BookTable::query() ->addSelect('*') ->where('> PRICE', 1000) ->fetchCollection() - ->walk(static function($book) - { + ->walk(static function($book) { $book->setActive(false); }) ->save() @@ -352,13 +350,11 @@ $books = \Bitrix\Main\Test\Typography\Books::wakeUp([ ```php $books = \Bitrix\Main\Test\Typography\BookTable::getList() ->whereIn('ID', [1, 2]) - ->fetchCollection() -; + ->fetchCollection(); $anotherBooks = \Bitrix\Main\Test\Typography\BookTable::getList() ->whereIn('ID', [3, 4]) - ->fetchCollection() -; + ->fetchCollection(); $books = $books->merge($anotherBooks); ``` diff --git a/pages/orm/entity-operations.md b/pages/orm/entity-operations.md index faedefe..94c7649 100644 --- a/pages/orm/entity-operations.md +++ b/pages/orm/entity-operations.md @@ -131,21 +131,20 @@ $em->addEventHandler( ```php class BookTable extends Entity\DataManager { - ... - public static function onBeforeAdd(Entity\Event $event) { $result = new Entity\EventResult; $data = $event->getParameter("fields"); - if (isset($data['ISBN'])) - { + if (isset($data['ISBN'])) { $cleanIsbn = str_replace('-', '', $data['ISBN']); // Удаляем дефисы из ISBN $result->modifyFields(['ISBN' => $cleanIsbn]); // Модифицируем поле ISBN } return $result; } + + // ... } ``` @@ -180,7 +179,7 @@ class BookTable extends Entity\DataManager // } // }, new Entity\Validator\RegExp('/\d{13}/'), // Валидатор, проверяющий, что значение содержит 13 цифр подряд - ... + // ... ]; } ``` @@ -197,8 +196,7 @@ public static function onBeforeUpdate(Entity\Event $event) $result = new Entity\EventResult; $data = $event->getParameter("fields"); - if (isset($data['ISBN'])) - { + if (isset($data['ISBN'])) { $result->unsetFields(['ISBN']); // Удаляет поле ISBN из данных для обновления } @@ -214,9 +212,8 @@ public static function onBeforeUpdate(Entity\Event $event) $result = new Entity\EventResult; $data = $event->getParameter("fields"); - if (isset($data['ISBN'])) - { - // Получает объект поля ISBN и выдает сообщение об ошибке + if (isset($data['ISBN'])) { + // Получает объект поля ISBN и выдает сообщение об ошибке $result->addError(new Entity\FieldError( $event->getEntity()->getField('ISBN'), 'Запрещено менять ISBN код у существующих книг' @@ -235,8 +232,7 @@ public static function onBeforeUpdate(Entity\Event $event) $result = new Entity\EventResult; $data = $event->getParameter("fields"); - if (...) - { // Здесь должна быть ваша логика комплексной проверки данных + if (...) { // Здесь должна быть ваша логика комплексной проверки данных $result->addError(new Entity\EntityError( 'Невозможно обновить запись' )); @@ -337,8 +333,7 @@ BookTable::update($id, [ // Обновление записи в таблице ```php // Вызов с проверкой успешности выполнения запроса $result = BookTable::update(...); // Выполнение обновления и сохранение результата -if (!$result->isSuccess()) -{ // Проверка успешности выполнения +if (!$result->isSuccess()) { // Проверка успешности выполнения // обработка ошибки // Здесь можно добавить код для обработки ошибок, например, логирование или уведомление пользователя } @@ -353,6 +348,7 @@ BookTable::update(...); // Обновление записи без провер ```php namespace SomePartner\MyBooksCatalog; // Определение пространства имен для организации кода + use Bitrix\Main\Entity; // Импорт класса Entity для работы с ORM use Bitrix\Main\Type; // Импорт класса Type для работы с типами данных @@ -415,8 +411,7 @@ class BookTable extends Entity\DataManager // Класс BookTable наслед { $result = new Entity\EventResult; // Создание объекта для результата события $data = $event->getParameter("fields"); // Получение данных полей из события - if (isset($data['ISBN'])) // Проверка наличия поля ISBN - { + if (isset($data['ISBN'])) { // Проверка наличия поля ISBN $cleanIsbn = str_replace('-', '', $data['ISBN']); // Удаление дефисов из ISBN $result->modifyFields(array('ISBN' => $cleanIsbn)); // Модификация поля ISBN } diff --git a/pages/orm/entity-relations.md b/pages/orm/entity-relations.md index 17690aa..9f8ac32 100644 --- a/pages/orm/entity-relations.md +++ b/pages/orm/entity-relations.md @@ -198,7 +198,8 @@ Array ( Создадим класс `PublisherTable`, который представляет собой таблицу издательств в базе данных. Этот класс наследуется от `DataManager` — основного класса для работы с данными в Bitrix Framework. ```php -namespace Bitrix\Main\Test\Typography; +namespace Bitrix\Main\Test\Typography; + use Bitrix\Main\ORM\Data\DataManager; // Импорт класса DataManager для работы с данными use Bitrix\Main\ORM\Fields\Relations\OneToMany; // Импорт класса OneToMany для создания связей «один ко многим» @@ -249,24 +250,24 @@ $data = \Bitrix\Main\Test\Typography\PublisherTable::getByPrimary(253, [ // Вернет Array ( - [0] => Array ( - [ID] => 253 - [TITLE] => Publisher Title 253 - [BOOK_ID] => 2 - [BOOK_TITLE] => Title 2 - [BOOK_PUBLISHER_ID] => 253 - [BOOK_ISBN] => 456-1-05-586920-1 - [BOOK_IS_ARCHIVED] => N - ) - [1] => Array ( - [ID] => 253 - [TITLE] => Publisher Title 253 - [BOOK_ID] => 1 - [BOOK_TITLE] => Title 1 - [BOOK_PUBLISHER_ID] => 253 - [BOOK_ISBN] => 978-3-16-148410-0 - [BOOK_IS_ARCHIVED] => Y - ) + [0] => Array ( + [ID] => 253 + [TITLE] => Publisher Title 253 + [BOOK_ID] => 2 + [BOOK_TITLE] => Title 2 + [BOOK_PUBLISHER_ID] => 253 + [BOOK_ISBN] => 456-1-05-586920-1 + [BOOK_IS_ARCHIVED] => N + ) + [1] => Array ( + [ID] => 253 + [TITLE] => Publisher Title 253 + [BOOK_ID] => 1 + [BOOK_TITLE] => Title 1 + [BOOK_PUBLISHER_ID] => 253 + [BOOK_ISBN] => 978-3-16-148410-0 + [BOOK_IS_ARCHIVED] => Y + ) ) ``` @@ -456,7 +457,8 @@ class CoverTable extends DataManager // Класс CoverTable наследует Для связи «один к одному» между таблицами `BookTable` и `CoverTable` используется поле `Reference`. Это поле позволяет создать связь между таблицами через указанные условия соединения. ```php -namespace Bitrix\Main\Test\Typography; +namespace Bitrix\Main\Test\Typography; + use Bitrix\Main\ORM\Fields\Relations\Reference; // Импорт класса Reference для создания связей между таблицами use Bitrix\Main\ORM\Query\Join; // Импорт класса Join для определения условий соединения @@ -855,15 +857,15 @@ class StoreBookTable extends DataManager ```php // Объект книги $book = \Bitrix\Main\Test\Typography\BookTable::getByPrimary(1) - ->fetchObject(); + ->fetchObject(); // Объект магазина $store = \Bitrix\Main\Test\Typography\StoreTable::getByPrimary(34) - ->fetchObject(); + ->fetchObject(); // Новый объект связи книги с магазином $item = \Bitrix\Main\Test\Typography\StoreBookTable::createObject() - ->setBook($book) - ->setStore($store) - ->setQuantity(5); + ->setBook($book) + ->setStore($store) + ->setQuantity(5); // Сохранение $item->save(); ``` @@ -873,7 +875,8 @@ $item->save(); ```php // Объект существующей связи $item = \Bitrix\Main\Test\Typography\StoreBookTable::getByPrimary([ - 'STORE_ID' => 33, 'BOOK_ID' => 2 + 'STORE_ID' => 33, + 'BOOK_ID' => 2, ])->fetchObject(); // Обновление количества $item->setQuantity(12); @@ -886,7 +889,8 @@ $item->save(); ```php // Объект существующей связи $item = \Bitrix\Main\Test\Typography\StoreBookTable::getByPrimary([ - 'STORE_ID' => 33, 'BOOK_ID' => 2 + 'STORE_ID' => 33, + 'BOOK_ID' => 2, ])->fetchObject(); // Удаление $item->delete(); @@ -897,16 +901,18 @@ $item->delete(); ```php // Добавление записи \Bitrix\Main\Test\Typography\StoreBookTable::add([ - 'STORE_ID' => 34, 'BOOK_ID' => 1, 'QUANTITY' => 5 + 'STORE_ID' => 34, + 'BOOK_ID' => 1, + 'QUANTITY' => 5, ]); // Обновление записи \Bitrix\Main\Test\Typography\StoreBookTable::update( - ['STORE_ID' => 34, 'BOOK_ID' => 1], - ['QUANTITY' => 12] + ['STORE_ID' => 34, 'BOOK_ID' => 1], + ['QUANTITY' => 12] ); // Удаление записи \Bitrix\Main\Test\Typography\StoreBookTable::delete( - ['STORE_ID' => 34, 'BOOK_ID' => 1] + ['STORE_ID' => 34, 'BOOK_ID' => 1] ); ``` @@ -967,8 +973,7 @@ $book = \Bitrix\Main\Test\Typography\BookTable::getByPrimary(1, [ 'select' => ['*', 'STORE_ITEMS'] // Выбираем все поля книги и связанные записи о наличии в магазинах ])->fetchObject(); -foreach ($book->getStoreItems() as $storeItem) // Перебираем все связанные записи о наличии книги в магазинах -{ +foreach ($book->getStoreItems() as $storeItem) { // Перебираем все связанные записи о наличии книги в магазинах printf( 'store "%s" has %s of book "%s"', // Форматируем строку для вывода информации $storeItem->getStoreId(), // Получаем ID магазина diff --git a/pages/orm/objects.md b/pages/orm/objects.md index c8b5486..2b7b546 100644 --- a/pages/orm/objects.md +++ b/pages/orm/objects.md @@ -46,7 +46,7 @@ class BookTable extends Bitrix\Main\ORM\Data\DataManager { return Book::class; } - //... + // ... } ``` @@ -340,7 +340,7 @@ $book->unset($fieldName); Метод `isFilled` проверяет, содержит ли объект актуальное значение из базы данных. ```php -use \Bitrix\Main\Test\Typography\Book; +use Bitrix\Main\Test\Typography\Book; // актуальными считаются значения из методов fetch* и wakeUp // в примере при инициализации объекта передается только первичный ключ $book = Book::wakeUp(1); @@ -354,7 +354,7 @@ var_dump($book->isTitleFilled()); // true Метод `isChanged` определяет, было ли установлено новое значение в течение сеанса. ```php -use \Bitrix\Main\Test\Typography\Book; +use Bitrix\Main\Test\Typography\Book; // объект может иметь исходное значение, а может и не иметь // это не повлияет на дальнейшее поведение $book = Book::wakeUp(['ID' => 1, 'TITLE' => 'Title 1']); @@ -370,7 +370,7 @@ var_dump($book->isTitleChanged()); // true Метод `has` проверяет, есть ли в объекте какое-либо значение поля — актуальное из базы данных или установленное в сеансе. Это эквивалентно `isFilled() || isChanged()`. ```php -use \Bitrix\Main\Test\Typography\Book; +use Bitrix\Main\Test\Typography\Book; $book = Book::wakeUp(['ID' => 1, 'TITLE' => 'Title 1']); $book->setIsArchived(true); @@ -394,8 +394,8 @@ var_dump($book->hasIsbn()); // false Переход между состояниями происходит автоматически на основе изменений данных. Состояние объекта можно проверить с помощью публичного read-only свойства `state` и констант класса `\Bitrix\Main\ORM\Objectify\State`. ```php -use \Bitrix\Main\Test\Typography\Book; -use \Bitrix\Main\ORM\Objectify\State; +use Bitrix\Main\Test\Typography\Book; +use Bitrix\Main\ORM\Objectify\State; $book = new Book; $book->setTitle('New title'); diff --git a/pages/orm/orm-concepts.md b/pages/orm/orm-concepts.md index b49ac3d..294607b 100644 --- a/pages/orm/orm-concepts.md +++ b/pages/orm/orm-concepts.md @@ -17,10 +17,10 @@ ORM (Object-Relational Mapping) — это технология, которая ```sql Book - ID int [autoincrement, primary] - ISBN str [match: /[0-9X-]+/] - TITLE str [max_length: 50] - PUBLISH_DATE date + ID int [autoincrement, primary] + ISBN str [match: /[0-9X-]+/] + TITLE str [max_length: 50] + PUBLISH_DATE date ``` Здесь: @@ -421,14 +421,12 @@ new Entity\ExpressionField('AGE_DAYS', ```php class BookTable extends Entity\DataManager { - ... - - public static function getUfId() - { - return 'MY_BOOK'; - } - - ... + public static function getUfId() + { + return 'MY_BOOK'; + } + + // ... } ``` diff --git a/pages/orm/querying-data.md b/pages/orm/querying-data.md index 605b280..ede4c84 100644 --- a/pages/orm/querying-data.md +++ b/pages/orm/querying-data.md @@ -12,7 +12,7 @@ description: 'Выборка данных. ORM Bitrix Framework: ключевы Рассмотрим применение метода на примере сущности `BookTable`. Метод принимает параметры: ```php -use \Bitrix\Main\ORM; +use Bitrix\Main\ORM; $result = BookTable::getList([ 'select' => ['ISBN', 'TITLE', 'PUBLISH_DATE', 'CNT'], // поля, которые нужно получить @@ -24,7 +24,7 @@ $result = BookTable::getList([ 'runtime' => [ // динамически определенные поля new ORM\Fields\ExpressionField('CNT', 'COUNT(*)') ], - 'count_total' => true // список всех элементов без постраничного вывода + 'count_total' => true // список всех элементов без постраничного вывода ]); ``` @@ -51,8 +51,7 @@ $result = BookTable::getList([ // Получение данных построчно $rows = []; $result = BookTable::getList($parameters); -while ($row = $result->fetch()) -{ +while ($row = $result->fetch()) { $rows[] = $row; } @@ -71,9 +70,8 @@ class BookTable extends \Bitrix\Main\Entity\DataManager { return [ function ($data) - { - if (isset($data['PUBLISH_DATE'])) - { + { + if (isset($data['PUBLISH_DATE'])) { $data['PUBLISH_DATE'] = date('d.m.Y', strtotime($data['PUBLISH_DATE'])); } return $data; @@ -298,7 +296,7 @@ BookTable::getList([ Для подсчета количества записей используйте `ExpressionField`: ```php -use \Bitrix\Main\ORM; +use Bitrix\Main\ORM; BookTable::getList([ 'select' => ['CNT'], @@ -316,7 +314,7 @@ BookTable::getList([ После того, как добавили вычисляемое поле, его можно использовать в фильтрах: ```php -use \Bitrix\Main\ORM; +use Bitrix\Main\ORM; BookTable::getList([ 'select' => ['PUBLISH_DATE'], @@ -341,7 +339,7 @@ BookTable::getList([ Если вычисляемое поле нужно только в `select`, `runtime` можно не использовать. Система поддерживает вложенные выражения, которые разворачиваются в финальном SQL. ```php -use \Bitrix\Main\ORM; +use Bitrix\Main\ORM; BookTable::getList([ 'select' => [ @@ -492,7 +490,7 @@ $row = $result->fetch(); Одну таблицу можно описать несколькими сущностями, разделив записи на сегменты. Метод `setDefaultScope` выполняется при каждом запросе, задавая фильтры и другие параметры. ```php -use \Bitrix\Main\ORM\Query\Query; +use Bitrix\Main\ORM\Query\Query; class Element4Table extends \Bitrix\Iblock\ElementTable { @@ -534,7 +532,7 @@ class Element5Table extends \Bitrix\Iblock\ElementTable На пользовательском уровне можно задавать предустановленные выборки с помощью методов `with*`, аналога `setDefaultScope`. ```php -use \Bitrix\Main\ORM\Query\Query; +use Bitrix\Main\ORM\Query\Query; class UserTable { @@ -559,7 +557,7 @@ $activeUsers = UserTable::query() Метод принимает объект `Bitrix\Main\ORM\Query\Query`, позволяя задавать фильтры и другие параметры. Можно добавить свои аргументы: ```php -use \Bitrix\Main\ORM\Query\Query; +use Bitrix\Main\ORM\Query\Query; class UserTable { @@ -875,7 +873,8 @@ public static function decompose(Query $query, $fairLimit = true, $separateRelat Вы можете использовать вложенные фильтры для более сложных условий: ```php -use \Bitrix\Main\ORM\Query\Query; +use Bitrix\Main\ORM\Query\Query; + \Bitrix\Main\UserTable::query() ->where(Query::filter()->where([ ["ID", '>', 1], @@ -888,7 +887,8 @@ use \Bitrix\Main\ORM\Query\Query; Для объединения условий с логикой `OR`: ```php -use \Bitrix\Main\ORM\Query\Query; +use Bitrix\Main\ORM\Query\Query; + \Bitrix\Main\UserTable::query() ->where('ACTIVE', true) ->where(Query::filter() @@ -905,7 +905,7 @@ use \Bitrix\Main\ORM\Query\Query; Вы также можете использовать цепочку вызовов для создания условий с `OR`: ```php -use \Bitrix\Main\ORM\Query\Query; +use Bitrix\Main\ORM\Query\Query; \Bitrix\Main\UserTable::query() ->where('ACTIVE', true) ->where(Query::filter() @@ -922,7 +922,7 @@ use \Bitrix\Main\ORM\Query\Query; В фильтре можно использовать `ExpressionField`, который автоматически регистрируется как runtime поле. Это позволяет создавать сложные условия: ```php -use \Bitrix\Main\ORM\Fields\ExpressionField; +use Bitrix\Main\ORM\Fields\ExpressionField; \Bitrix\Main\UserTable::query() ->where(new ExpressionField('LNG', 'LENGTH(%s)', 'LAST_NAME'), '>', 10) @@ -933,7 +933,7 @@ use \Bitrix\Main\ORM\Fields\ExpressionField; Для упрощения таких конструкций используйте хелпер. Хелпер — это вспомогательный метод, который упрощает работу с выражениями. `Query::expr()` является хелпером, который позволяет использовать SQL-функции: ```php -use \Bitrix\Main\ORM\Query\Query; +use Bitrix\Main\ORM\Query\Query; \Bitrix\Main\UserTable::query() ->where(Query::expr()->length("LAST_NAME"), '>', 10) ->exec(); @@ -972,7 +972,7 @@ use \Bitrix\Main\ORM\Query\Query; При использовании `getList`, фильтр можно вставить вместо массива: ```php -use \Bitrix\Main\ORM\Query\Query; +use Bitrix\Main\ORM\Query\Query; \Bitrix\Main\UserTable::getList([ 'filter' => ['=ID' => 1] ]); @@ -989,8 +989,8 @@ use \Bitrix\Main\ORM\Query\Query; Референсы — это связи между таблицами, которые позволяют объединять данные из разных таблиц. Они описываются с помощью `ReferenceField`: ```php -use \Bitrix\Main\Entity; -use \Bitrix\Main\ORM\Query\Join; +use Bitrix\Main\Entity; +use Bitrix\Main\ORM\Query\Join; new Entity\ReferenceField('GROUP', GroupTable::class, Join::on('this.GROUP_ID', 'ref.ID') @@ -1000,8 +1000,8 @@ new Entity\ReferenceField('GROUP', GroupTable::class, Метод `on` — это сокращенная запись `Query::filter()` с предустановленным условием по колонкам. Он позволяет строить условия JOIN: ```php -use \Bitrix\Main\Entity; -use \Bitrix\Main\ORM\Query\Join; +use Bitrix\Main\Entity; +use Bitrix\Main\ORM\Query\Join; new Entity\ReferenceField('GROUP', GroupTable::class, Join::on('this.GROUP_ID', 'ref.ID') diff --git a/pages/performance/caching.md b/pages/performance/caching.md index e7dbc89..46e25f6 100644 --- a/pages/performance/caching.md +++ b/pages/performance/caching.md @@ -53,13 +53,10 @@ $cache = Bitrix\Main\Application::getInstance()->getCache(); ```php // Проверяем наличие кеша -if ($cache->initCache(3600, 'cache_key')) -{ +if ($cache->initCache(3600, 'cache_key')) { // Получаем данные из кеша $data = $cache->getVars(); -} -elseif ($cache->startDataCache()) -{ +} elseif ($cache->startDataCache()) { // Если кеша нет, получаем данные из базы $data = getDataFromDatabase(); @@ -79,13 +76,10 @@ if ($cache->initCache( )) { $result = $cache->getVars(); -} -elseif ($cache->startDataCache()) -{ +} elseif ($cache->startDataCache()) { $result = array(); // Если данные недействительны, отменяем кеширование - if ($isInvalid) - { + if ($isInvalid) { $cache->abortDataCache(); } // Сохраняем валидные данные @@ -99,8 +93,7 @@ elseif ($cache->startDataCache()) $cache = Bitrix\Main\Data\Cache::createInstance(); // Если есть закешированные данные, они выведутся в буфер в методе Cache::startDataCache -if ($cache->startDataCache(3600, 'xxxx')) -{ +if ($cache->startDataCache(3600, 'xxxx')) { echo 'Какой-нибудь HTML'; $cache->endDataCache(); @@ -143,13 +136,10 @@ use Bitrix\Main\Application; $cache = Application::getInstance()->getCache(); // Проверяем наличие кеша -if ($cache->initCache(3600, 'cache_key')) -{ +if ($cache->initCache(3600, 'cache_key')) { // Получаем данные из кеша $data = $cache->getVars(); -} -elseif ($cache->startDataCache()) -{ +} elseif ($cache->startDataCache()) { // Если кеша нет, получаем данные из базы $data = getDataFromDatabase(); @@ -199,13 +189,10 @@ $managedCache = Application::getInstance()->getManagedCache(); $cacheKey = 'user_list'; // Проверяем наличие кеша с помощью read -if ($managedCache->read(3600, $cacheKey)) -{ +if ($managedCache->read(3600, $cacheKey)) { // Получаем данные из кеша с помощью get $data = $managedCache->get($cacheKey); -} -else -{ +} else { // Если кеша нет, загружаем данные и сохраняем их в кеш $data = loadUsers(); $managedCache->set($cacheKey, $data); @@ -229,8 +216,7 @@ use Bitrix\Main\Application; $managedCache = Application::getInstance()->getManagedCache(); $cacheKey = 'user_list'; -if (!$managedCache->read(3600, $cacheKey)) -{ +if (!$managedCache->read(3600, $cacheKey)) { $data = loadUsers(); $managedCache->setImmediate($cacheKey, $data); } @@ -246,12 +232,9 @@ $cacheKey = 'active_user_list'; $cacheDir = 'orm_b_user'; // Проверяем наличие кеша с помощью read -if ($managedCache->read(3600, $cacheKey, $cacheDir)) -{ +if ($managedCache->read(3600, $cacheKey, $cacheDir)) { $users = $managedCache->get($cacheKey); -} -else -{ +} else { $users = loadActiveUsers(); $managedCache->set($cacheKey, $users); } @@ -593,13 +576,10 @@ $cacheDir = 'my_cache_dir'; $taggedCache = Application::getInstance()->getTaggedCache(); // Проверяем наличие кеша -if ($cache->initCache(3600, 'cache_key', $cacheDir)) -{ +if ($cache->initCache(3600, 'cache_key', $cacheDir)) { // Получаем данные из кеша $data = $cache->getVars(); -} -elseif ($cache->startDataCache()) -{ +} elseif ($cache->startDataCache()) { // Если кеша нет, получаем данные из базы $data = getDataFromDatabase(); diff --git a/pages/performance/composite-site.md b/pages/performance/composite-site.md index e44244d..fe6e5d9 100644 --- a/pages/performance/composite-site.md +++ b/pages/performance/composite-site.md @@ -737,7 +737,7 @@ BX.addCustomEvent("onFrameDataRequestFail", function(response) { - `AssetMode::NO_ASSETS` — ресурсы не добавляются в ``. -```javascript +```php $dynamicArea = new \Bitrix\Main\Page\FrameStatic("workarea"); $dynamicArea->setAssetMode(AssetMode::STANDARD); // Устанавливает режим добавления ресурсов @@ -822,7 +822,7 @@ $id = $this->randString(); // Генерация стабильного иден Для хранения данных в локальном хранилище браузера используйте метод `setBrowserStorage(true)`. -```javascript +```php $frame = $this->createFrame()->begin(); // Создание динамической зоны $frame->setBrowserStorage(true); // Включает использование локального хранилища браузера // Здесь размещается динамический контент @@ -833,7 +833,7 @@ $frame->end(); // Завершение динамической зоны Если нужно кешировать весь контент шаблона и обновлять его на втором хите, поместите код шаблона в `createFrame()->begin()`. -```javascript +```php $frame = $this->createFrame()->begin(); // Начало динамической зоны для всего шаблона // Весь контент шаблона $frame->end(); // Завершение динамической зоны diff --git a/pages/performance/hot-and-cold-session.md b/pages/performance/hot-and-cold-session.md index 5ca4a61..7f65b8b 100644 --- a/pages/performance/hot-and-cold-session.md +++ b/pages/performance/hot-and-cold-session.md @@ -43,7 +43,7 @@ description: 'Сессия в разделенном режиме. Оптими ```php return [ - //... + // ... 'session' => [ 'value' => [ 'mode' => 'separated', diff --git a/pages/security/access-control.md b/pages/security/access-control.md index f0ac7e2..c04769f 100644 --- a/pages/security/access-control.md +++ b/pages/security/access-control.md @@ -196,7 +196,7 @@ $PERM["файл_или_папка"]["ID_группы"] = "уровень_дос ### Пример настройки прав через файл ```php -SetCodeCrypt($captchaPass); Добавьте в форму три элемента: -```html +```php - + - + ``` Чтобы проверить, правильно ли пользователь ввел CAPTCHA, добавьте в обработчик формы код: @@ -148,12 +148,12 @@ $code = $APPLICATION->CaptchaGetCode(); Код передается в HTML для отображения картинки. Картинка генерируется скриптом `/bitrix/tools/captcha.php`. -```html +```php - + -CAPTCHA +CAPTCHA ``` При обращении к скрипту: @@ -202,10 +202,10 @@ $code = $cpt->GetSID(); 3. Обновите путь к файлу в HTML-коде. -```html +```php - + -CAPTCHA +CAPTCHA ``` diff --git a/pages/security/cipher.md b/pages/security/cipher.md index a719a57..5b4ea2b 100644 --- a/pages/security/cipher.md +++ b/pages/security/cipher.md @@ -123,8 +123,7 @@ $decrypted = $cipher->decrypt($decoded, $cryptoKey); Обрабатывайте ошибки с помощью `try/catch`. ```php -try -{ +try { $cipher = new \Bitrix\Main\Security\Cipher(); $originalData = 'Конфиденциальная информация'; @@ -138,9 +137,7 @@ try // Результат должен совпадать с исходными данными echo $decryptedData; // Конфиденциальная информация -} -catch(\Bitrix\Main\Security\SecurityException $e) -{ +} catch(\Bitrix\Main\Security\SecurityException $e) { // Обрабатываем ошибку echo 'Ошибка шифрования: ' . $e->getMessage(); } diff --git a/pages/security/cryptofield.md b/pages/security/cryptofield.md index 18f742b..75be68b 100644 --- a/pages/security/cryptofield.md +++ b/pages/security/cryptofield.md @@ -49,8 +49,7 @@ description: 'Криптографические поля в ORM. Руковод - поддержку OpenSSL на сервере. ```php -if (\Bitrix\Main\ORM\Fields\CryptoField::cryptoAvailable()) -{ +if (\Bitrix\Main\ORM\Fields\CryptoField::cryptoAvailable()) { // можно работать с CryptoField и SecretField } ``` @@ -161,8 +160,7 @@ BookTable::enableCrypto('ISBN'); Если таблица только создается и в ней еще нет данных, сразу включите шифрование для нужной колонки в установщике модуля. ```php -if (\Bitrix\Main\ORM\Fields\CryptoField::cryptoAvailable()) -{ +if (\Bitrix\Main\ORM\Fields\CryptoField::cryptoAvailable()) { BookTable::enableCrypto('ISBN'); } ``` @@ -211,14 +209,12 @@ class TempBookTable extends DataManager } } -if (CryptoField::cryptoAvailable()) -{ +if (CryptoField::cryptoAvailable()) { $connection = Application::getConnection(); $result = $connection->query('SELECT ID, ISBN FROM book'); // Перебираем все записи и обновляем ISBN через временный класс - while ($row = $result->fetch()) - { + while ($row = $result->fetch()) { // Передаем то же значение, но поле crypto зашифрует его TempBookTable::update($row['ID'], ['ISBN' => $row['ISBN']]); } @@ -257,9 +253,9 @@ use Bitrix\Main\ORM\Fields\SecretField; public static function getMap() { return [ - // ... + // ... // другие поля - // ... + // ... 'API_TOKEN' => new SecretField('API_TOKEN', [ 'secret_length' => 32, @@ -277,8 +273,7 @@ public static function getMap() Как и для `CryptoField`, после создания таблицы или добавления поля с уже существующими данными, нужно включить шифрование с помощью `enableCrypto()`. ```php -if (\Bitrix\Main\ORM\Fields\CryptoField::cryptoAvailable()) -{ +if (\Bitrix\Main\ORM\Fields\CryptoField::cryptoAvailable()) { MyTable::enableCrypto('API_TOKEN'); } ``` diff --git a/pages/security/csrf-ssrf.md b/pages/security/csrf-ssrf.md index 9e5edb7..e43edca 100644 --- a/pages/security/csrf-ssrf.md +++ b/pages/security/csrf-ssrf.md @@ -88,10 +88,10 @@ HTML-инъекции могут нарушить форматирование ```php
- - - ... + + + ...
``` @@ -116,8 +116,8 @@ HTML-инъекции могут нарушить форматирование ```php
- - ... + + ...
``` diff --git a/pages/security/secure-cookies.md b/pages/security/secure-cookies.md index 25fc6ae..3aa94c7 100644 --- a/pages/security/secure-cookies.md +++ b/pages/security/secure-cookies.md @@ -20,14 +20,14 @@ description: 'Защищенные cookie. Руководство по безо ```php [ 'value' => [ 'crypto_key' => 'mysupersecretphrase', ], 'readonly' => true, // 'readonly' указывает, что значение 'crypto_key' нельзя изменить через интерфейс администратора. Это повышает безопасность: ключ остается постоянным и защищенным от случайных изменений ] - //... + // ... ]; ``` diff --git a/pages/security/sql-injection.md b/pages/security/sql-injection.md index 999a706..d102e6c 100644 --- a/pages/security/sql-injection.md +++ b/pages/security/sql-injection.md @@ -114,7 +114,7 @@ $select = $_REQUEST['select'] //['ID' => 'ID', 'TITLE' => 'TITLE', 'LAST_NAME' => 'RESPONSIBLE.LAST_NAME']; $result = \Bitrix\Tasks\Internals\TaskTable::getList([ - 'select' => $select // доступ к любым поля и связям + 'select' => $select // доступ к любым поля и связям ]); var_dump($result->fetchAll()); @@ -140,7 +140,7 @@ var_dump($result->fetchAll()); // Пример подбора email через фильтр $result = \Bitrix\Main\UserTable::getList([ // Если что-то возвращается, значит email начинается с буквы А. Если нет — пробуем другой символ. - 'filter' => ['ID' => 1, '%=EMAIL' => "A%"] + 'filter' => ['ID' => 1, '%=EMAIL' => "A%"] ]); ``` diff --git a/pages/security/xss.md b/pages/security/xss.md index f610696..fb56b5d 100644 --- a/pages/security/xss.md +++ b/pages/security/xss.md @@ -21,7 +21,7 @@ XSS (Cross-Site Scripting) — уязвимость, которая позвол {% endnote %} -```html +```php
@@ -53,7 +53,7 @@ const valueEscaped = Text.encode(valueNotSafe); Заключайте значения атрибутов в двойные кавычки `"`. С одинарными кавычками экранирование не сработает. -```html +```php @@ -65,7 +65,7 @@ const valueEscaped = Text.encode(valueNotSafe); Метод `CUtil::JSEscape` экранирует спецсимволы JavaScript `'`, `"`, `\`, `\n`, `\r`. Подходит для строк, заключенных в кавычки. -```html +```php // Правильно: строка в кавычках, спецсимволы экранированы ``` diff --git a/pages/ui/dialogs-messagebox.md b/pages/ui/dialogs-messagebox.md index bc2f1eb..9bc2be7 100644 --- a/pages/ui/dialogs-messagebox.md +++ b/pages/ui/dialogs-messagebox.md @@ -65,10 +65,10 @@ MessageBox.alert(message, title, onOk, okCaption); import { MessageBox } from 'ui.dialogs.messagebox'; MessageBox.alert( - 'Проверьте параметры перед продолжением.', - 'Параметры задачи', - () => true, - 'Понятно', + 'Проверьте параметры перед продолжением.', + 'Параметры задачи', + () => true, + 'Понятно', ); ``` @@ -86,15 +86,15 @@ MessageBox.alert( import { MessageBox } from 'ui.dialogs.messagebox'; MessageBox.confirm( - 'Удалить элемент?', - (messageBox) => { - return BX.ajax.runAction('example.Item.delete', { - data: { - id: 42, - }, - }); - }, - 'Удалить', + 'Удалить элемент?', + (messageBox) => { + return BX.ajax.runAction('example.Item.delete', { + data: { + id: 42, + }, + }); + }, + 'Удалить', ); ``` @@ -132,13 +132,13 @@ MessageBox.confirm(message, title, onOk, okCaption, onCancel, cancelCaption, use import { MessageBox } from 'ui.dialogs.messagebox'; MessageBox.confirm( - 'Отменить изменения в форме?', - 'Несохраненные данные', - () => true, - 'Отменить изменения', - () => false, - 'Вернуться', - true, + 'Отменить изменения в форме?', + 'Несохраненные данные', + () => true, + 'Отменить изменения', + () => false, + 'Вернуться', + true, ); ``` @@ -152,10 +152,10 @@ MessageBox.confirm( import { MessageBox } from 'ui.dialogs.messagebox'; MessageBox.show({ - title: 'Заявка отправлена', - message: 'Ответственный получит уведомление.', - modal: true, - buttons: BX.UI.Dialogs.MessageBoxButtons.OK, + title: 'Заявка отправлена', + message: 'Ответственный получит уведомление.', + modal: true, + buttons: BX.UI.Dialogs.MessageBoxButtons.OK, }); ``` @@ -169,15 +169,15 @@ MessageBox.show({ import { MessageBox } from 'ui.dialogs.messagebox'; const messageBox = new MessageBox({ - title: 'Удалить контакт', - message: 'Контакт будет удален из адресной книги.', - buttons: BX.UI.Dialogs.MessageBoxButtons.OK_CANCEL, - okCaption: 'Удалить', - cancelCaption: 'Отмена', - onOk: () => { - messageBox.close(); - return false; - }, + title: 'Удалить контакт', + message: 'Контакт будет удален из адресной книги.', + buttons: BX.UI.Dialogs.MessageBoxButtons.OK_CANCEL, + okCaption: 'Удалить', + cancelCaption: 'Отмена', + onOk: () => { + messageBox.close(); + return false; + }, }); messageBox.show(); @@ -243,16 +243,16 @@ messageBox.show(); import { MessageBox } from 'ui.dialogs.messagebox'; const messageBox = new MessageBox({ - message: 'Выберите действие.', - buttons: [ - new BX.UI.Button({ - text: 'Архивировать', - color: BX.UI.Button.Color.PRIMARY, - events: { - click: () => messageBox.close(), - }, - }), - ], + message: 'Выберите действие.', + buttons: [ + new BX.UI.Button({ + text: 'Архивировать', + color: BX.UI.Button.Color.PRIMARY, + events: { + click: () => messageBox.close(), + }, + }), + ], }); messageBox.show(); @@ -280,16 +280,16 @@ messageBox.show(); import { MessageBox } from 'ui.dialogs.messagebox'; const messageBox = new MessageBox({ - message: 'Удалить элемент?', - buttons: BX.UI.Dialogs.MessageBoxButtons.OK_CANCEL, - onOk: (box, button, event) => { - return BX.ajax.runAction('example.Item.delete', { - data: { - id: 42, - }, - }); - }, - onCancel: () => true, + message: 'Удалить элемент?', + buttons: BX.UI.Dialogs.MessageBoxButtons.OK_CANCEL, + onOk: (box, button, event) => { + return BX.ajax.runAction('example.Item.delete', { + data: { + id: 42, + }, + }); + }, + onCancel: () => true, }); messageBox.show(); @@ -317,8 +317,8 @@ messageBox.show(); import { MessageBox } from 'ui.dialogs.messagebox'; const messageBox = new MessageBox({ - message: 'Идет проверка данных.', - buttons: BX.UI.Dialogs.MessageBoxButtons.OK, + message: 'Идет проверка данных.', + buttons: BX.UI.Dialogs.MessageBoxButtons.OK, }); messageBox.show(); diff --git a/pages/ui/hint.md b/pages/ui/hint.md index 77b024d..fa6a575 100644 --- a/pages/ui/hint.md +++ b/pages/ui/hint.md @@ -76,8 +76,8 @@ import { Dom, Tag } from 'main.core'; const container = document.getElementById('settings-container'); Dom.append( - Tag.render``, - container, + Tag.render``, + container, ); BX.UI.Hint.init(container); From 48336f0a836e07387382b510055679e873b31490 Mon Sep 17 00:00:00 2001 From: shoman4eg Date: Mon, 20 Jul 2026 15:02:03 +0200 Subject: [PATCH 2/3] =?UTF-8?q?docs:=20=D1=81=D0=BA=D0=BE=D0=B1=D0=BA?= =?UTF-8?q?=D0=B8=20Allman=20=D0=B8=20=D0=B2=D1=8B=D0=BD=D0=BE=D1=81=20;?= =?UTF-8?q?=20=D0=B2=20=D1=86=D0=B5=D0=BF=D0=BE=D1=87=D0=BA=D0=B0=D1=85=20?= =?UTF-8?q?=D0=B2=D1=8B=D0=B7=D0=BE=D0=B2=D0=BE=D0=B2=20=D0=BF=D0=BE=20CON?= =?UTF-8?q?TRIBUTING?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pages/advanced/datetime.md | 6 +- pages/advanced/debug.md | 6 +- pages/advanced/geolocation.md | 10 +- pages/advanced/http-client.md | 66 ++++-- pages/advanced/images.md | 18 +- pages/advanced/logger.md | 12 +- pages/advanced/multisite.md | 45 ++-- pages/advanced/quality-monitor.md | 3 +- pages/advanced/stepper.md | 9 +- pages/cms-basics/admin-panel.md | 21 +- pages/cms-basics/mail.md | 16 +- pages/cms-basics/menu.md | 37 ++- pages/cms-basics/page-navigation.md | 15 +- pages/cms-basics/page-templates.md | 18 +- pages/cms-basics/sms.md | 43 ++-- pages/cms-basics/user-groups.md | 16 +- pages/cms-basics/userfields.md | 6 +- pages/cms-basics/users.md | 51 +++-- pages/database/postgresql/compatible-code.md | 9 +- pages/database/query-execution.md | 9 +- pages/database/sql-tracker.md | 3 +- pages/database/transactions.md | 38 +++- pages/framework/autoloading.md | 6 +- pages/framework/background-jobs.md | 36 ++- pages/framework/components.md | 45 ++-- pages/framework/controllers.md | 9 +- pages/framework/cookies.md | 13 +- pages/framework/events.md | 20 +- pages/framework/messenger.md | 3 +- pages/framework/pre-post-filters.md | 6 +- pages/framework/results-and-errors.md | 39 +++- pages/framework/routing.md | 27 ++- pages/framework/service-locator.md | 3 +- pages/framework/sessions.md | 6 +- pages/framework/storage.md | 15 +- pages/framework/validation.md | 48 ++-- pages/get-started/create-component.md | 18 +- pages/get-started/create-controller.md | 44 ++-- pages/get-started/create-module.md | 15 +- pages/modules/architecture.md | 44 ++-- .../availability-prices-subscription.md | 52 +++-- .../modules/catalog/bundles-sets-discounts.md | 36 ++- pages/modules/catalog/catalog-settings.md | 46 ++-- pages/modules/catalog/export-import.md | 141 ++++++++---- pages/modules/catalog/inventory-management.md | 45 ++-- pages/modules/catalog/overview.md | 12 +- pages/modules/catalog/performance.md | 36 ++- pages/modules/catalog/products-and-offers.md | 78 ++++--- pages/modules/iblocks/api.md | 215 ++++++++++++------ pages/modules/iblocks/architecture.md | 9 +- pages/modules/iblocks/overview.md | 6 +- pages/modules/iblocks/performance.md | 31 ++- pages/orm/annotations.md | 3 +- pages/orm/collections.md | 54 +++-- pages/orm/entity-operations.md | 9 +- pages/orm/entity-relations.md | 39 ++-- pages/orm/objects.md | 69 ++++-- pages/orm/orm-concepts.md | 17 +- pages/orm/query-builder.md | 9 +- pages/orm/querying-data.md | 83 ++++--- pages/performance/caching.md | 50 ++-- pages/performance/query-optimization.md | 27 ++- pages/security/captcha.md | 13 +- pages/security/cipher.md | 7 +- pages/security/cryptofield.md | 15 +- pages/security/csrf-ssrf.md | 13 +- pages/security/jwt.md | 7 +- 67 files changed, 1338 insertions(+), 638 deletions(-) diff --git a/pages/advanced/datetime.md b/pages/advanced/datetime.md index 0f70850..d3ce198 100644 --- a/pages/advanced/datetime.md +++ b/pages/advanced/datetime.md @@ -230,7 +230,8 @@ echo $diff->days; // 9 ```php use Bitrix\Main\Type\Date; -if (Date::isCorrect('31.02.2025', 'd.m.Y')) { +if (Date::isCorrect('31.02.2025', 'd.m.Y')) +{ // Код не выполнится, так как дата неверна } ``` @@ -295,7 +296,8 @@ $dt3 = new DateTime('2025-11-25 14:30:15+03:00', \DateTime::ATOM); use Bitrix\Main\Type\DateTime; $dt = DateTime::tryParse($request['DATE'], 'd.m.Y H:i'); - if ($dt === null) { + if ($dt === null) + { // Строка имеет неверный формат } ``` diff --git a/pages/advanced/debug.md b/pages/advanced/debug.md index 523cd98..331fa62 100644 --- a/pages/advanced/debug.md +++ b/pages/advanced/debug.md @@ -130,7 +130,8 @@ $connection->stopTracker(); $queries = $tracker->getQueries(); // Перебираем все запросы, которые были выполнены в отслеживаемом участке кода -foreach ($queries as $query) { +foreach ($queries as $query) +{ echo 'SQL: ' . $query->getSql() . '
'; echo 'Время: ' . round($query->getTime(), 5) . ' сек.
'; } @@ -157,7 +158,8 @@ $connection->stopTracker(); $queries = $tracker->getQueries(); -foreach ($queries as $query) { +foreach ($queries as $query) +{ echo 'SQL: ' . $query->getSql() . '
'; echo 'Время: ' . round($query->getTime(), 5) . ' сек.
'; } diff --git a/pages/advanced/geolocation.md b/pages/advanced/geolocation.md index c4a892c..d309fa6 100644 --- a/pages/advanced/geolocation.md +++ b/pages/advanced/geolocation.md @@ -129,7 +129,8 @@ $pos = \Bitrix\Main\Service\GeoIp\Manager::getGeoPosition('92.50.195.50'); $lat = \Bitrix\Main\Service\GeoIp\Manager::getGeoPositionLatitude('92.50.195.50'); $lon = \Bitrix\Main\Service\GeoIp\Manager::getGeoPositionLongitude('92.50.195.50'); -if ($lat !== '' && $lon !== '') { +if ($lat !== '' && $lon !== '') +{ echo "Координаты: $lat, $lon"; } ``` @@ -160,12 +161,15 @@ $geoResult = \Bitrix\Main\Service\GeoIp\Manager::getDataResult( ['countryName', 'cityName', 'latitude', 'longitude'] ); -if ($geoResult && $geoResult->isSuccess()) { +if ($geoResult && $geoResult->isSuccess()) +{ $data = $geoResult->getGeoData(); echo $data->cityName; // Калининград echo $data->countryName; // Россия echo $data->latitude; // 54.70649 -} else { +} +else +{ echo 'Нет данных для этого IP'; } ``` diff --git a/pages/advanced/http-client.md b/pages/advanced/http-client.md index de9a290..f18f9d1 100644 --- a/pages/advanced/http-client.md +++ b/pages/advanced/http-client.md @@ -109,10 +109,13 @@ $http = new HttpClient([ $result = $http->get('https://1c-bitrix.ru/'); -if ($result !== false) { +if ($result !== false) +{ var_dump($http->getStatus()); var_dump($http->getHeaders()); -} else { +} +else +{ var_dump($http->getError()); } ``` @@ -281,13 +284,16 @@ $body->write(http_build_query($data, '', '&')); $request = new Request(Method::POST, $uri, [], $body); -try { +try +{ $response = $http->sendRequest($request); var_dump($response->getStatusCode()); var_dump($response->getHeaders()); var_dump((string)$response->getBody()); -} catch (ClientException $e) { +} +catch (ClientException $e) +{ var_dump($e->getMessage()); } ``` @@ -344,13 +350,16 @@ $request = new Request(Method::POST, $uri, $headers, $body); // Закрываем файл после использования fclose($res); -try { +try +{ $response = $http->sendRequest($request); var_dump($response->getStatusCode()); var_dump($response->getHeaders()); var_dump((string)$response->getBody()); -} catch (ClientException $e) { +} +catch (ClientException $e) +{ var_dump($e->getMessage()); } ``` @@ -380,16 +389,21 @@ $http = new HttpClient([ $uri = new Uri('http://1с-битрикс.рф/'); $request = new Request(Method::GET, $uri); -try { - do { +try +{ + do + { $response = $http->sendRequest($request); - if ($response->hasHeader('Location')) { + if ($response->hasHeader('Location')) + { $location = $response->getHeader('Location')[0]; $request = $request->withUri(new Uri($location)); } } while ($response->hasHeader('Location')); -} catch (ClientException $e) { +} +catch (ClientException $e) +{ var_dump($e->getMessage()); } ``` @@ -425,16 +439,21 @@ $urls = [ 'https://www.1c-bitrix.ru/', ]; -foreach ($urls as $url) { +foreach ($urls as $url) +{ $request = new Request(Method::GET, new Uri($url)); $http->sendAsyncRequest($request); } -try { - foreach ($http->wait() as $response) { +try +{ + foreach ($http->wait() as $response) + { var_dump($response->getStatusCode()); } -} catch (ClientException $e) { +} +catch (ClientException $e) +{ var_dump($e->getMessage()); } ``` @@ -448,17 +467,22 @@ try { ```php $promises = []; -foreach ($urls as $url) { +foreach ($urls as $url) +{ $request = new Request(Method::GET, new Uri($url)); $promises[] = $http->sendAsyncRequest($request); } -foreach ($promises as $promise) { - try { +foreach ($promises as $promise) +{ + try + { $response = $promise->wait(); var_dump($promise->getRequest()->getUri()->getHost()); var_dump($response->getStatusCode()); - } catch (ClientException $e) { + } + catch (ClientException $e) + { var_dump($e->getMessage()); } } @@ -473,7 +497,8 @@ foreach ($promises as $promise) { Callback-функции позволяют строить цепочки обработки без блокирующих вызовов `wait()`. ```php -foreach ($urls as $url) { +foreach ($urls as $url) +{ $request = new Request(Method::GET, new Uri($url)); $promise = $http->sendAsyncRequest($request); @@ -625,7 +650,8 @@ return [ public function format($message, array $context = []): string { // Игнорировать запросы push-сервера - if ($this->request->getUri()->getPort() === 1337) { + if ($this->request->getUri()->getPort() === 1337) + { return ''; } diff --git a/pages/advanced/images.md b/pages/advanced/images.md index 636dab6..5b8fe89 100644 --- a/pages/advanced/images.md +++ b/pages/advanced/images.md @@ -156,7 +156,8 @@ $orientation = $exif['Orientation'] ?? 1; Вызовите метод `load()`, чтобы загрузить изображение в память: ```php -if ($image->load()) { +if ($image->load()) +{ // изображение успешно загружено и готово к обработке } ``` @@ -217,7 +218,8 @@ use Bitrix\Main\File\Image\Rectangle; $image = new Image('/home/bitrix/www/sticker.gif'); -if ($image->load()) { +if ($image->load()) +{ // Исходный прямоугольник по текущим размерам изображения $source = new Rectangle($image->getWidth(), $image->getHeight()); @@ -225,7 +227,8 @@ if ($image->load()) { $destination = new Rectangle(400, 400); // Корректируем $destination с учетом режима пропорций - if ($source->resize($destination, Image::RESIZE_PROPORTIONAL)) { + if ($source->resize($destination, Image::RESIZE_PROPORTIONAL)) + { $image->resize($source, $destination); } } @@ -249,7 +252,8 @@ use Bitrix\Main\File\Image\Mask; $image = new Image('/home/bitrix/www/sticker.gif'); -if ($image->load()) { +if ($image->load()) +{ $image->filter(Mask::createSharpen(15)); } ``` @@ -266,7 +270,8 @@ use Bitrix\Main\File\Image\ImageWatermark; $image = new Image('/home/bitrix/www/sticker.gif'); -if ($image->load()) { +if ($image->load()) +{ $watermark = new ImageWatermark("/home/bitrix/www/watermark.png"); $watermark->setAlpha(70); // прозрачность 70% $image->drawWatermark($watermark); @@ -296,7 +301,8 @@ use Bitrix\Main\File\Image; $image = new Image('/home/bitrix/www/sticker.gif'); -if ($image->load()) { +if ($image->load()) +{ // ... после обработки $image->saveAs("/home/bitrix/www/resized_sticker.gif", 95, Image::FORMAT_GIF); // Освобождаем память diff --git a/pages/advanced/logger.md b/pages/advanced/logger.md index 2d484c0..a439fe3 100644 --- a/pages/advanced/logger.md +++ b/pages/advanced/logger.md @@ -225,7 +225,8 @@ class MyClass implements Log\LoggerAwareInterface public function doSomething() { - if ($this->logger) { + if ($this->logger) + { $this->logger->error('Error!'); } } @@ -255,14 +256,16 @@ class MyClass implements Log\LoggerAwareInterface public function doSomething() { - if ($logger = $this->getLogger()) { + if ($logger = $this->getLogger()) + { $logger->error('Error!'); } } protected function getLogger() { - if ($this->logger === null) { + if ($this->logger === null) + { $logger = Diag\Logger::create('myClassLogger', [$this]); $this->setLogger($logger); } @@ -466,7 +469,8 @@ return [ public function format($message, array $context = []): string { // Игнорируем запросы к push-серверу - if ($this->request->getUri()->getPort() === 1337) { + if ($this->request->getUri()->getPort() === 1337) + { return ''; } diff --git a/pages/advanced/multisite.md b/pages/advanced/multisite.md index 9fbb43a..36d7b9f 100644 --- a/pages/advanced/multisite.md +++ b/pages/advanced/multisite.md @@ -308,32 +308,49 @@ Bitrix Framework поддерживает два режима многосайт $path = rtrim($_POST['path'] ?? '../site_main', "/\\"); $strError = ''; - if ($_POST['create']) { + if ($_POST['create']) + { // Формируем абсолютный путь $full_path = preg_match("#^/#", $path) ? $path : realpath($_SERVER['DOCUMENT_ROOT'].'/'.$path); - if (file_exists($_SERVER["DOCUMENT_ROOT"]."/bitrix")) { + if (file_exists($_SERVER["DOCUMENT_ROOT"]."/bitrix")) + { $strError = "В текущей папке уже существует папка bitrix."; - } elseif (is_dir($full_path)) { - if (is_dir($full_path."/bitrix")) { + } + elseif (is_dir($full_path)) + { + if (is_dir($full_path."/bitrix")) + { // Создаем ссылки - if (!symlink($path."/bitrix", $_SERVER["DOCUMENT_ROOT"]."/bitrix")) { + if (!symlink($path."/bitrix", $_SERVER["DOCUMENT_ROOT"]."/bitrix")) + { $strError = 'Не удалось создать ссылку на папку bitrix.'; - } elseif (!symlink($path."/upload", $_SERVER["DOCUMENT_ROOT"]."/upload")) { + } + elseif (!symlink($path."/upload", $_SERVER["DOCUMENT_ROOT"]."/upload")) + { $strError = 'Не удалось создать ссылку на папку upload.'; - } elseif (!symlink($path."/local", $_SERVER["DOCUMENT_ROOT"]."/local")) { + } + elseif (!symlink($path."/local", $_SERVER["DOCUMENT_ROOT"]."/local")) + { $strError = 'Не удалось создать ссылку на папку local.'; - } else { + } + else + { echo "Символические ссылки успешно созданы."; } - } else { + } + else + { $strError = 'Указанный путь не содержит папку bitrix.'; } - } else { + } + else + { $strError = 'Неверно указан путь или ошибка прав доступа.'; } - if ($strError) { + if ($strError) + { echo '' . $strError . '
Путь: ' . htmlspecialchars($full_path); } } @@ -684,10 +701,12 @@ setcookie("PHPSESSID", "", time() - 3600, '/', '.site.ru'); function MyOnBeforePrologHandler() { global $USER; - if (!is_object($USER)) { + if (!is_object($USER)) + { $USER = new CUser(); } - if (!$USER->IsAdmin()) { + if (!$USER->IsAdmin()) + { include($_SERVER["DOCUMENT_ROOT"] . "/coming-soon/underconstruction.html"); die(); } diff --git a/pages/advanced/quality-monitor.md b/pages/advanced/quality-monitor.md index 63d9628..7f5382a 100644 --- a/pages/advanced/quality-monitor.md +++ b/pages/advanced/quality-monitor.md @@ -153,7 +153,8 @@ class ProjectQualityTests { $path = $_SERVER['DOCUMENT_ROOT'] . '/favicon.ico'; - if (file_exists($path)) { + if (file_exists($path)) + { return [ 'STATUS' => true, 'MESSAGE' => [ diff --git a/pages/advanced/stepper.md b/pages/advanced/stepper.md index f33b603..cf8e8cf 100644 --- a/pages/advanced/stepper.md +++ b/pages/advanced/stepper.md @@ -31,7 +31,8 @@ class ExampleStepper extends Stepper // За один запуск обработаем один шаг и увеличим счетчик прогресса. public function execute(array &$option) { - if (empty($option)) { + if (empty($option)) + { $option['steps'] = 0; // сколько обработано $option['count'] = 100; // всего шагов } @@ -80,7 +81,8 @@ protected $deleteFile = true; ```php // Запустить через 120 секунд - if (\Bitrix\Main\Loader::includeModule('mycompany.mymodule')) { + if (\Bitrix\Main\Loader::includeModule('mycompany.mymodule')) + { \MyCompany\MyModule\Stepper\ExampleStepper::bind(120); } ``` @@ -190,7 +192,8 @@ public function execute(array &$option) ```php public function execute(array &$option) { - if (empty($option)) { + if (empty($option)) + { // Инициализация при первом запуске $option['steps'] = 0; // количество выполненных шагов $option['count'] = $this->calculateTotalItems(); // общее количество шагов diff --git a/pages/cms-basics/admin-panel.md b/pages/cms-basics/admin-panel.md index ef485f6..6d2cd85 100644 --- a/pages/cms-basics/admin-panel.md +++ b/pages/cms-basics/admin-panel.md @@ -292,7 +292,8 @@ $this->AddIncludeAreaIcons( ```php // Проверка режима редактирования -if ($APPLICATION->GetShowIncludeAreas()) { +if ($APPLICATION->GetShowIncludeAreas()) +{ $this->AddIncludeAreaIcons([ // Массив кнопок для панели ]); @@ -377,12 +378,14 @@ $excelMode = $lAdmin->getCurrentMode() === CAdminList::MODE_EXPORT; // Пров ```php // Проверить, было ли отправлено inline-редактирование -if ($lAdmin->EditAction()) { +if ($lAdmin->EditAction()) +{ // Добавить загруженные файлы в список изменяемых полей $lAdmin->convertFilesToEditFields(); // Обработать каждое измененное поле - foreach ($lAdmin->getEditFields() as $id => $fields) { + foreach ($lAdmin->getEditFields() as $id => $fields) + { // Сохранить изменения для записи с ID $id // $fields содержит новые значения полей } @@ -409,22 +412,26 @@ if ($lAdmin->EditAction()) { ```php // Проверить наличие группового действия -if ($itemIds = $lAdmin->GroupAction()) { +if ($itemIds = $lAdmin->GroupAction()) +{ // Получить выбранное действие $actionId = $lAdmin->getAction(); // Пропустить если действие не выбрано - if ($actionId === null) { + if ($actionId === null) + { continue; } // Проверить действие Для всех - if ($lAdmin->isGroupActionToAll()) { + if ($lAdmin->isGroupActionToAll()) + { // В $itemIds теперь все идентификаторы списка } // Обработать каждый элемент - foreach ($itemIds as $itemId) { + foreach ($itemIds as $itemId) + { switch ($actionId) { // Выполнить выбранное действие case 'delete': // Удалить элемент diff --git a/pages/cms-basics/mail.md b/pages/cms-basics/mail.md index 2abb075..590f19a 100644 --- a/pages/cms-basics/mail.md +++ b/pages/cms-basics/mail.md @@ -355,9 +355,12 @@ Bitrix Framework обрабатывает входящие и исходящие 7. Проверьте работу. ```php - @@ -674,7 +677,8 @@ $arTemplate = [ : \Bitrix\Main\Config\Option::get('main', 'site_name', '') ); - if (empty($companyName)) { + if (empty($companyName)) + { $companyName = $arParams["SITE_NAME"]; } @@ -843,7 +847,8 @@ Event::send([ ```php $fileId ? [$fileId] : [], ]); -if ($fileId) { +if ($fileId) +{ \CFile::Delete($fileId); } ?> diff --git a/pages/cms-basics/menu.md b/pages/cms-basics/menu.md index 791758e..55cd214 100644 --- a/pages/cms-basics/menu.md +++ b/pages/cms-basics/menu.md @@ -155,7 +155,8 @@ use Bitrix\Main\Loader; global $APPLICATION; // Подготовим массив для дополнительных пунктов меню $aMenuLinksExt = []; -if(Loader::includeModule('iblock')) { +if(Loader::includeModule('iblock')) +{ // Фильтр для выборки инфоблоков типа catalog и привязанных к текущему сайту $arFilter = [ "TYPE" => "catalog", @@ -164,12 +165,15 @@ if(Loader::includeModule('iblock')) { // Получаем список инфоблоков, сортируем по полю SORT, затем по ID $dbIBlock = CIBlock::GetList(['SORT' => 'ASC', 'ID' => 'ASC'], $arFilter); $dbIBlock = new CIBlockResult($dbIBlock); - if ($arIBlock = $dbIBlock->GetNext()) { - if(defined("BX_COMP_MANAGED_CACHE")) { + if ($arIBlock = $dbIBlock->GetNext()) + { + if(defined("BX_COMP_MANAGED_CACHE")) + { $GLOBALS["CACHE_MANAGER"]->RegisterTag("iblock_id_".$arIBlock["ID"]); } // Если инфоблок активен, подключаем компонент для генерации меню из его разделов - if ($arIBlock["ACTIVE"] == "Y") { + if ($arIBlock["ACTIVE"] == "Y") + { // Подключаем компонент menu.sections $aMenuLinksExt = $APPLICATION->IncludeComponent( "bitrix:menu.sections", @@ -189,7 +193,8 @@ if(Loader::includeModule('iblock')) { ); } } - if (defined("BX_COMP_MANAGED_CACHE")) { + if (defined("BX_COMP_MANAGED_CACHE")) + { $GLOBALS["CACHE_MANAGER"]->RegisterTag("iblock_id_new"); } } @@ -356,7 +361,8 @@ $aMenuLinks = [ Дополнительные параметры передаются в шаблон с помощью массива `$PARAMS` в виде пар `имя => значение`. Например: ```php -if ($PARAMS["SEPARATOR"] === "Y") { +if ($PARAMS["SEPARATOR"] === "Y") +{ // выводим разделитель } ``` @@ -1003,9 +1009,12 @@ $aMenuLinks = [ Если шаблон сайта простой, можно добавить в код проверку с помощью строк: ```php -if ($APPLICATION->GetCurPage() == "/index.php") { +if ($APPLICATION->GetCurPage() == "/index.php") +{ // вывод меню для главной страницы -} else { +} +else +{ // вывод другого меню } ``` @@ -1041,13 +1050,16 @@ if ($APPLICATION->GetCurPage() == "/index.php") { $lastLevel = 0; $selected = false; // Проходим по меню в обратном порядке, чтобы найти выбранный пункт и подсветить его родителей -foreach(array_reverse($arResult) as $arItem){ - if ($arItem["SELECTED"]) { +foreach(array_reverse($arResult) as $arItem) +{ + if ($arItem["SELECTED"]) + { $lastLevel = $arItem["DEPTH_LEVEL"]; // Запоминаем уровень выбранного пункта $selected = true; } // Если уже нашли выбранный пункт и поднимаемся выше по дереву - if ($selected and $arItem["DEPTH_LEVEL"] < $lastLevel) { + if ($selected and $arItem["DEPTH_LEVEL"] < $lastLevel) + { $arResult[$arItem["ITEM_INDEX"]]["SELECTED"] = true; // Подсвечиваем родителя $lastLevel--; // Переходим на уровень выше } @@ -1077,7 +1089,8 @@ foreach($arResult as $arItem): ?> 3. В нижнюю часть сайта `footer.php` добавьте код: ```php - if ($APPLICATION->GetPageProperty('hide_menu') !== 'Y') { + if ($APPLICATION->GetPageProperty('hide_menu') !== 'Y') + { ob_start(); echo 'проверка отложенного меню!'; // здесь выводим меню компонентом или другим способом diff --git a/pages/cms-basics/page-navigation.md b/pages/cms-basics/page-navigation.md index d05abe6..413ae7a 100644 --- a/pages/cms-basics/page-navigation.md +++ b/pages/cms-basics/page-navigation.md @@ -85,7 +85,8 @@ $pagination->initFromUri(); $records = \Bitrix\Main\UserTable::query() ->setLimit($pagination->getLimit()) ->setOffset($pagination->getOffset()) - ->fetchCollection(); + ->fetchCollection() +; ``` Если нужны фильтры, добавьте их в запрос. @@ -95,7 +96,8 @@ $records = \Bitrix\Main\UserTable::query() ->setFilter(['>ID' => 10]) ->setLimit($pagination->getLimit()) ->setOffset($pagination->getOffset()) - ->fetchCollection(); + ->fetchCollection() +; ``` Чтобы получить общее число записей, выполните отдельный запрос до основного: @@ -103,7 +105,8 @@ $records = \Bitrix\Main\UserTable::query() ```php $totalCount = \Bitrix\Main\UserTable::query() ->setFilter(['>ID' => 10]) - ->count(); + ->count() +; $pagination->setRecordCount($totalCount); ``` @@ -229,8 +232,10 @@ echo (string)$pagination->addParams(clone $uri, $isHumanUrl, 3); ) ->exec() ; - foreach ($queryResult as $i => $user) { - if ($i === $pagination->getLimit()) { + foreach ($queryResult as $i => $user) + { + if ($i === $pagination->getLimit()) + { break; } diff --git a/pages/cms-basics/page-templates.md b/pages/cms-basics/page-templates.md index 33c04e5..351579f 100644 --- a/pages/cms-basics/page-templates.md +++ b/pages/cms-basics/page-templates.md @@ -313,8 +313,10 @@ class CBootstrapPageTemplate $gridHtml = '
'; - if (isset($_POST['BT_COL'])) { - switch ($_POST['BT_COL']) { + if (isset($_POST['BT_COL'])) + { + switch ($_POST['BT_COL']) + { case '1': { $gridHtml.= ' @@ -547,8 +549,10 @@ $MESS['BT_COL_4'] = "Мозаика"; '; // Изменение шаблона в зависимости от ответа на первой вопрос об изображении - if (isset($_POST['BT_COL_1'])) { - switch ($_POST['BT_COL_1']) { + if (isset($_POST['BT_COL_1'])) + { + switch ($_POST['BT_COL_1']) + { case '1_1': { $myNewHtml.= ' @@ -578,8 +582,10 @@ $MESS['BT_COL_4'] = "Мозаика";
'; // Изменение шаблона в зависимости от ответа на второй вопрос об обратной связи - if (isset($_POST['BT_COL_2'])) { - switch ($_POST['BT_COL_2']) { + if (isset($_POST['BT_COL_2'])) + { + switch ($_POST['BT_COL_2']) + { case '2_1': { $myNewHtml.= ' diff --git a/pages/cms-basics/sms.md b/pages/cms-basics/sms.md index 3b77209..3848c15 100644 --- a/pages/cms-basics/sms.md +++ b/pages/cms-basics/sms.md @@ -137,8 +137,10 @@ $result = $event->send(false); Метод возвращает объект `\Bitrix\Main\Result`. Получить список ошибок можно кодом: ```php -if (!$result->isSuccess()) { - foreach ($result->getErrorMessages() as $msg) { +if (!$result->isSuccess()) +{ + foreach ($result->getErrorMessages() as $msg) + { echo $msg; } } @@ -151,7 +153,8 @@ if (!$result->isSuccess()) { ```php $result = $event->createMessageList(); -if ($result->isSuccess()) { +if ($result->isSuccess()) +{ $messages = $result->getData(); } ``` @@ -177,11 +180,14 @@ $event = new Event('USER_CONFIRM_PHONE', [ $result = $event ->setSite('s1') // Указываем сайт для поиска шаблона ->setLanguage('ru') // Указываем язык шаблона - ->send(false); // false — отправка через очередь + ->send(false) // false — отправка через очередь +; // Проверяем результат отправки -if (!$result->isSuccess()) { - foreach ($result->getErrorMessages() as $msg) { +if (!$result->isSuccess()) +{ + foreach ($result->getErrorMessages() as $msg) + { echo $msg; } } @@ -195,7 +201,8 @@ if (!$result->isSuccess()) { // Создаем и отправляем событие в одной строке $result = (new Event('PASSWORD_RESTORE', $fields)) // $fields — массив данных для шаблона ->setSite('s1') // Указываем сайт - ->send(true); // true — немедленная отправка без очереди + ->send(true) // true — немедленная отправка без очереди +; ``` #### Отправить сообщение по ID шаблона @@ -207,7 +214,8 @@ $result = (new Event('PASSWORD_RESTORE', $fields)) // $fields — массив $result = (new Event('IGNORED_EVENT', $fields)) // Имя события игнорируется ->setSite('s1') ->setTemplate(105) // Используем шаблон с ID 105 - ->send(); // Отправляем сообщение + ->send() // Отправляем сообщение +; ``` ### Событие onBeforeSendSms @@ -227,7 +235,8 @@ EventManager::getInstance()->addEventHandler( $msg = $event->getParameter('message'); // Проверяем формат номера телефона - if (!preg_match('/^\+?[1-9]\d{7,14}$/', $msg->getTo())) { + if (!preg_match('/^\+?[1-9]\d{7,14}$/', $msg->getTo())) + { // Если номер невалидный — отменяем отправку return new EventResult(EventResult::ERROR); } @@ -419,7 +428,8 @@ $messages = \Bitrix\MessageService\Sender\SmsManager::createMessageListByTemplat ); // Отправляем все созданные сообщения -foreach ($messages as $message) { +foreach ($messages as $message) +{ $message->send(); } ``` @@ -432,11 +442,14 @@ foreach ($messages as $message) { // Получаем статус сообщения по его ID $status = \Bitrix\MessageService\Sender\SmsManager::getMessageStatus($messageId); -if ($status->isSuccess()) { +if ($status->isSuccess()) +{ // Сообщение успешно обработано $statusCode = $status->getExternalStatus(); // Код статуса от провайдера $statusText = $status->getStatusText(); // Текстовое описание статуса -} else { +} +else +{ // Произошла ошибка $errors = $status->getErrorMessages(); // Массив ошибок } @@ -457,8 +470,10 @@ if ($status->isSuccess()) { ```php $result = \Bitrix\MessageService\Sender\SmsManager::sendMessage($messageFields); -if (!$result->isSuccess()) { - foreach ($result->getErrorMessages() as $error) { +if (!$result->isSuccess()) +{ + foreach ($result->getErrorMessages() as $error) + { // Обработка ошибки } } diff --git a/pages/cms-basics/user-groups.md b/pages/cms-basics/user-groups.md index 02f6a68..5a0d3bc 100644 --- a/pages/cms-basics/user-groups.md +++ b/pages/cms-basics/user-groups.md @@ -201,9 +201,12 @@ $newGroupId = $group->Add([ 'USER_ID' => [128, 134], // Опционально: добавить пользователей при создании ]); -if ($newGroupId > 0) { +if ($newGroupId > 0) +{ echo "Группа добавлена, ID: " . $newGroupId; -} else { +} +else +{ echo "Ошибка: " . $group->LAST_ERROR; } ``` @@ -218,7 +221,8 @@ $group->Update($groupId, [ 'DESCRIPTION' => 'Новое Описание группы', 'USER_ID' => [1, 2], ]); -if ($group->LAST_ERROR) { +if ($group->LAST_ERROR) +{ echo "Ошибка: " . $group->LAST_ERROR; } ``` @@ -231,9 +235,11 @@ if ($group->LAST_ERROR) { */ $isDeleted = CGroup::Delete($groupId); -if (!$isDeleted) { +if (!$isDeleted) +{ $error = (string)$APPLICATION->GetException(); - if (empty($error)) { + if (empty($error)) + { $error = "Не пытайтесь удалить группы 1 или 2, они служебные"; } } diff --git a/pages/cms-basics/userfields.md b/pages/cms-basics/userfields.md index 62b032c..3256f45 100644 --- a/pages/cms-basics/userfields.md +++ b/pages/cms-basics/userfields.md @@ -348,7 +348,8 @@ $section = \CIBlockSection::GetList([], [ 'CODE' => 'test_section', ])->Fetch(); -if (!$section) { +if (!$section) +{ throw new \Exception('Секция не найдена'); } @@ -409,7 +410,8 @@ ORM автоматически добавит JOIN к таблице польз После получения коллекции объектов можно работать с пользовательскими полями через геттеры и сеттеры. ```php -foreach ($rows as $row) { +foreach ($rows as $row) +{ $value = $row->getUfGratitude(); $row->setUfGratitude($value + 50); $row->save(); diff --git a/pages/cms-basics/users.md b/pages/cms-basics/users.md index 4380155..924fe73 100644 --- a/pages/cms-basics/users.md +++ b/pages/cms-basics/users.md @@ -151,9 +151,12 @@ $id = $user->Add([ "CONFIRM_PASSWORD" => "strong_password_123", ]); -if ($id > 0) { +if ($id > 0) +{ echo "Пользователь добавлен, ID: " . $id; -} else { +} +else +{ echo "Ошибка: " . $user->LAST_ERROR; } ``` @@ -167,7 +170,8 @@ $user->Update($ID, [ "GROUP_ID" => [2, 3, 5], ]); -if ($user->LAST_ERROR) { +if ($user->LAST_ERROR) +{ echo "Ошибка: " . $user->LAST_ERROR; } ``` @@ -182,10 +186,13 @@ global $USER; */ $authResult = $USER->Login($login, $password, "Y"); -if ($authResult === true) { +if ($authResult === true) +{ // Пользователь успешно авторизовался LocalRedirect("/personal/"); -} else { +} +else +{ // Вывести ошибку ShowMessage($authResult['MESSAGE']); } @@ -225,9 +232,12 @@ global $USER; * @var \CUser $USER */ -if ($USER->IsAuthorized()) { +if ($USER->IsAuthorized()) +{ echo "Пользователь авторизован"; -} else { +} +else +{ echo "Пользователь не авторизован"; } ``` @@ -266,7 +276,8 @@ $users = UserTable::query() /** * @var \Bitrix\Main\EO_User $user */ -foreach ($users as $user) { +foreach ($users as $user) +{ $user->getName(); $user->getEmail(); } @@ -283,12 +294,14 @@ $users = \Bitrix\Main\UserTable::query() 'GROUPS.GROUP_ID' => 1, '=ACTIVE' => 'Y', ]) - ->fetchCollection(); + ->fetchCollection() +; /** * @var \Bitrix\Main\EO_User $user */ -foreach ($users as $user) { +foreach ($users as $user) +{ # code... } ``` @@ -299,13 +312,16 @@ foreach ($users as $user) { $users = \Bitrix\Main\UserTable::query() ->setSelect(['ID', 'GROUPS.GROUP']) ->setLimit(1) - ->fetchCollection(); + ->fetchCollection() +; /** * @var \Bitrix\Main\EO_User $user */ -foreach ($users as $user) { - foreach ($user->getGroups() as $userGroup) { +foreach ($users as $user) +{ + foreach ($user->getGroups() as $userGroup) + { $activeTo = $userGroup->getDateActiveTo(); $activeFrom = $userGroup->getDateActiveFrom(); @@ -329,7 +345,8 @@ global $USER; */ $groupId = 1; -if (in_array($groupId, $USER->GetUserGroupArray())) { +if (in_array($groupId, $USER->GetUserGroupArray())) +{ # code... } ``` @@ -342,9 +359,11 @@ if (in_array($groupId, $USER->GetUserGroupArray())) { */ $isDeleted = CUser::Delete($userId); -if (!$isDeleted) { +if (!$isDeleted) +{ $error = (string)$APPLICATION->GetException(); - if (empty($error)) { + if (empty($error)) + { $error = "Пользователь не найден"; } } diff --git a/pages/database/postgresql/compatible-code.md b/pages/database/postgresql/compatible-code.md index d7cb0b5..1b88aa5 100644 --- a/pages/database/postgresql/compatible-code.md +++ b/pages/database/postgresql/compatible-code.md @@ -249,7 +249,8 @@ SELECT ID, POSITION(',' IN NAME) AS A_POS FROM b_user ```php $lockName = 'mylock'; $connection = \Bitrix\Main\Application::getConnection(); -if ($connection->lock($lockName)) { +if ($connection->lock($lockName)) +{ // ... $connection->unlock($lockName); } @@ -355,12 +356,14 @@ $update = [ 'DATA' => 'a', ]; $merge = $helper->prepareMerge('b_module_table', ['KEY_ID'], $update, $update); -if ($merge[0]) { +if ($merge[0]) +{ $connection->query($merge[0]); } //or another helper method //$update - is a row in a rows array -foreach ($helper->prepareMergeMultiple('b_module_table', ['KEY_ID'], [$update]) as $sql) { +foreach ($helper->prepareMergeMultiple('b_module_table', ['KEY_ID'], [$update]) as $sql) +{ $connection->query($sql); } ``` diff --git a/pages/database/query-execution.md b/pages/database/query-execution.md index e7ee7c5..b390e9d 100644 --- a/pages/database/query-execution.md +++ b/pages/database/query-execution.md @@ -215,7 +215,8 @@ $fields = $db->getTableFields('my_table'); ```php $result = $connection->query('SELECT * FROM b_user'); -foreach ($result as $row) { +foreach ($result as $row) +{ $id = $row['ID']; } ``` @@ -223,7 +224,8 @@ foreach ($result as $row) { Читать построчно: ```php -while ($row = $result->fetch()) { +while ($row = $result->fetch()) +{ $id = $row['ID']; } ``` @@ -282,7 +284,8 @@ $resultIterator->addFetchDataModifier(static function(array $row) { Данные после обработки: ```php -foreach ($resultIterator as $row) { +foreach ($resultIterator as $row) +{ /** * [ID] => 1 * [ACTIVE] => Y diff --git a/pages/database/sql-tracker.md b/pages/database/sql-tracker.md index e7631a9..af328e5 100644 --- a/pages/database/sql-tracker.md +++ b/pages/database/sql-tracker.md @@ -33,7 +33,8 @@ $tracker = \Bitrix\Main\Application::getConnection()->startTracker(true); ## Получить результат ```php -foreach ($tracker->getQueries() as $query) { +foreach ($tracker->getQueries() as $query) +{ print_r([ $query->getSql(), // текст запроса $query->getTime(), // время в секундах diff --git a/pages/database/transactions.md b/pages/database/transactions.md index 760c1fa..bd0af9a 100644 --- a/pages/database/transactions.md +++ b/pages/database/transactions.md @@ -24,7 +24,8 @@ description: 'Транзакции. Работа с базой данных в B ```php $db = \Bitrix\Main\Application::getConnection(); -try { +try +{ $db->startTransaction(); // Пример SQL-запроса @@ -36,7 +37,9 @@ try { \Bitrix\Main\SiteTable::update('s1', ['ACTIVE' => 'N']); $db->commitTransaction(); -} catch (Throwable $e) { +} +catch (Throwable $e) +{ $db->rollbackTransaction(); throw $e; } @@ -93,24 +96,32 @@ use Bitrix\Main\DB\SqlExpression; use Bitrix\Main\DB\TransactionException; // Функция обновления счетов -function updateAccounts(int $userId, Connection $db) { - try { +function updateAccounts(int $userId, Connection $db) +{ + try + { $db->startTransaction(); // Ваш код изменения данных $db->commitTransaction(); - } catch (Throwable $e) { + } + catch (Throwable $e) + { $db->rollbackTransaction(); throw $e; } } // Функция обновления заказов -function updateOrders(int $userId, Connection $db) { - try { +function updateOrders(int $userId, Connection $db) +{ + try + { $db->startTransaction(); // Ваш SQL-запрос $db->commitTransaction(); - } catch (Throwable $e) { + } + catch (Throwable $e) + { $db->rollbackTransaction(); throw $e; } @@ -119,17 +130,22 @@ function updateOrders(int $userId, Connection $db) { // Основная транзакция $db = Application::getConnection(); -try { +try +{ $db->startTransaction(); updateOrders($userId, $db); // Вложенная транзакция updateAccounts($userId, $db); // Вложенная транзакция $db->commitTransaction(); -} catch (TransactionException $e) { +} +catch (TransactionException $e) +{ // Если ошибка во вложенной транзакции $db->rollbackTransaction(); // Откатываем все -} catch (Throwable $e) { +} +catch (Throwable $e) +{ $db->rollbackTransaction(); throw $e; } diff --git a/pages/framework/autoloading.md b/pages/framework/autoloading.md index f9c63cd..0a8e61a 100644 --- a/pages/framework/autoloading.md +++ b/pages/framework/autoloading.md @@ -11,10 +11,12 @@ description: 'Автозагрузка классов. Документация ```php // Подключим модуль CRM, который уже установлен в системе -if (\Bitrix\Main\Loader::includeModule('crm')) { +if (\Bitrix\Main\Loader::includeModule('crm')) +{ // Теперь можно работать с классами CRM } -else { +else +{ // Обработка случая, когда модуль недоступен throw new \Exception('Модуль CRM не установлен'); } diff --git a/pages/framework/background-jobs.md b/pages/framework/background-jobs.md index 776c0da..0eb1bbb 100644 --- a/pages/framework/background-jobs.md +++ b/pages/framework/background-jobs.md @@ -160,7 +160,8 @@ $app->addBackgroundJob(function() { 3. Добавьте в файл строчку: ```php - if (!(defined("CHK_EVENT") && CHK_EVENT===true)) { + if (!(defined("CHK_EVENT") && CHK_EVENT===true)) + { define("BX_CRONTAB_SUPPORT", true); // Разрешаем работу через cron // При этом обычные хиты не будут запускать агентов } @@ -199,7 +200,8 @@ $app->addBackgroundJob(function() { define("BX_CRONTAB", true); // Пометка текущего выполнения как cron // 2. Обрабатываем почтовые события (если модуль установлен) - if(CModule::IncludeModule('sender')) { + if(CModule::IncludeModule('sender')) + { \Bitrix\Sender\MailingManager::checkPeriod(false); \Bitrix\Sender\MailingManager::checkSend(); } @@ -245,7 +247,8 @@ $app->addBackgroundJob(function() { Функция агента — это PHP-код, который выполняется при запуске агента. Функция должна вернуть строку с кодом для следующего запуска. Чтобы остановить агента — пустую строку. ```php -function TestAgent() { +function TestAgent() +{ mail('mail@gmail.com', 'Тест агента', 'Агент работает'); // код функции return "TestAgent();"; // Для повторного запуска // Для остановки агента передайте пустой return ""; @@ -289,8 +292,10 @@ function TestAgent() { ```php // Агент завершится после 5 запусков - class CMyModule { - public static function AgentLimited($count = 1) { + class CMyModule + { + public static function AgentLimited($count = 1) + { if ($count >= 5) return ""; // Остановка агента return "CMyModule::AgentLimited(".($count+1).");"; // Следующий запуск } @@ -308,27 +313,32 @@ function TestAgent() { 3. Обновить курс валют. Курс валюты не должен зависеть от хитов, поэтому агента нужно запускать через cron. ```php - function AgentCurrencyUpdate() { + function AgentCurrencyUpdate() + { // Проверка подключения модуля валют - if (!CModule::IncludeModule('currency')) { + if (!CModule::IncludeModule('currency')) + { return "AgentCurrencyUpdate();"; // Повторить попытку } // Запрос к API ЦБ (возвращает курс рубля к валютам) $json = file_get_contents('https://api.exchangerate.host/latest?base=RUB'); - if (!$json) { + if (!$json) + { return "AgentCurrencyUpdate();"; // Ошибка запроса — повторить } // Декодирование JSON и проверка данных $data = json_decode($json, true); $rates = $data['rates'] ?? []; - if (empty($rates)) { + if (empty($rates)) + { return "AgentCurrencyUpdate();"; // Нет данных — повторить } // Обновление курсов в базе - foreach (['USD', 'EUR'] as $currency) { + foreach (['USD', 'EUR'] as $currency) + { // Конвертируем курс (1 USD = X RUB, 1 RUB = 1/X USD) $convertedRate = 1 / ($rates[$currency] ?? 1); @@ -411,7 +421,8 @@ function TestAgent() { ['user@example.com', 'Добро пожаловать!'], ); - function sendWelcomeEmail($email, $message) { + function sendWelcomeEmail($email, $message) + { mail($email, 'Уведомление', $message); } ``` @@ -423,7 +434,8 @@ function TestAgent() { $tmpFilePath = \Bitrix\Main\Application::getDocumentRoot().'/upload/tmp/'.uniqid('file_'); // Перемещаем загруженный файл в постоянное хранилище - if (!move_uploaded_file($_FILES['big_file']['tmp_name'], $tmpFilePath)) { + if (!move_uploaded_file($_FILES['big_file']['tmp_name'], $tmpFilePath)) + { throw new \Exception('File upload failed'); } diff --git a/pages/framework/components.md b/pages/framework/components.md index b96ecb3..2629301 100644 --- a/pages/framework/components.md +++ b/pages/framework/components.md @@ -112,7 +112,8 @@ $APPLICATION->IncludeComponent( ```php startResultCache()) { + if ($this->startResultCache()) + { // Формируем массив $arResult $this->initResult(); // Подключаем шаблон компонента @@ -236,8 +238,10 @@ $dbIBlockType = CIBlockType::GetList( ["sort" => "asc"], ["ACTIVE" => "Y"] ); -while ($arIBlockType = $dbIBlockType->Fetch()) { - if ($arIBlockTypeLang = CIBlockType::GetByIDLang($arIBlockType["ID"], LANGUAGE_ID)) { +while ($arIBlockType = $dbIBlockType->Fetch()) +{ + if ($arIBlockTypeLang = CIBlockType::GetByIDLang($arIBlockType["ID"], LANGUAGE_ID)) + { $arIblockType[$arIBlockType["ID"]] = "[".$arIBlockType["ID"]."] ".$arIBlockTypeLang["NAME"]; } } @@ -379,11 +383,13 @@ $arComponentParameters = [ Параметр `REFRESH` позволяет перегружать форму параметров после выбора значения. Это полезно, например, для фильтрации списка инфоблоков по типу. ```php -if (isset($arCurrentValues['IBLOCK_ID']) && intval($arCurrentValues['IBLOCK_ID']) > 0) { +if (isset($arCurrentValues['IBLOCK_ID']) && intval($arCurrentValues['IBLOCK_ID']) > 0) +{ $arPropList = []; $rsProps = CIBlockProperty::GetList([], ['IBLOCK_ID' => $arCurrentValues['IBLOCK_ID']]); - while ($arProp = $rsProps->Fetch()) { + while ($arProp = $rsProps->Fetch()) + { $arPropList[$arProp['ID']] = $arProp['NAME']; } @@ -631,14 +637,16 @@ $MESS["SORT_BY1_TIP"] = "Это подсказка для первой сорт use Bitrix\Main\Localization\Loc; use Bitrix\Main\Loader; - if (!Loader::includeModule("advertising")) { + if (!Loader::includeModule("advertising")) + { return; } $arTypeFields = ["-" => Loc::getMessage("ADV_SELECT_DEFAULT")]; $res = CAdvType::GetList($by, $order, Array("ACTIVE" => "Y"),$is_filtered, "Y"); - while (is_object($res) && $ar = $res->GetNext()) { + while (is_object($res) && $ar = $res->GetNext()) + { $arTypeFields[$ar["SID"]] = "[".$ar["SID"]."] ".$ar["NAME"]; } @@ -666,12 +674,15 @@ $MESS["SORT_BY1_TIP"] = "Это подсказка для первой сорт "CACHE_TIME" => ["DEFAULT"=>"0"], ]; - if ($templateProperties['NEED_TEMPLATE'] == 'Y') { + if ($templateProperties['NEED_TEMPLATE'] == 'Y') + { $templates = ['-' => Loc::getMessage("ADV_NOT_SELECTED")]; $arTemplates = CComponentUtil::GetTemplatesList('bitrix:advertising.banner.view'); - if (is_array($arTemplates) && !empty($arTemplates)) { - foreach ($arTemplates as $template) { + if (is_array($arTemplates) && !empty($arTemplates)) + { + foreach ($arTemplates as $template) + { $templates[$template['NAME']] = $template['NAME']; } } @@ -853,7 +864,8 @@ $this->SetResultCacheKeys([ ```php SetTitle($arResult['MY_TITLE']); } ?> @@ -880,7 +892,8 @@ $templateData = [ if (!defined("B_PROLOG_INCLUDED") || B_PROLOG_INCLUDED !== true) die(); // Проверяем, что $templateData определена и содержит данные -if (isset($templateData) && is_array($templateData)) { +if (isset($templateData) && is_array($templateData)) +{ // Используем данные из $templateData $itemCount = $templateData['ITEM_COUNT']; $lastUpdated = $templateData['LAST_UPDATED']; @@ -899,7 +912,8 @@ if (isset($templateData) && is_array($templateData)) { ```php $this->IncludeComponentTemplate(); -if ($arParams["SET_TITLE"]) { +if ($arParams["SET_TITLE"]) +{ $APPLICATION->SetTitle($arResult["NAME"]); } ``` @@ -1006,7 +1020,8 @@ class ExampleComponent extends \CBitrixComponent implements \Bitrix\Main\Engine\ // Пример обработки ошибок public function showMeYourErrorAction():? string { - if (rand(3, 43) === 42) { + if (rand(3, 43) === 42) + { $this->errorCollection[] = new Error('You are so beautiful or so handsome'); // В ответе будут ошибки, и статус ответа будет 'error' return null; diff --git a/pages/framework/controllers.md b/pages/framework/controllers.md index d49f7e9..01f9986 100644 --- a/pages/framework/controllers.md +++ b/pages/framework/controllers.md @@ -447,7 +447,8 @@ final class Post extends Controller public function listAction(\Bitrix\Main\Engine\CurrentUser $user) { $isGuest = empty($user->getId()); - if ($isGuest) { + if ($isGuest) + { $this->addError( new \Bitrix\Main\Error('Need authenticated') ); @@ -535,7 +536,8 @@ final class Post extends Controller public function getAction(string $code) { $post = \MyPost::query()->where('CODE', $code)->fetchObject(); - if (!$post) { + if (!$post) + { $this->addError( new \Bitrix\Main\Error('Not found post') ); @@ -959,7 +961,8 @@ use Bitrix\Main\Error; public function deleteAction(string $code) { $blog = Blog::getByCode($code); - if (!$blog) { + if (!$blog) + { $this->addError(new Error('Блог не найден', 'BLOG_NOT_FOUND')); return null; } diff --git a/pages/framework/cookies.md b/pages/framework/cookies.md index 00a25d2..b2bb0ef 100644 --- a/pages/framework/cookies.md +++ b/pages/framework/cookies.md @@ -58,9 +58,12 @@ description: 'Cookie-файлы. Документация по Bitrix Framework: $cookieValue = $request->getCookie("example_cookie"); // Проверка наличия и вывод значения - if ($cookieValue !== null) { + if ($cookieValue !== null) + { echo "Значение cookie: " . $cookieValue; - } else { + } + else + { echo "Cookie не найдено."; } ``` @@ -152,13 +155,15 @@ require $_SERVER["DOCUMENT_ROOT"] . "/bitrix/modules/main/include/prolog_before. use Bitrix\Main\Application; use Bitrix\Main\Web\Cookie; -if ($_SERVER['REQUEST_METHOD'] === 'POST' && $_POST['ACTION'] === 'selectMyCity') { +if ($_SERVER['REQUEST_METHOD'] === 'POST' && $_POST['ACTION'] === 'selectMyCity') +{ $APPLICATION->RestartBuffer(); header('Content-Type: application/json'); $response = ['STATUS' => 'ERROR', 'MESSAGE' => 'Не удалось добавить cookie']; - if (check_bitrix_sessid()) { + if (check_bitrix_sessid()) + { $city = $_POST['city']; $application = Application::getInstance(); diff --git a/pages/framework/events.md b/pages/framework/events.md index b03292a..d36618d 100644 --- a/pages/framework/events.md +++ b/pages/framework/events.md @@ -200,7 +200,8 @@ final class TicketService $result = new Result(); $error = $this->canClose($ticketId, $closeReason); - if ($error) { + if ($error) + { return $result->addError($error); } @@ -214,14 +215,20 @@ final class TicketService $event = new BeforeTicketCloseEvent($ticketId, $closeReason); $event->send(); - foreach ($event->getResults() as $result) { - if ($result->getType() === EventResult::ERROR) { + foreach ($event->getResults() as $result) + { + if ($result->getType() === EventResult::ERROR) + { return new Error( (string)($result->getParameters()['message'] ?? 'Unknown'), ); - } elseif ($result->getType() === EventResult::SUCCESS) { + } + elseif ($result->getType() === EventResult::SUCCESS) + { // Обработка успешного результата - } elseif ($result->getType() === EventResult::UNDEFINED) { + } + elseif ($result->getType() === EventResult::UNDEFINED) + { // Обработка неопределенного результата } } @@ -238,7 +245,8 @@ final class BeforeTicketCloseEventHandler { public static function handle(BeforeTicketCloseEvent $event): EventResult { - if (self::hasOpenTasks($event->ticketId)) { + if (self::hasOpenTasks($event->ticketId)) + { return new EventResult( EventResult::ERROR, parameters: [ diff --git a/pages/framework/messenger.md b/pages/framework/messenger.md index 84078db..ee5368a 100644 --- a/pages/framework/messenger.md +++ b/pages/framework/messenger.md @@ -431,7 +431,8 @@ class SomeReceiver extends AbstractReceiver { protected function process(MessageInterface $message): void { - if ($message instanceof SectionMessage) { + if ($message instanceof SectionMessage) + { $section = $this->sectionRepository->getById($message->getSectionId()); (new SendSectionCommand($section))->run(); return; diff --git a/pages/framework/pre-post-filters.md b/pages/framework/pre-post-filters.md index 820c94b..76db3cc 100644 --- a/pages/framework/pre-post-filters.md +++ b/pages/framework/pre-post-filters.md @@ -121,14 +121,16 @@ final class RedirectGuestToLogin extends Base public function onBeforeAction(Event $event) { $isAuthorized = $this->getAction()->getController()->getCurrentUser()?->getId() > 0; - if ($isAuthorized) { + if ($isAuthorized) + { return; } $requestUri = Application::getInstance() ->getContext() ->getRequest() - ->getRequestUri(); + ->getRequestUri() + ; \LocalRedirect('/login/?backurl=' . urlencode($requestUri)); } diff --git a/pages/framework/results-and-errors.md b/pages/framework/results-and-errors.md index 1947491..56693e4 100644 --- a/pages/framework/results-and-errors.md +++ b/pages/framework/results-and-errors.md @@ -55,7 +55,8 @@ function updateUserData(int $userId, array $fields): Result { $result = new Result(); - if ($userId <= 0) { + if ($userId <= 0) + { $result->addError(new Error('Неверный ID пользователя', 'INVALID_USER_ID')); return $result; } @@ -63,9 +64,12 @@ function updateUserData(int $userId, array $fields): Result // Обновляем данные $updateResult = someUpdateFunction($userId, $fields); - if ($updateResult === false) { + if ($updateResult === false) + { $result->addError(new Error('Ошибка при обновлении данных', 'UPDATE_FAILED')); - } else { + } + else + { $result->setData(['UPDATED_FIELDS' => $fields]); } @@ -75,10 +79,13 @@ function updateUserData(int $userId, array $fields): Result // Используем функцию $result = updateUserData(123, ['NAME' => 'Иван', 'LAST_NAME' => 'Иванов']); -if ($result->isSuccess()) { +if ($result->isSuccess()) +{ $data = $result->getData(); echo 'Данные обновлены: ' . print_r($data, true); -} else { +} +else +{ $errors = $result->getErrorMessages(); echo 'Ошибки: ' . implode(', ', $errors); } @@ -122,17 +129,21 @@ function updateUserInDatabase(int $userId, array $fields): array function updateUserWithTypedResult(int $userId, array $fields): UserUpdateResult { $result = new UserUpdateResult(); - if ($userId <= 0) { + if ($userId <= 0) + { $result->addError(new Error('Invalid user ID', 100)); return $result; } - try { + try + { $updatedData = updateUserInDatabase($userId, $fields); $result->setUpdatedData( $updatedData, new DateTime() ); - } catch (Exception $e) { + } + catch (Exception $e) + { $result->addError(new Error($e->getMessage(), $e->getCode())); } return $result; @@ -140,12 +151,14 @@ function updateUserWithTypedResult(int $userId, array $fields): UserUpdateResult $typedResult = updateUserWithTypedResult(123, ['NAME' => 'Иван']); -if ($typedResult->isSuccess()) { +if ($typedResult->isSuccess()) +{ $fields = $typedResult->getUpdatedFields(); $time = $typedResult->getTimestamp()->format('Y-m-d H:i:s'); echo 'Данные обновлены. Поля: ' . print_r($fields, true) . ', Время: ' . $time; } -else { +else +{ echo 'Ошибки: ' . implode(', ', $typedResult->getErrorMessages()); } ``` @@ -183,12 +196,14 @@ $errorCollection->setError(new Error('Третья ошибка', 'ERROR_3')); // Получаем ошибку по коду $error = $errorCollection->getErrorByCode('ERROR_2'); -if ($error) { +if ($error) +{ echo 'Найдена ошибка: ' . $error->getMessage(); } // Перебираем ошибки -foreach ($errorCollection as $error) { +foreach ($errorCollection as $error) +{ echo 'Код: ' . $error->getCode() . ', Сообщение: ' . $error->getMessage() . '
'; } ``` diff --git a/pages/framework/routing.md b/pages/framework/routing.md index e2c2f8f..3b4e336 100644 --- a/pages/framework/routing.md +++ b/pages/framework/routing.md @@ -189,7 +189,8 @@ $routes->options('/blog/post/{code}', [PostController::class, 'options']); ```php $routes ->any('/blog/post', [PostController::class, 'update']) - ->methods(['PUT', 'PATCH']); + ->methods(['PUT', 'PATCH']) +; ``` ## Параметры маршрута @@ -234,7 +235,8 @@ class PostViewAction extends \Bitrix\Main\Engine\Action implements \Bitrix\Main\ ```php $app = \Bitrix\Main\Application::getInstance(); -if ($app->hasCurrentRoute()) { +if ($app->hasCurrentRoute()) +{ $code = $app->getCurrentRoute()->getParameterValue('code'); } ``` @@ -254,7 +256,8 @@ if ($app->hasCurrentRoute()) { ```php $routes ->get('/blog/post/{code}', [PostController::class, 'view']) - ->where('code', '[\w\d\-]+'); + ->where('code', '[\w\d\-]+') +; ``` Теперь маршрут будет сопоставляться по регулярному выражению `/blog/post/(?[\w\d\-]+)`. @@ -266,7 +269,8 @@ $routes ```php $routes ->get('/blog/post/{code}/translate/{lang}', [PostController::class, 'translate']) - ->default('lang', 'en'); + ->default('lang', 'en') +; ``` - При переходе на `/blog/post/my-first-article/translate/` параметр `lang` получит значение `en`. @@ -280,7 +284,8 @@ $routes ->get('/blog/post/{code}', static function(string $code, string $lang) { // ... }) - ->default('lang', 'en'); + ->default('lang', 'en') + ; ``` ### Именованные маршруты @@ -292,7 +297,8 @@ $routes ```php $routes ->get('/blog/post/{code}', [PostController::class, 'view']) - ->name('blog.post.view'); + ->name('blog.post.view') +; ``` ### Группировка маршрутов @@ -471,7 +477,8 @@ $url = \Bitrix\Main\Application::getInstance()->getRouter()->route('blog.post.vi ```php $routes ->get('/blog/post-{code}/', [PostController::class, 'view']) - ->name('blog.post.view'); + ->name('blog.post.view') +; ``` Тот же код генерации будет создавать новый URL автоматически. @@ -512,7 +519,8 @@ array( $routes ->any('/blog/{SECTION_ID}/{ELEMENT_ID}/', new PublicPageController('/blog/detail.php')) ->where('SECTION_ID', '\d+') - ->where('ELEMENT_ID', '\d+'); + ->where('ELEMENT_ID', '\d+') +; ``` Контроллер `Bitrix\Main\Routing\Controllers\PublicPageController` подключит нужный физический файл. Но лучше перевести работу на контроллеры. @@ -521,7 +529,8 @@ $routes $routes ->any('/blog/{sectionId}/{elementId}/', [BlogController::class, 'detail']) ->where('sectionId', '\d+') - ->where('elementId', '\d+'); + ->where('elementId', '\d+') +; ``` ## Частые ошибки и решения diff --git a/pages/framework/service-locator.md b/pages/framework/service-locator.md index 73eb163..80d4f66 100644 --- a/pages/framework/service-locator.md +++ b/pages/framework/service-locator.md @@ -11,7 +11,8 @@ Service Locator — это шаблон проектирования для уп ```php $serviceLocator = \Bitrix\Main\DI\ServiceLocator::getInstance(); -if ($serviceLocator->has('someService')) { +if ($serviceLocator->has('someService')) +{ $someService = $serviceLocator->get('someService'); } ``` diff --git a/pages/framework/sessions.md b/pages/framework/sessions.md index 5ff5b07..ebe2211 100644 --- a/pages/framework/sessions.md +++ b/pages/framework/sessions.md @@ -11,7 +11,8 @@ description: 'Сессии. Документация по Bitrix Framework: пр ```php $session = \Bitrix\Main\Application::getInstance()->getSession(); -if (!$session->has('foo')) { +if (!$session->has('foo')) +{ $session->set('foo', 'bar'); } echo $session['foo']; //bar @@ -25,7 +26,8 @@ echo $session['foo']; //bar ```php $localStorage = \Bitrix\Main\Application::getInstance()->getLocalSession('someCategory'); -if (!isset($localStorage['productIds'])) { +if (!isset($localStorage['productIds'])) +{ $localStorage->set('productIds', [1, 2, 100]); $localStorage->set('price', 42); } diff --git a/pages/framework/storage.md b/pages/framework/storage.md index 75047e7..58cb68c 100644 --- a/pages/framework/storage.md +++ b/pages/framework/storage.md @@ -49,7 +49,8 @@ Bitrix Framework предлагает два решения для управл ```php $storage = \Bitrix\Main\DI\ServiceLocator::getInstance() - ->get(\Bitrix\Main\Data\Storage\PersistentStorageInterface::class); + ->get(\Bitrix\Main\Data\Storage\PersistentStorageInterface::class) +; ``` {% note tip "" %} @@ -70,7 +71,8 @@ $storage = \Bitrix\Main\DI\ServiceLocator::getInstance() ```php $storage = \Bitrix\Main\DI\ServiceLocator::getInstance() - ->get(\Bitrix\Main\Data\Storage\PersistentStorageInterface::class); + ->get(\Bitrix\Main\Data\Storage\PersistentStorageInterface::class) +; $storage->set('mymodule.feature_processing.feature123', ['somedata' => 12345], 3600); @@ -89,7 +91,8 @@ $storage->set('key', 'value', $interval); ```php $storage = \Bitrix\Main\DI\ServiceLocator::getInstance() - ->get(\Bitrix\Main\Data\Storage\PersistentStorageInterface::class); + ->get(\Bitrix\Main\Data\Storage\PersistentStorageInterface::class) +; $value = $storage->get('mymodule.feature_processing.feature123', 'default value'); @@ -172,7 +175,8 @@ $storage->deleteMultiple([ ```php // Получаем базовое хранилище $baseStorage = \Bitrix\Main\DI\ServiceLocator::getInstance() - ->get(\Bitrix\Main\Data\Storage\PersistentStorageInterface::class); + ->get(\Bitrix\Main\Data\Storage\PersistentStorageInterface::class) +; // Создаем декоратор с отложенным сохранением $deferredStorage = new \Bitrix\Main\Data\Storage\DeferredStorageDecorator($baseStorage); @@ -195,7 +199,8 @@ $deferredStorage->save(); ```php $baseStorage = \Bitrix\Main\DI\ServiceLocator::getInstance() - ->get(\Bitrix\Main\Data\Storage\PersistentStorageInterface::class); + ->get(\Bitrix\Main\Data\Storage\PersistentStorageInterface::class) +; $deferredStorage = new \Bitrix\Main\Data\Storage\DeferredStorageDecorator($baseStorage); ``` diff --git a/pages/framework/validation.md b/pages/framework/validation.md index 9b2c609..2e07651 100644 --- a/pages/framework/validation.md +++ b/pages/framework/validation.md @@ -12,7 +12,8 @@ description: 'Валидация. Документация по Bitrix Framework ```php public function __construct(int $userId) { - if ($userId <= 0) { + if ($userId <= 0) + { throw new \Exception(); } $this->userId = $userId; @@ -91,7 +92,8 @@ public function __construct(int $userId) $user->setPhone($phone); $result = $this->validation->validate($user); - if (!$result->isSuccess()) { + if (!$result->isSuccess()) + { return $result; } @@ -147,7 +149,8 @@ $buyer = new Buyer(); $buyer->id = 0; $result1 = $validationService->validate($buyer); // "id: Значение поля меньше допустимого" -foreach ($result1->getErrors() as $error) { +foreach ($result1->getErrors() as $error) +{ echo $error->getCode() . ': ' . $error->getMessage(). PHP_EOL; } echo PHP_EOL; @@ -158,7 +161,8 @@ $order->id = -1; $buyer->order = $order; $result2 = $validationService->validate($buyer); // "order.id: Значение поля меньше допустимого" -foreach ($result2->getErrors() as $error) { +foreach ($result2->getErrors() as $error) +{ echo $error->getCode() . ': ' . $error->getMessage(). PHP_EOL; } echo PHP_EOL; @@ -171,7 +175,8 @@ $buyer->order->payment = $payment; $result3 = $validationService->validate($buyer); // "order.payment.status: Значение поля не может быть пустым" // "order.payment.systemCode: Custom message error" -foreach ($result3->getErrors() as $error) { +foreach ($result3->getErrors() as $error) +{ echo $error->getCode() . ': ' . $error->getMessage(). PHP_EOL; } ``` @@ -256,8 +261,10 @@ $article->tags = [ ]; $result = $validationService->validate($article); -if (!$result->isSuccess()) { - foreach ($result->getErrors() as $error) { +if (!$result->isSuccess()) +{ + foreach ($result->getErrors() as $error) + { // Путь к ошибке будет включать индекс элемента, например: "tags.2.name" echo $error->getCode() . ': ' . $error->getMessage() . PHP_EOL; } @@ -321,7 +328,8 @@ class UserController extends Controller $dto->passwordRepeat = (string)$this->getRequest()->get('passwordRepeat'); $result = $this->validation->validate($dto); - if (!$result->isSuccess()) { + if (!$result->isSuccess()) + { $this->addErrors($result->getErrors()); return false; @@ -415,7 +423,8 @@ use Bitrix\Main\Validation\Validator\EmailValidator; $email = 'bitrix@bitrix.ru'; $validator = new EmailValidator(); $result = $validator->validate($email); -if (!$result->isSuccess()) { +if (!$result->isSuccess()) +{ // ... } ``` @@ -438,7 +447,8 @@ class User $user = new User(-150); /** @var \Bitrix\Main\Validation\ValidationService $service */ $result = $service->validate($user); -foreach ($result->getErrors() as $error) { +foreach ($result->getErrors() as $error) +{ echo $error->getMessage(); } // output: 'Invalid ID!' @@ -459,7 +469,8 @@ class User $user = new User(-150); /** @var \Bitrix\Main\Validation\ValidationService $service */ $result = $service->validate($user); -foreach ($result->getErrors() as $error) { +foreach ($result->getErrors() as $error) +{ echo $error->getMessage(); } // output: 'Значение поля меньше допустимого' @@ -471,7 +482,8 @@ foreach ($result->getErrors() as $error) { ```php $errors = $service->validate($dto)->getErrors(); -foreach ($errors as $error) { +foreach ($errors as $error) +{ $failedValidator = $error->getFailedValidator(); // ... } @@ -575,7 +587,8 @@ final class Min implements ValidatorInterface public function validate(mixed $value): ValidationResult { $result = new ValidationResult(); - if (!is_numeric($value)) { + if (!is_numeric($value)) + { $result->addError( new ValidationError( Loc::getMessage('MAIN_VALIDATION_MIN_NOT_A_NUMBER'), @@ -584,7 +597,8 @@ final class Min implements ValidatorInterface ); return $result; } - if ($value < $this->min) { + if ($value < $this->min) + { $result->addError( new ValidationError( Loc::getMessage('MAIN_VALIDATION_MIN_LESS_THAN_MIN'), @@ -618,7 +632,8 @@ class NotOne implements PropertyValidationAttributeInterface public function validateProperty(mixed $propertyValue): ValidationResult { $result = new ValidationResult(); - if ($propertyValue === 1) { + if ($propertyValue === 1) + { $result->addError(new ValidationError('Значение не должно быть равно 1')); } return $result; @@ -678,7 +693,8 @@ class NotOne extends AbstractClassValidationAttribute $result = new ValidationResult(); $properties = (new ReflectionClass($object))->getProperties(); - if (count($properties) > 2) { + if (count($properties) > 2) + { $result->addError(new ValidationError('Класс содержит слишком много свойств')); } return $result; diff --git a/pages/get-started/create-component.md b/pages/get-started/create-component.md index dd8df6f..117d2d2 100644 --- a/pages/get-started/create-component.md +++ b/pages/get-started/create-component.md @@ -139,11 +139,13 @@ class UserCardComponent extends CBitrixComponent public function executeComponent() { // Кешируем результат, чтобы не делать постоянные запросы к базе - if ($this->startResultCache()) { + if ($this->startResultCache()) + { $this->initResult(); // Если ничего не найдено, отменяем кеширование - if (empty($this->arResult)) { + if (empty($this->arResult)) + { $this->abortResultCache(); ShowError('Пользователь не найден'); @@ -162,7 +164,8 @@ class UserCardComponent extends CBitrixComponent private function initResult(): void { $userId = (int)$this->arParams['USER_ID']; - if ($userId < 1) { + if ($userId < 1) + { return; } @@ -173,9 +176,11 @@ class UserCardComponent extends CBitrixComponent 'PERSONAL_PHOTO', ]) ->where('ID', $userId) - ->fetch(); + ->fetch() + ; - if (empty($user)) { + if (empty($user)) + { return; } @@ -185,7 +190,8 @@ class UserCardComponent extends CBitrixComponent ]; // Получаем путь до аватара, если он указан - if (!empty($user['PERSONAL_PHOTO'])) { + if (!empty($user['PERSONAL_PHOTO'])) + { $this->arResult['PERSONAL_PHOTO_SRC'] = \CFile::GetPath($user['PERSONAL_PHOTO']); } } diff --git a/pages/get-started/create-controller.md b/pages/get-started/create-controller.md index dfde504..e4fb3d1 100644 --- a/pages/get-started/create-controller.md +++ b/pages/get-started/create-controller.md @@ -170,19 +170,24 @@ class LikeService private function getLikedUsersIds(): array { - try { + try + { $cookieValue = Context::getCurrent()->getRequest()->getCookie(self::COOKIE_NAME); - if (empty($cookieValue)) { + if (empty($cookieValue)) + { return []; } $value = Json::decode($cookieValue); - if (!is_array($value)) { + if (!is_array($value)) + { return []; } return $value; - } catch (ArgumentException) { + } + catch (ArgumentException) + { return []; } } @@ -255,7 +260,8 @@ class User extends Controller public function likeAction(LikeService $service, int $likedUserId) { // Базовая валидация: ID должен быть положительным целым - if ($likedUserId < 1) { + if ($likedUserId < 1) + { $this->addError(new Error('Неверный ID пользователя')); return null; @@ -263,9 +269,12 @@ class User extends Controller // Если лайка нет — добавляем, иначе удаляем $isLikeAction = !$service->isLiked($likedUserId); - if ($isLikeAction) { + if ($isLikeAction) + { $service->likeUser($likedUserId); - } else { + } + else + { $service->dislikeUser($likedUserId); } @@ -485,18 +494,21 @@ class UserCardComponent extends CBitrixComponent public function executeComponent() { - if (!Loader::includeModule('my.module')) { + if (!Loader::includeModule('my.module')) + { ShowError('Модуль my.module не установлен'); return; } // кешируем результат, чтобы не делать постоянные запросы к базе - if ($this->startResultCache()) { + if ($this->startResultCache()) + { $this->initResult(); // в случае если ничего не найдено, отменяем кеширование - if (empty($this->arResult)) { + if (empty($this->arResult)) + { $this->abortResultCache(); ShowError('Пользователь не найден'); @@ -514,7 +526,8 @@ class UserCardComponent extends CBitrixComponent private function initResult(): void { $userId = (int)$this->arParams['USER_ID']; - if ($userId < 1) { + if ($userId < 1) + { return; } @@ -526,9 +539,11 @@ class UserCardComponent extends CBitrixComponent 'PERSONAL_PHOTO', ]) ->where('ID', $userId) - ->fetch(); + ->fetch() + ; - if (empty($user)) { + if (empty($user)) + { return; } @@ -539,7 +554,8 @@ class UserCardComponent extends CBitrixComponent ]; // получаем путь до аватарки, в случае если она указана - if (!empty($user['PERSONAL_PHOTO'])) { + if (!empty($user['PERSONAL_PHOTO'])) + { $this->arResult['PERSONAL_PHOTO_SRC'] = \CFile::GetPath($user['PERSONAL_PHOTO']); } } diff --git a/pages/get-started/create-module.md b/pages/get-started/create-module.md index 7b848cf..23a1b9b 100644 --- a/pages/get-started/create-module.md +++ b/pages/get-started/create-module.md @@ -146,7 +146,8 @@ class my_module extends CModule { include __DIR__ . '/version.php'; - if (isset($arModuleVersion['VERSION'], $arModuleVersion['VERSION_DATE'])) { + if (isset($arModuleVersion['VERSION'], $arModuleVersion['VERSION_DATE'])) + { $this->MODULE_VERSION = $arModuleVersion['VERSION']; $this->MODULE_VERSION_DATE = $arModuleVersion['VERSION_DATE']; } @@ -159,7 +160,8 @@ class my_module extends CModule { global $USER, $APPLICATION; - if (!$USER->IsAdmin()) { + if (!$USER->IsAdmin()) + { return; } @@ -178,7 +180,8 @@ class my_module extends CModule { global $USER, $APPLICATION; - if (!$USER->IsAdmin()) { + if (!$USER->IsAdmin()) + { return; } @@ -250,7 +253,8 @@ class my_module extends CModule ```php MODULE_VERSION = $arModuleVersion['VERSION']; $this->MODULE_VERSION_DATE = $arModuleVersion['VERSION_DATE'] ?? null; } @@ -251,7 +254,8 @@ class vendor_modulename extends CModule $errors = $db->executeSqlBatch( __DIR__ . '/' . $db->getType() . '/install.sql' ); - if (!empty($errors)) { + if (!empty($errors)) + { $APPLICATION->ThrowException( join(',', $errors) ); @@ -269,7 +273,8 @@ class vendor_modulename extends CModule $errors = $db->executeSqlBatch( __DIR__ . '/' . $db->getType() . '/uninstall.sql' ); - if (!empty($errors)) { + if (!empty($errors)) + { $APPLICATION->ThrowException( join(',', $errors) ); @@ -379,7 +384,8 @@ class company_module extends CModule public function InstallDB(array $params = []) { - if (($params['createDemoData'] ?? 'N') === 'Y') { + if (($params['createDemoData'] ?? 'N') === 'Y') + { // Создание демонстрационных данных модуля } @@ -390,13 +396,15 @@ class company_module extends CModule { global $APPLICATION; - if (!check_bitrix_sessid()) { + if (!check_bitrix_sessid()) + { return false; } $step = (int)($_REQUEST['step'] ?? 1); - if ($step < 2) { + if ($step < 2) + { $APPLICATION->IncludeAdminFile( 'Установка модуля', __DIR__ . '/install_step1.php' @@ -496,7 +504,8 @@ class company_module extends CModule public function DoUninstall() { - if (!check_bitrix_sessid()) { + if (!check_bitrix_sessid()) + { return false; } @@ -504,7 +513,8 @@ class company_module extends CModule $step = (int)($_REQUEST['step'] ?? 1); - if ($step < 2) { + if ($step < 2) + { $APPLICATION->IncludeAdminFile( 'Удаление модуля', __DIR__ . '/uninstall_step1.php' @@ -530,7 +540,8 @@ class company_module extends CModule public function UnInstallDB(array $params = []) { - if (($params['savedata'] ?? 'N') === 'Y') { + if (($params['savedata'] ?? 'N') === 'Y') + { return true; } @@ -548,7 +559,8 @@ class company_module extends CModule @@ -682,7 +694,7 @@ require_once($_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/company.module/prolog. /local/modules/company.module/ ├── admin/ │ └── my_page.php -├── lang/ +└── lang/ ├── en/ │ └── admin/ │ └── my_page.php @@ -768,7 +780,8 @@ return [ ```php 'news'])->Fetch()['ID']; // Дальнейшая работа с инфоблоком } @@ -798,7 +811,8 @@ return [ 0 && \Bitrix\Main\Loader::includeModule('iblock')) { + if ($iblockId > 0 && \Bitrix\Main\Loader::includeModule('iblock')) + { // Работа с инфоблоком, который выбран в настройках модуля } ``` diff --git a/pages/modules/catalog/availability-prices-subscription.md b/pages/modules/catalog/availability-prices-subscription.md index 3cd3946..cdaaed9 100644 --- a/pages/modules/catalog/availability-prices-subscription.md +++ b/pages/modules/catalog/availability-prices-subscription.md @@ -38,7 +38,8 @@ $result = \Bitrix\Catalog\Model\Product::update($productId, [ 'CAN_BUY_ZERO' => 'N', ]); -if (!$result->isSuccess()) { +if (!$result->isSuccess()) +{ throw new \RuntimeException(implode('; ', $result->getErrorMessages())); } ``` @@ -70,7 +71,8 @@ $result = \Bitrix\Catalog\Model\Product::update($offerId, [ 'CAN_BUY_ZERO' => 'N', ]); -if (!$result->isSuccess()) { +if (!$result->isSuccess()) +{ throw new \RuntimeException(implode('; ', $result->getErrorMessages())); } ``` @@ -100,7 +102,8 @@ $result = \Bitrix\Catalog\Model\Product::update($productId, [ 'NEGATIVE_AMOUNT_TRACE' => 'Y', ]); -if (!$result->isSuccess()) { +if (!$result->isSuccess()) +{ throw new \RuntimeException(implode('; ', $result->getErrorMessages())); } ``` @@ -124,7 +127,8 @@ $productRow = \Bitrix\Catalog\ProductTable::getList([ 'limit' => 1, ])->fetch(); -if (!$productRow) { +if (!$productRow) +{ throw new \RuntimeException('Товар не найден'); } ``` @@ -196,12 +200,15 @@ $price = \Bitrix\Catalog\Model\Price::getList([ ], ])->fetch(); -if ($price) { +if ($price) +{ $result = \Bitrix\Catalog\Model\Price::update((int)$price['ID'], [ 'PRICE' => 1350.00, 'CURRENCY' => 'RUB', ]); -} else { +} +else +{ $result = \Bitrix\Catalog\Model\Price::add([ 'PRODUCT_ID' => $productId, 'CATALOG_GROUP_ID' => $basePriceTypeId, @@ -210,7 +217,8 @@ if ($price) { ]); } -if (!$result->isSuccess()) { +if (!$result->isSuccess()) +{ throw new \RuntimeException(implode('; ', $result->getErrorMessages())); } ``` @@ -241,7 +249,8 @@ $result = \Bitrix\Catalog\Model\Price::add([ 'QUANTITY_TO' => 9, ]); -if (!$result->isSuccess()) { +if (!$result->isSuccess()) +{ throw new \RuntimeException(implode('; ', $result->getErrorMessages())); } @@ -254,7 +263,8 @@ $result = \Bitrix\Catalog\Model\Price::add([ 'QUANTITY_TO' => null, ]); -if (!$result->isSuccess()) { +if (!$result->isSuccess()) +{ throw new \RuntimeException(implode('; ', $result->getErrorMessages())); } ``` @@ -282,7 +292,8 @@ $quantityPrice = \CCatalogProduct::GetNearestQuantityPrice( $userGroups ); -if ($quantityPrice) { +if ($quantityPrice) +{ echo $quantityPrice['PRICE']; } ``` @@ -325,7 +336,8 @@ $optimalPrice = \CCatalogProduct::GetOptimalPrice( SITE_ID ); -if ($optimalPrice) { +if ($optimalPrice) +{ echo $optimalPrice['RESULT_PRICE']['DISCOUNT_PRICE']; } ``` @@ -409,7 +421,8 @@ $subscribeId = $subscribeManager->addSubscribe([ 'USER_ID' => 15, ]); -if (!$subscribeId) { +if (!$subscribeId) +{ $error = current($subscribeManager->getErrors()); $message = $error ? $error->getMessage() : 'Не удалось добавить подписку'; @@ -439,7 +452,8 @@ $subscribeRow = \Bitrix\Catalog\SubscribeTable::getList([ 'limit' => 1, ])->fetch(); -if ($subscribeRow) { +if ($subscribeRow) +{ $subscribeId = (int)$subscribeRow['ID']; } ``` @@ -453,7 +467,8 @@ if ($subscribeRow) { ```php $subscribeManager = new \Bitrix\Catalog\Product\SubscribeManager; -if (!$subscribeManager->deactivateSubscription([$subscribeId])) { +if (!$subscribeManager->deactivateSubscription([$subscribeId])) +{ $error = current($subscribeManager->getErrors()); $message = $error ? $error->getMessage() : 'Не удалось отключить подписку'; @@ -466,7 +481,8 @@ if (!$subscribeManager->deactivateSubscription([$subscribeId])) { ```php $subscribeManager = new \Bitrix\Catalog\Product\SubscribeManager; -if (!$subscribeManager->deleteManySubscriptions([$subscribeId], $productId)) { +if (!$subscribeManager->deleteManySubscriptions([$subscribeId], $productId)) +{ $error = current($subscribeManager->getErrors()); $message = $error ? $error->getMessage() : 'Не удалось удалить подписку'; @@ -486,7 +502,8 @@ $unsubscribed = $subscribeManager->unSubscribe([ 'productId' => $productId, ]); -if (!$unsubscribed) { +if (!$unsubscribed) +{ $error = current($subscribeManager->getErrors()); $message = $error ? $error->getMessage() : 'Не удалось отписать пользователя'; @@ -509,7 +526,8 @@ if (!$unsubscribed) { Если нужно вручную поставить активные подписки товара в очередь отправки, вызовите `runAgentToSendNotice()`. ```php -if (!\Bitrix\Catalog\SubscribeTable::runAgentToSendNotice($productId)) { +if (!\Bitrix\Catalog\SubscribeTable::runAgentToSendNotice($productId)) +{ throw new \RuntimeException('Не удалось поставить уведомления в очередь'); } ``` diff --git a/pages/modules/catalog/bundles-sets-discounts.md b/pages/modules/catalog/bundles-sets-discounts.md index db0a8a9..f4f2af3 100644 --- a/pages/modules/catalog/bundles-sets-discounts.md +++ b/pages/modules/catalog/bundles-sets-discounts.md @@ -32,7 +32,8 @@ $result = \Bitrix\Catalog\Model\Product::update($productId, [ 'TYPE' => \Bitrix\Catalog\ProductTable::TYPE_SET, ]); -if (!$result->isSuccess()) { +if (!$result->isSuccess()) +{ throw new \RuntimeException(implode('; ', $result->getErrorMessages())); } ``` @@ -77,7 +78,8 @@ $setId = \CCatalogProductSet::add([ ], ]); -if (!$setId) { +if (!$setId) +{ $errors = \CCatalogProductSet::getErrors(); $message = $errors ? $errors[0]['text'] : 'Не удалось создать комплект'; @@ -124,7 +126,8 @@ $isUpdated = \CCatalogProductSet::update($setId, [ ], ]); -if (!$isUpdated) { +if (!$isUpdated) +{ $errors = \CCatalogProductSet::getErrors(); $message = $errors ? $errors[0]['text'] : 'Не удалось обновить комплект'; @@ -170,7 +173,8 @@ $groupId = \CCatalogProductSet::add([ ], ]); -if (!$groupId) { +if (!$groupId) +{ $errors = \CCatalogProductSet::getErrors(); $message = $errors ? $errors[0]['text'] : 'Не удалось создать набор'; @@ -212,7 +216,8 @@ $isUpdated = \CCatalogProductSet::update($groupId, [ ], ]); -if (!$isUpdated) { +if (!$isUpdated) +{ $errors = \CCatalogProductSet::getErrors(); $message = $errors ? $errors[0]['text'] : 'Не удалось обновить набор'; @@ -227,7 +232,8 @@ if (!$isUpdated) { Комплект или набор можно удалить с помощью `CCatalogProductSet::delete()`. В метод передайте идентификатор комплекта или набора. В примере удаляется комплект по `$setId`. ```php -if (!\CCatalogProductSet::delete($setId)) { +if (!\CCatalogProductSet::delete($setId)) +{ $errors = \CCatalogProductSet::getErrors(); $message = $errors ? $errors[0]['text'] : 'Не удалось удалить комплект или набор'; @@ -305,7 +311,8 @@ $discountId = \CCatalogDiscount::Add([ ], ]); -if (!$discountId) { +if (!$discountId) +{ global $APPLICATION; $exception = $APPLICATION->GetException(); $message = $exception ? $exception->GetString() : 'Не удалось создать скидку'; @@ -343,7 +350,8 @@ $couponResult = \Bitrix\Catalog\DiscountCouponTable::add([ 'TYPE' => \Bitrix\Catalog\DiscountCouponTable::TYPE_ONE_ORDER, ]); -if (!$couponResult->isSuccess()) { +if (!$couponResult->isSuccess()) +{ throw new \RuntimeException(implode('; ', $couponResult->getErrorMessages())); } @@ -365,11 +373,13 @@ if (!$couponResult->isSuccess()) { {% endnote %} ```php -if (!\Bitrix\Main\Loader::includeModule('sale')) { +if (!\Bitrix\Main\Loader::includeModule('sale')) +{ throw new \RuntimeException('Не удалось подключить модуль sale'); } -if (!\Bitrix\Sale\DiscountCouponsManager::add('SALE-10-PRODUCT')) { +if (!\Bitrix\Sale\DiscountCouponsManager::add('SALE-10-PRODUCT')) +{ throw new \RuntimeException('Не удалось добавить купон в расчет'); } ``` @@ -399,11 +409,13 @@ $discounts = \CCatalogDiscount::GetDiscountByProduct( SITE_ID ); -if ($discounts === false) { +if ($discounts === false) +{ throw new \RuntimeException('Не удалось получить скидки товара'); } -foreach ($discounts as $discount) { +foreach ($discounts as $discount) +{ echo $discount['NAME'] . "\n"; } ``` diff --git a/pages/modules/catalog/catalog-settings.md b/pages/modules/catalog/catalog-settings.md index ac6373b..40b2224 100644 --- a/pages/modules/catalog/catalog-settings.md +++ b/pages/modules/catalog/catalog-settings.md @@ -28,7 +28,8 @@ description: 'Базовые настройки каталога. Модуль ```php $basePriceType = \Bitrix\Catalog\GroupTable::getBasePriceType(); -if (!$basePriceType) { +if (!$basePriceType) +{ throw new \RuntimeException('Базовый тип цен не найден'); } @@ -68,7 +69,8 @@ $wholesalePriceTypeId = \CCatalogGroup::Add([ ], ]); -if (!$wholesalePriceTypeId) { +if (!$wholesalePriceTypeId) +{ global $APPLICATION; $exception = $APPLICATION->GetException(); $message = $exception ? $exception->GetString() : 'Не удалось создать тип цены'; @@ -112,12 +114,15 @@ $accessRows = \Bitrix\Catalog\GroupAccessTable::getList([ ], ])->fetchAll(); -foreach ($accessRows as $row) { - if ($row['ACCESS'] === 'ACCESS_VIEW') { +foreach ($accessRows as $row) +{ + if ($row['ACCESS'] === 'ACCESS_VIEW') + { echo "Группа {$row['GROUP_ID']} видит цену\n"; } - if ($row['ACCESS'] === 'ACCESS_BUY') { + if ($row['ACCESS'] === 'ACCESS_BUY') + { echo "Группа {$row['GROUP_ID']} может покупать по этой цене\n"; } } @@ -153,7 +158,8 @@ $result = \Bitrix\Catalog\Model\Vat::add([ 'SORT' => 100, ]); -if (!$result->isSuccess()) { +if (!$result->isSuccess()) +{ throw new \RuntimeException(implode('; ', $result->getErrorMessages())); } @@ -184,7 +190,8 @@ $result = \Bitrix\Catalog\Model\Product::update($productId, [ 'VAT_INCLUDED' => 'Y', ]); -if (!$result->isSuccess()) { +if (!$result->isSuccess()) +{ throw new \RuntimeException(implode('; ', $result->getErrorMessages())); } ``` @@ -228,19 +235,22 @@ $productRow = \Bitrix\Catalog\ProductTable::getList([ 'limit' => 1, ])->fetch(); -if (!$productRow) { +if (!$productRow) +{ throw new \RuntimeException('Товар не найден в каталоге'); } $vatRate = null; -if ((int)$productRow['VAT_ID'] > 0) { +if ((int)$productRow['VAT_ID'] > 0) +{ $vatRow = \Bitrix\Catalog\VatTable::getList([ 'select' => ['ID', 'NAME', 'RATE', 'ACTIVE'], 'filter' => ['=ID' => (int)$productRow['VAT_ID']], 'limit' => 1, ])->fetch(); - if ($vatRow) { + if ($vatRow) + { $vatRate = (float)$vatRow['RATE']; } } @@ -272,7 +282,8 @@ $result = \Bitrix\Catalog\MeasureTable::add([ 'IS_DEFAULT' => 'N', ]); -if (!$result->isSuccess()) { +if (!$result->isSuccess()) +{ throw new \RuntimeException(implode('; ', $result->getErrorMessages())); } @@ -312,7 +323,8 @@ $result = \Bitrix\Catalog\Model\Product::update($productId, [ 'MEASURE' => $measureId, ]); -if (!$result->isSuccess()) { +if (!$result->isSuccess()) +{ throw new \RuntimeException(implode('; ', $result->getErrorMessages())); } ``` @@ -351,12 +363,15 @@ $ratioRow = \Bitrix\Catalog\MeasureRatioTable::getList([ ])->fetch(); // Обновляем существующий коэффициент или создаем новый -if ($ratioRow) { +if ($ratioRow) +{ // У товара есть коэффициент -- обновляем его $result = \Bitrix\Catalog\MeasureRatioTable::update((int)$ratioRow['ID'], [ 'RATIO' => $ratioValue, ]); -} else { +} +else +{ // У товара нет коэффициента -- создаем новый $result = \Bitrix\Catalog\MeasureRatioTable::add([ 'PRODUCT_ID' => $productId, @@ -366,7 +381,8 @@ if ($ratioRow) { } // Проверяем результат -if (!$result->isSuccess()) { +if (!$result->isSuccess()) +{ throw new \RuntimeException(implode('; ', $result->getErrorMessages())); } ``` diff --git a/pages/modules/catalog/export-import.md b/pages/modules/catalog/export-import.md index d252743..32dae40 100644 --- a/pages/modules/catalog/export-import.md +++ b/pages/modules/catalog/export-import.md @@ -67,19 +67,29 @@ $productIblockId = (int)$IBLOCK_ID; $exportFile = (string)$SETUP_FILE_NAME; $allowedDirectory = '/upload/export/'; -if ($productIblockId <= 0) { +if ($productIblockId <= 0) +{ $strExportErrorMessage = 'Не выбран инфоблок каталога'; -} elseif ($exportFile === '') { +} +elseif ($exportFile === '') +{ $strExportErrorMessage = 'Не указан файл экспорта'; -} elseif (strncmp($exportFile, $allowedDirectory, strlen($allowedDirectory)) !== 0) { +} +elseif (strncmp($exportFile, $allowedDirectory, strlen($allowedDirectory)) !== 0) +{ $strExportErrorMessage = 'Файл экспорта должен находиться в /upload/export/'; -} else { +} +else +{ $filePath = $_SERVER['DOCUMENT_ROOT'] . $exportFile; $file = fopen($filePath, 'wb'); - if (!$file) { + if (!$file) + { $strExportErrorMessage = 'Не удалось открыть файл экспорта'; - } else { + } + else + { fputcsv($file, ['ID', 'XML_ID', 'NAME'], ';'); $elementsIterator = \CIBlockElement::GetList( @@ -93,7 +103,8 @@ if ($productIblockId <= 0) { ['ID', 'XML_ID', 'NAME'] ); - while ($element = $elementsIterator->Fetch()) { + while ($element = $elementsIterator->Fetch()) + { fputcsv( $file, [ @@ -133,29 +144,37 @@ if ($productIblockId <= 0) { ```php $errorMessage = ''; -if ($STEP > 1) { +if ($STEP > 1) +{ $IBLOCK_ID = (int)$IBLOCK_ID; - if ($IBLOCK_ID <= 0) { + if ($IBLOCK_ID <= 0) + { $errorMessage .= 'Инфоблок не выбран.
'; } - if ((string)$SETUP_FILE_NAME === '') { + if ((string)$SETUP_FILE_NAME === '') + { $errorMessage .= 'Не указан файл данных.
'; } - if ($ACTION === 'EXPORT_SETUP' && (string)$SETUP_PROFILE_NAME === '') { + if ($ACTION === 'EXPORT_SETUP' && (string)$SETUP_PROFILE_NAME === '') + { $errorMessage .= 'Не указано имя профиля.
'; } - if ($errorMessage !== '') { + if ($errorMessage !== '') + { $STEP = 1; } } -if ((int)$STEP === 1) { +if ((int)$STEP === 1) +{ $SETUP_FIELDS_LIST = 'IBLOCK_ID,SETUP_FILE_NAME'; -} elseif ((int)$STEP === 2) { +} +elseif ((int)$STEP === 2) +{ $FINITE = true; } ``` @@ -201,7 +220,8 @@ $exportProfileId = \CCatalogExport::Add([ 'SETUP_VARS' => $setupVars, ]); -if (!$exportProfileId) { +if (!$exportProfileId) +{ throw new \RuntimeException('Не удалось создать профиль экспорта'); } ``` @@ -217,7 +237,8 @@ if (!$exportProfileId) { ```php $agentCall = \CCatalogExport::PreGenerateExport($exportProfileId); -if ($agentCall === false) { +if ($agentCall === false) +{ throw new \RuntimeException('Не удалось запустить экспорт по профилю'); } ``` @@ -236,7 +257,8 @@ $profilesIterator = \CCatalogExport::GetList( ['IN_MENU' => 'Y'] ); -while ($profile = $profilesIterator->Fetch()) { +while ($profile = $profilesIterator->Fetch()) +{ echo $profile['ID'] . ': ' . $profile['NAME'] . "\n"; } @@ -268,7 +290,8 @@ $updatedExportProfileId = \CCatalogExport::Update($exportProfileId, [ ]), ]); -if (!$updatedExportProfileId) { +if (!$updatedExportProfileId) +{ throw new \RuntimeException('Не удалось обновить профиль экспорта'); } @@ -302,30 +325,44 @@ $productIblockId = (int)$IBLOCK_ID; $dataFile = (string)$URL_DATA_FILE; $allowedDirectory = '/upload/import/'; -if ($productIblockId <= 0) { +if ($productIblockId <= 0) +{ $strImportErrorMessage = 'Не выбран инфоблок каталога'; -} elseif ($dataFile === '') { +} +elseif ($dataFile === '') +{ $strImportErrorMessage = 'Не указан файл импорта'; -} elseif (strncmp($dataFile, $allowedDirectory, strlen($allowedDirectory)) !== 0) { +} +elseif (strncmp($dataFile, $allowedDirectory, strlen($allowedDirectory)) !== 0) +{ $strImportErrorMessage = 'Файл импорта должен находиться в /upload/import/'; -} elseif (!is_readable($_SERVER['DOCUMENT_ROOT'] . $dataFile)) { +} +elseif (!is_readable($_SERVER['DOCUMENT_ROOT'] . $dataFile)) +{ $strImportErrorMessage = 'Файл импорта недоступен для чтения'; -} else { +} +else +{ $file = fopen($_SERVER['DOCUMENT_ROOT'] . $dataFile, 'rb'); $element = new \CIBlockElement; - if (!$file) { + if (!$file) + { $strImportErrorMessage = 'Не удалось открыть файл импорта'; - } else { + } + else + { fgetcsv($file, 0, ';'); // пропускаем строку заголовков - while (($row = fgetcsv($file, 0, ';')) !== false) { + while (($row = fgetcsv($file, 0, ';')) !== false) + { [$xmlId, $name] = array_pad($row, 2, ''); $xmlId = trim((string)$xmlId); $name = trim((string)$name); - if ($xmlId === '' || $name === '') { + if ($xmlId === '' || $name === '') + { $strImportErrorMessage = 'В файле импорта есть строка без XML_ID или названия'; break; } @@ -341,11 +378,14 @@ if ($productIblockId <= 0) { ['ID'] )->Fetch(); - if ($elementRow) { + if ($elementRow) + { $result = $element->Update((int)$elementRow['ID'], [ 'NAME' => $name, ]); - } else { + } + else + { $result = $element->Add([ 'IBLOCK_ID' => $productIblockId, 'XML_ID' => $xmlId, @@ -354,7 +394,8 @@ if ($productIblockId <= 0) { ]); } - if (!$result) { + if (!$result) + { $strImportErrorMessage = $element->LAST_ERROR ?: 'Не удалось сохранить элемент каталога'; break; } @@ -388,29 +429,37 @@ if ($productIblockId <= 0) { ```php $errorMessage = ''; -if ($STEP > 1) { +if ($STEP > 1) +{ $IBLOCK_ID = (int)$IBLOCK_ID; - if ($IBLOCK_ID <= 0) { + if ($IBLOCK_ID <= 0) + { $errorMessage .= 'Инфоблок не выбран.
'; } - if ((string)$URL_DATA_FILE === '') { + if ((string)$URL_DATA_FILE === '') + { $errorMessage .= 'Не указан файл импорта.
'; } - if ($ACTION === 'IMPORT_SETUP' && (string)$SETUP_PROFILE_NAME === '') { + if ($ACTION === 'IMPORT_SETUP' && (string)$SETUP_PROFILE_NAME === '') + { $errorMessage .= 'Не указано имя профиля.
'; } - if ($errorMessage !== '') { + if ($errorMessage !== '') + { $STEP = 1; } } -if ((int)$STEP === 1) { +if ((int)$STEP === 1) +{ $SETUP_FIELDS_LIST = 'IBLOCK_ID,URL_DATA_FILE'; -} elseif ((int)$STEP === 2) { +} +elseif ((int)$STEP === 2) +{ $FINITE = true; } ``` @@ -436,7 +485,8 @@ $importProfileId = \CCatalogImport::Add([ ]), ]); -if (!$importProfileId) { +if (!$importProfileId) +{ throw new \RuntimeException('Не удалось создать профиль импорта'); } ``` @@ -452,7 +502,8 @@ if (!$importProfileId) { ```php $agentCall = \CCatalogImport::PreGenerateImport($importProfileId); -if ($agentCall === false) { +if ($agentCall === false) +{ throw new \RuntimeException('Не удалось запустить импорт по профилю'); } ``` @@ -471,7 +522,8 @@ $profilesIterator = \CCatalogImport::GetList( ['FILE_NAME' => 'furniture_csv'] ); -while ($profile = $profilesIterator->Fetch()) { +while ($profile = $profilesIterator->Fetch()) +{ echo $profile['ID'] . ': ' . $profile['NAME'] . "\n"; } @@ -481,7 +533,8 @@ $updatedImportProfileId = \CCatalogImport::Update($importProfileId, [ 'NAME' => 'Импорт мебели из CSV по расписанию', ]); -if (!$updatedImportProfileId) { +if (!$updatedImportProfileId) +{ throw new \RuntimeException('Не удалось обновить профиль импорта'); } @@ -531,13 +584,15 @@ if (!$updatedImportProfileId) { ```php $profile = \CCatalogExport::GetByID($exportProfileId); -if (!$profile) { +if (!$profile) +{ throw new \RuntimeException('Профиль экспорта не найден'); } $exportFile = '/upload/export/furniture.csv'; -if (!is_readable($_SERVER['DOCUMENT_ROOT'] . $exportFile)) { +if (!is_readable($_SERVER['DOCUMENT_ROOT'] . $exportFile)) +{ throw new \RuntimeException('Файл экспорта не найден'); } ``` diff --git a/pages/modules/catalog/inventory-management.md b/pages/modules/catalog/inventory-management.md index a44c168..4bfc021 100644 --- a/pages/modules/catalog/inventory-management.md +++ b/pages/modules/catalog/inventory-management.md @@ -10,7 +10,8 @@ description: 'Складской учет. Модуль Торговый кат Перед выполнением примеров подключите модуль `catalog` и проверьте права пользователя на изменение данных каталога и складских документов. ```php -if (!\Bitrix\Main\Loader::includeModule('catalog')) { +if (!\Bitrix\Main\Loader::includeModule('catalog')) +{ throw new \RuntimeException('Не удалось подключить модуль catalog'); } ``` @@ -70,7 +71,8 @@ $storeId = \CCatalogStore::Add([ 'SORT' => 100, ]); -if (!$storeId) { +if (!$storeId) +{ global $APPLICATION; $exception = $APPLICATION->GetException(); $message = $exception ? $exception->GetString() : 'Не удалось создать склад'; @@ -166,7 +168,8 @@ $contractorId = \CCatalogContractor::add([ 'KPP' => '770001001', ]); -if (!$contractorId) { +if (!$contractorId) +{ global $APPLICATION; $exception = $APPLICATION->GetException(); $message = $exception ? $exception->GetString() : 'Не удалось создать поставщика-юрлицо'; @@ -195,7 +198,8 @@ $contractorId = \CCatalogContractor::add([ 'INN' => '390000000000', ]); -if (!$contractorId) { +if (!$contractorId) +{ global $APPLICATION; $exception = $APPLICATION->GetException(); $message = $exception ? $exception->GetString() : 'Не удалось создать поставщика-физлицо'; @@ -244,7 +248,8 @@ $storeProductId = \CCatalogStoreProduct::Add([ 'AMOUNT' => 12, ]); -if (!$storeProductId) { +if (!$storeProductId) +{ global $APPLICATION; $exception = $APPLICATION->GetException(); $message = $exception ? $exception->GetString() : 'Не удалось записать остаток на складе'; @@ -264,7 +269,8 @@ $storeProductResult = \CCatalogStoreProduct::UpdateFromForm([ 'AMOUNT' => 15, // числовое значение остатка ]); -if (!$storeProductResult) { +if (!$storeProductResult) +{ global $APPLICATION; $exception = $APPLICATION->GetException(); $message = $exception ? $exception->GetString() : 'Не удалось обновить остаток на складе'; @@ -293,7 +299,8 @@ $barcodeResult = \Bitrix\Catalog\StoreBarcodeTable::add([ 'CREATED_BY' => $responsibleUserId, ]); -if (!$barcodeResult->isSuccess()) { +if (!$barcodeResult->isSuccess()) +{ throw new \RuntimeException(implode('; ', $barcodeResult->getErrorMessages())); } @@ -315,11 +322,13 @@ $barcodeRow = \Bitrix\Catalog\StoreBarcodeTable::getList([ 'limit' => 1, ])->fetch(); -if (!$barcodeRow) { +if (!$barcodeRow) +{ throw new \RuntimeException('Штрихкод не найден'); } -if ((int)$barcodeRow['PRODUCT_ID'] !== $productId) { +if ((int)$barcodeRow['PRODUCT_ID'] !== $productId) +{ throw new \RuntimeException('Штрихкод относится к другому товару'); } ``` @@ -449,7 +458,8 @@ $documentId = \CCatalogDocs::add([ ], ]); -if (!$documentId) { +if (!$documentId) +{ global $APPLICATION; $exception = $APPLICATION->GetException(); $message = $exception ? $exception->GetString() : 'Не удалось создать документ'; @@ -603,7 +613,8 @@ $documentRows = \Bitrix\Catalog\StoreDocumentElementTable::getList([ ```php $conducted = \CCatalogDocs::conductDocument($documentId, $responsibleUserId); -if (!$conducted) { +if (!$conducted) +{ global $APPLICATION; $exception = $APPLICATION->GetException(); $message = $exception ? $exception->GetString() : 'Не удалось провести документ'; @@ -623,7 +634,8 @@ if (!$conducted) { ```php $cancelled = \CCatalogDocs::cancellationDocument($documentId, $responsibleUserId); -if (!$cancelled) { +if (!$cancelled) +{ global $APPLICATION; $exception = $APPLICATION->GetException(); $message = $exception ? $exception->GetString() : 'Не удалось отменить проведение документа'; @@ -657,7 +669,8 @@ $storeRows = \Bitrix\Catalog\StoreProductTable::getList([ ], ])->fetchAll(); -foreach ($storeRows as $row) { +foreach ($storeRows as $row) +{ echo $row['STORE_TITLE'] . ': ' . $row['AMOUNT'] . "\n"; } ``` @@ -722,7 +735,8 @@ $storeProductRow = \Bitrix\Catalog\StoreProductTable::getList([ 'limit' => 1, ])->fetch(); -if (!$storeProductRow) { +if (!$storeProductRow) +{ throw new \RuntimeException('Остаток товара на складе не найден'); } @@ -800,7 +814,8 @@ $documentRows = \Bitrix\Catalog\StoreDocumentElementTable::getList([ $documentElementIds = array_column($documentRows, 'ID'); $batchRows = []; -if (!empty($documentElementIds)) { +if (!empty($documentElementIds)) +{ $batchRows = \Bitrix\Catalog\StoreBatchDocumentElementTable::getList([ 'select' => [ 'PRODUCT_BATCH_ID', diff --git a/pages/modules/catalog/overview.md b/pages/modules/catalog/overview.md index 945ffa9..474e73e 100644 --- a/pages/modules/catalog/overview.md +++ b/pages/modules/catalog/overview.md @@ -153,14 +153,16 @@ $catalogCreated = \CCatalog::Add([ 'SKU_PROPERTY_ID' => 0, ]); -if (!$catalogCreated) { +if (!$catalogCreated) +{ throw new \RuntimeException('Не удалось создать торговый каталог'); } // Получить базовый тип цены для добавления цены товара $basePriceType = \Bitrix\Catalog\GroupTable::getBasePriceType(); -if (!$basePriceType) { +if (!$basePriceType) +{ throw new \RuntimeException('Базовый тип цен не найден'); } @@ -177,7 +179,8 @@ $productResult = \Bitrix\Catalog\Model\Product::add([ ]); // Проверить результат создания товара -if (!$productResult->isSuccess()) { +if (!$productResult->isSuccess()) +{ throw new \RuntimeException(implode('; ', $productResult->getErrorMessages())); } @@ -190,7 +193,8 @@ $priceResult = \Bitrix\Catalog\Model\Price::add([ ]); // Проверить результат создания цены -if (!$priceResult->isSuccess()) { +if (!$priceResult->isSuccess()) +{ throw new \RuntimeException(implode('; ', $priceResult->getErrorMessages())); } ``` diff --git a/pages/modules/catalog/performance.md b/pages/modules/catalog/performance.md index 72712ba..6ee7e3b 100644 --- a/pages/modules/catalog/performance.md +++ b/pages/modules/catalog/performance.md @@ -39,7 +39,8 @@ description: 'Производительность и частые ошибки. Неверный подход: ```php -foreach ($productIds as $productId) { +foreach ($productIds as $productId) +{ $price = \Bitrix\Catalog\PriceTable::getList([ 'select' => ['PRICE', 'CURRENCY'], 'filter' => ['=PRODUCT_ID' => $productId], @@ -68,7 +69,8 @@ $priceIterator = \Bitrix\Catalog\PriceTable::getList([ ], ]); -while ($price = $priceIterator->fetch()) { +while ($price = $priceIterator->fetch()) +{ $priceMap[(int)$price['PRODUCT_ID']] = $price; } ``` @@ -231,7 +233,8 @@ $result = \Bitrix\Catalog\Model\Price::update($priceId, [ 'CURRENCY' => 'RUB', ]); -if (!$result->isSuccess()) { +if (!$result->isSuccess()) +{ throw new \RuntimeException(implode('; ', $result->getErrorMessages())); } ``` @@ -259,7 +262,8 @@ $result = \Bitrix\Catalog\Model\Price::recountPricesFromBase([ 'PRODUCT_ID' => $productId, ]); -if (!$result->isSuccess()) { +if (!$result->isSuccess()) +{ throw new \RuntimeException(implode('; ', $result->getErrorMessages())); } ``` @@ -321,11 +325,13 @@ $iterator = \CIBlockElement::GetList( Подключайте модули `iblock` и `catalog` до обращения к таблицам каталога: ```php -if (!\Bitrix\Main\Loader::includeModule('iblock')) { +if (!\Bitrix\Main\Loader::includeModule('iblock')) +{ throw new \Bitrix\Main\SystemException('Модуль iblock не установлен.'); } -if (!\Bitrix\Main\Loader::includeModule('catalog')) { +if (!\Bitrix\Main\Loader::includeModule('catalog')) +{ throw new \Bitrix\Main\SystemException('Модуль catalog не установлен.'); } ``` @@ -347,7 +353,8 @@ $result = \Bitrix\Catalog\Model\Product::add([ 'QUANTITY' => 100, ]); -if (!$result->isSuccess()) { +if (!$result->isSuccess()) +{ throw new \RuntimeException(implode('; ', $result->getErrorMessages())); } ``` @@ -380,7 +387,8 @@ if (!$result->isSuccess()) { $limit = 500; $offset = 0; -do { +do +{ $rows = \Bitrix\Catalog\ProductTable::getList([ 'select' => ['ID', 'QUANTITY', 'TYPE'], 'order' => ['ID' => 'ASC'], @@ -388,12 +396,14 @@ do { 'offset' => $offset, ])->fetchAll(); - foreach ($rows as $row) { + foreach ($rows as $row) + { // Обработать товар } $offset += $limit; -} while (!empty($rows)); +} +while (!empty($rows)); ``` ### Неверная передача параметров в GetOptimalPriceList @@ -412,7 +422,8 @@ do { $currentPage = (int)($_GET['PAGEN_1'] ?? 1); $pageCount = (int)$arResult['NAV_RESULT']->NavPageCount; -if ($currentPage > $pageCount) { +if ($currentPage > $pageCount) +{ \CHTTP::SetStatus('404 Not Found'); require $_SERVER['DOCUMENT_ROOT'] . '/404.php'; exit; @@ -426,7 +437,8 @@ if ($currentPage > $pageCount) { ```php $catalogInfo = \CCatalogSKU::getInfoByIBlock($iblockId); -if (!$catalogInfo) { +if (!$catalogInfo) +{ return; } diff --git a/pages/modules/catalog/products-and-offers.md b/pages/modules/catalog/products-and-offers.md index 062ded1..822544c 100644 --- a/pages/modules/catalog/products-and-offers.md +++ b/pages/modules/catalog/products-and-offers.md @@ -42,7 +42,8 @@ $productIblockId = $iblock->Add([ 'LID' => ['s1'], ]); -if (!$productIblockId) { +if (!$productIblockId) +{ throw new \RuntimeException($iblock->getLastError()->getMessage()); } ``` @@ -77,7 +78,8 @@ $result = \CCatalog::Add([ 'SKU_PROPERTY_ID' => 0, ]); -if (!$result) { +if (!$result) +{ throw new \RuntimeException('Не удалось создать торговый каталог'); } ``` @@ -115,7 +117,8 @@ $productId = $element->Add([ 'ACTIVE' => 'Y', ]); -if (!$productId) { +if (!$productId) +{ throw new \RuntimeException($element->LAST_ERROR); } @@ -128,7 +131,8 @@ $result = \Bitrix\Catalog\Model\Product::add([ 'SUBSCRIBE' => 'Y', ]); -if (!$result->isSuccess()) { +if (!$result->isSuccess()) +{ throw new \RuntimeException(implode('; ', $result->getErrorMessages())); } ``` @@ -163,7 +167,8 @@ $result = \Bitrix\Catalog\Model\Price::add([ 'CURRENCY' => 'RUB', ]); -if (!$result->isSuccess()) { +if (!$result->isSuccess()) +{ throw new \RuntimeException(implode('; ', $result->getErrorMessages())); } ``` @@ -195,7 +200,8 @@ $serviceId = $element->Add([ 'ACTIVE' => 'Y', ]); -if (!$serviceId) { +if (!$serviceId) +{ throw new \RuntimeException($element->LAST_ERROR); } @@ -204,7 +210,8 @@ $productResult = \Bitrix\Catalog\Model\Product::add([ 'TYPE' => \Bitrix\Catalog\ProductTable::TYPE_SERVICE, ]); -if (!$productResult->isSuccess()) { +if (!$productResult->isSuccess()) +{ throw new \RuntimeException(implode('; ', $productResult->getErrorMessages())); } @@ -215,7 +222,8 @@ $priceResult = \Bitrix\Catalog\Model\Price::add([ 'CURRENCY' => 'RUB', ]); -if (!$priceResult->isSuccess()) { +if (!$priceResult->isSuccess()) +{ throw new \RuntimeException(implode('; ', $priceResult->getErrorMessages())); } ``` @@ -268,7 +276,8 @@ $productIblockId = $iblock->Add([ 'LID' => ['s1'], // массив кодов сайтов для привязки ]); -if (!$productIblockId) { +if (!$productIblockId) +{ throw new \RuntimeException($iblock->getLastError()->getMessage()); } @@ -281,7 +290,8 @@ $offerIblockId = $iblock->Add([ 'LID' => ['s1'], ]); -if (!$offerIblockId) { +if (!$offerIblockId) +{ throw new \RuntimeException($iblock->getLastError()->getMessage()); } ``` @@ -320,7 +330,8 @@ $skuPropertyId = $property->Add([ 'MULTIPLE' => 'N', ]); -if (!$skuPropertyId) { +if (!$skuPropertyId) +{ throw new \RuntimeException($property->LAST_ERROR); } ``` @@ -353,7 +364,8 @@ $productCatalogCreated = \CCatalog::Add([ 'SKU_PROPERTY_ID' => 0, ]); -if (!$productCatalogCreated) { +if (!$productCatalogCreated) +{ throw new \RuntimeException('Не удалось создать каталог товаров'); } @@ -366,7 +378,8 @@ $offerCatalogCreated = \CCatalog::Add([ 'SKU_PROPERTY_ID' => $skuPropertyId, ]); -if (!$offerCatalogCreated) { +if (!$offerCatalogCreated) +{ throw new \RuntimeException('Не удалось создать каталог торговых предложений'); } ``` @@ -386,7 +399,8 @@ $productId = $element->Add([ 'ACTIVE' => 'Y', ]); -if (!$productId) { +if (!$productId) +{ throw new \RuntimeException($element->LAST_ERROR); } @@ -395,7 +409,8 @@ $result = \Bitrix\Catalog\Model\Product::add([ 'TYPE' => \Bitrix\Catalog\ProductTable::TYPE_SKU, ]); -if (!$result->isSuccess()) { +if (!$result->isSuccess()) +{ throw new \RuntimeException(implode('; ', $result->getErrorMessages())); } ``` @@ -428,7 +443,8 @@ $offerId = $element->Add([ ], ]); -if (!$offerId) { +if (!$offerId) +{ throw new \RuntimeException($element->LAST_ERROR); } @@ -441,7 +457,8 @@ $result = \Bitrix\Catalog\Model\Product::add([ 'SUBSCRIBE' => 'Y', ]); -if (!$result->isSuccess()) { +if (!$result->isSuccess()) +{ throw new \RuntimeException(implode('; ', $result->getErrorMessages())); } ``` @@ -464,7 +481,8 @@ $result = \Bitrix\Catalog\Model\Price::add([ 'CURRENCY' => 'RUB', ]); -if (!$result->isSuccess()) { +if (!$result->isSuccess()) +{ throw new \RuntimeException(implode('; ', $result->getErrorMessages())); } ``` @@ -503,7 +521,8 @@ $offers = $offersByProduct[$productId] ?? []; ```php $skuInfo = \CCatalogSKU::GetInfoByProductIBlock($productIblockId); -if (!$skuInfo) { +if (!$skuInfo) +{ throw new \RuntimeException('Инфоблок не связан с торговыми предложениями'); } @@ -519,7 +538,8 @@ $offersIterator = \CIBlockElement::GetList( ['ID', 'NAME'] ); -while ($offer = $offersIterator->Fetch()) { +while ($offer = $offersIterator->Fetch()) +{ echo $offer['ID'] . ': ' . $offer['NAME'] . "\n"; } ``` @@ -556,7 +576,8 @@ $updated = $element->Update($productId, [ 'ACTIVE' => 'Y', ]); -if (!$updated) { +if (!$updated) +{ throw new \RuntimeException($element->LAST_ERROR); } ``` @@ -574,7 +595,8 @@ $result = \Bitrix\Catalog\Model\Product::update($productId, [ 'SUBSCRIBE' => 'Y', ]); -if (!$result->isSuccess()) { +if (!$result->isSuccess()) +{ throw new \RuntimeException(implode('; ', $result->getErrorMessages())); } ``` @@ -604,7 +626,8 @@ if (!$result->isSuccess()) { Для простого товара без предложений используйте `CIBlockElement::Delete()`. В метод передайте идентификатор элемента инфоблока. ```php -if (!\CIBlockElement::Delete($productId)) { +if (!\CIBlockElement::Delete($productId)) +{ global $APPLICATION; $exception = $APPLICATION->GetException(); $message = $exception ? $exception->GetString() : 'Не удалось удалить товар'; @@ -635,8 +658,10 @@ $offersByProduct = \CCatalogSKU::getOffersList( $offers = $offersByProduct[$productId] ?? []; -foreach ($offers as $offer) { - if (!\CIBlockElement::Delete((int)$offer['ID'])) { +foreach ($offers as $offer) +{ + if (!\CIBlockElement::Delete((int)$offer['ID'])) + { global $APPLICATION; $exception = $APPLICATION->GetException(); $message = $exception ? $exception->GetString() : 'Не удалось удалить торговое предложение'; @@ -645,7 +670,8 @@ foreach ($offers as $offer) { } } -if (!\CIBlockElement::Delete($productId)) { +if (!\CIBlockElement::Delete($productId)) +{ global $APPLICATION; $exception = $APPLICATION->GetException(); $message = $exception ? $exception->GetString() : 'Не удалось удалить родительский товар'; diff --git a/pages/modules/iblocks/api.md b/pages/modules/iblocks/api.md index 9025b99..4762454 100644 --- a/pages/modules/iblocks/api.md +++ b/pages/modules/iblocks/api.md @@ -59,7 +59,8 @@ $result = $iblockType->Add([ ], ]); -if (!$result) { +if (!$result) +{ throw new \Exception($iblockType->getLastError()->getMessage()); } ``` @@ -106,7 +107,8 @@ $result = $iblock->Add([ ], ]); -if (!$result) { +if (!$result) +{ throw new \Exception($iblock->getLastError()->getMessage()); } @@ -183,7 +185,8 @@ $result = $authorProp->Add([ 'MULTIPLE' => 'N', // одно значение ]); -if (!$result) { +if (!$result) +{ throw new \Exception($authorProp->getLastError()->getMessage()); } @@ -198,7 +201,8 @@ $result = $tagsProp->Add([ 'MULTIPLE' => 'Y', // несколько значений ]); -if (!$result) { +if (!$result) +{ throw new \Exception($tagsProp->getLastError()->getMessage()); } ``` @@ -246,7 +250,8 @@ $result = $property->Add([ 'MULTIPLE' => 'N', ]); -if (!$result) { +if (!$result) +{ throw new \Exception($property->getLastError()->getMessage()); } @@ -293,7 +298,8 @@ $result = $property->Add([ 'MULTIPLE' => 'N', ]); -if (!$result) { +if (!$result) +{ throw new \Exception($property->getLastError()->getMessage()); } ``` @@ -332,7 +338,8 @@ $result = $property->Add([ ], ]); -if (!$result) { +if (!$result) +{ throw new \Exception($property->getLastError()->getMessage()); } ``` @@ -391,7 +398,8 @@ $section = $sectionNewsClass::createObject() ->setName('Мероприятия') ->setCode('events') ->setActive(true) - ->save(); + ->save() +; $eventsSectionId = $section->getId(); ``` @@ -406,8 +414,10 @@ $section = $sectionNewsClass::query() ->setSelect(['NAME', 'ACTIVE']) ->where('CODE', 'events') ->setLimit(1) - ->fetchObject(); -if ($section) { + ->fetchObject() +; +if ($section) +{ echo "Раздел: " . $section->getName(); // Мероприятия echo "Активен: " . ($section->getActive() ? 'да' : 'нет'); } @@ -425,9 +435,11 @@ $parentSection = $sectionNewsClass::query() ->setSelect(['ID']) ->where('CODE', 'events') ->setLimit(1) - ->fetchObject(); + ->fetchObject() +; -if ($parentSection) { +if ($parentSection) +{ // создаем вложенный раздел Выставки $exhibitionSection = $sectionNewsClass::createObject() ->setIblockId($iblockId) @@ -435,7 +447,8 @@ if ($parentSection) { ->setCode('exhibitions') ->setIblockSectionId($parentSection->getId()) // привязка к родителю ->setActive(true) - ->save(); + ->save() + ; $exhibitionSectionId = $exhibitionSection->getId(); } @@ -451,8 +464,11 @@ $sections = $sectionNewsClass::query() ->where('ACTIVE', 'Y') ->setOrder(['NAME' => 'ASC']) ->setLimit(10) - ->fetchCollection(); -foreach ($sections as $item) { + ->fetchCollection() +; + +foreach ($sections as $item) +{ echo $item->getName() . "\n"; } ``` @@ -471,11 +487,14 @@ $exhibitionSection = $sectionNewsClass::query() ]) ->where('CODE', 'exhibitions') ->setLimit(1) - ->fetchObject(); + ->fetchObject() +; -if ($exhibitionSection) { +if ($exhibitionSection) +{ $parent = $exhibitionSection->getParentSection(); // метод возвращает объект родителя - if ($parent) { + if ($parent) + { echo "Родительский раздел: " . $parent->getName(); // Мероприятия } } @@ -500,17 +519,22 @@ if ($exhibitionSection) { $exhibitionSection = $sectionNewsClass::query() ->where('CODE', 'exhibitions') ->setLimit(1) - ->fetchObject(); + ->fetchObject() +; -if ($exhibitionSection) { +if ($exhibitionSection) +{ $exhibitionSection ->setName('Выставки 2025-2026') // изменим название раздела - ->setActive(false); // и деактивируем его + ->setActive(false) // и деактивируем его + ; $result = $exhibitionSection->save(); - if (!$result->isSuccess()) { - foreach ($result->getErrors() as $error) { + if (!$result->isSuccess()) + { + foreach ($result->getErrors() as $error) + { echo $error->getMessage() . "\n"; } } @@ -536,7 +560,8 @@ $conferenceSection = $sectionNewsClass::createObject() ->setCode('conferences') ->set('UF_MANAGER', 'Ирина Сидорова') // ← значение UF-поля ->setActive(true) - ->save(); + ->save() +; ``` ### Получить пользовательские поля раздела @@ -548,9 +573,11 @@ $conferenceSection = $sectionNewsClass::query() ->setSelect(['ID', 'NAME', 'UF_*']) // загружаем все UF-поля ->where('CODE', 'conferences') ->setLimit(1) - ->fetchObject(); + ->fetchObject() +; -if ($conferenceSection) { +if ($conferenceSection) +{ $manager = $conferenceSection->get('UF_MANAGER'); // строка echo "Ответственный: " . $manager; // Ирина Сидорова } @@ -584,9 +611,11 @@ ORM-метод `$section->delete()` применяйте для специфич $conferenceSection = $sectionNewsClass::query() ->where('CODE', 'conferences') ->setLimit(1) - ->fetchObject(); + ->fetchObject() +; -if ($conferenceSection) { +if ($conferenceSection) +{ $conferenceSection->delete(); // элементы останутся в базе, но исчезнут из дерева } ``` @@ -638,12 +667,15 @@ $element = $elementNewsClass::createObject() ->setName('Обновление системы безопасности') ->setCode('security-update') ->setActive(true) - ->set('AUTHOR', 'Ирина Петрова'); + ->set('AUTHOR', 'Ирина Петрова') +; $result = $element->save(); -if (!$result->isSuccess()) { - foreach ($result->getErrors() as $error) { +if (!$result->isSuccess()) +{ + foreach ($result->getErrors() as $error) + { echo $error->getMessage() . "\n"; } return; @@ -670,15 +702,18 @@ $parentSection = $sectionNewsClass::query() ->setSelect(['ID']) ->where('CODE', 'events') ->setLimit(1) - ->fetchObject(); + ->fetchObject() +; -if ($parentSection) { +if ($parentSection) +{ $element = $elementNewsClass::createObject() ->setName('Конференция по кибербезопасности') ->setCode('cybersec-conf-2026') ->setActive(true) ->setIblockSectionId($parentSection->getId()) // привязка к разделу - ->set('AUTHOR', 'Иван Сидоров'); + ->set('AUTHOR', 'Иван Сидоров') + ; $element->save(); } @@ -707,7 +742,8 @@ $element = $elementNewsClass::createObject() ->setName('Новость с автором и источником') ->setCode('news-author-source') ->set('AUTHOR', 'Светлана Пирогова') // строка — текст напрямую - ->set('SOURCE', 1); // список — идентификатор значения «РИА Новости» + ->set('SOURCE', 1) // список — идентификатор значения «РИА Новости» +; $element->save(); ``` @@ -722,7 +758,8 @@ $element = $elementNewsClass::createObject() ->setCode('news-tags') ->addTo('TAGS', 'безопасность') ->addTo('TAGS', 'обновление') - ->addTo('TAGS', '2026'); + ->addTo('TAGS', '2026') +; $element->save(); ``` @@ -778,7 +815,8 @@ $element = $elementNewsClass::createObject() ->setName('Новость с изображениями') ->setCode('news-image') ->set('PHOTO', new PropertyValue($photoId, 'Главное фото')) - ->addTo('GALLERY', new PropertyValue($otherId, 'Дополнительный снимок')); + ->addTo('GALLERY', new PropertyValue($otherId, 'Дополнительный снимок')) +; $element->save(); ``` @@ -796,7 +834,8 @@ $element->save(); ```php $element = $elementNewsClass::createObject() ->setName('Новость с итогом') - ->set('SUMMARY', '

Вывод: система защищена от уязвимостей CVE-2026-XXXX.

'); + ->set('SUMMARY', '

Вывод: система защищена от уязвимостей CVE-2026-XXXX.

') +; $element->save(); ``` @@ -819,7 +858,8 @@ $safeHtml = \Bitrix\Main\Text\HtmlFilter::getHtmlEncoder()->encode($userInput); $element = $elementNewsClass::createObject() ->setName('Новость по кибербезопасности') ->setCode('news-cybersec') - ->set('CATEGORY', 'cybersec'); + ->set('CATEGORY', 'cybersec') +; $element->save(); ``` @@ -856,9 +896,11 @@ $element->save(); $element = $elementNewsClass::query() ->where('CODE', 'security-update') ->setLimit(1) - ->fetchObject(); + ->fetchObject() +; -if ($element) { +if ($element) +{ echo $element->getName(); // Обновление системы безопасности } ``` @@ -871,12 +913,14 @@ if ($element) { $element = $elementNewsClass::query() ->where('CODE', 'news-author-source') ->setLimit(1) - ->fetchObject(); + ->fetchObject() +; echo $element->get('AUTHOR')?->getValue(); // Светлана Пирогова $source = $element->get('SOURCE'); -if ($source) { +if ($source) +{ echo $source->getItem()->getValue(); // РИА Новости echo $source->getItem()->getXmlId(); // ria } @@ -890,9 +934,11 @@ if ($source) { $element = $elementNewsClass::query() ->where('CODE', 'news-tags') ->setLimit(1) - ->fetchObject(); + ->fetchObject() +; -foreach ($element->get('TAGS')->getAll() as $tag) { +foreach ($element->get('TAGS')->getAll() as $tag) +{ echo $tag->getValue() . "\n"; } ``` @@ -907,10 +953,12 @@ foreach ($element->get('TAGS')->getAll() as $tag) { $element = $elementNewsClass::query() ->where('CODE', 'news-image') ->setLimit(1) - ->fetchObject(); + ->fetchObject() +; $photo = $element->get('PHOTO'); -if ($photo) { +if ($photo) +{ $fileId = $photo->getValue(); // идентификатор сохраненного файла $desc = $photo->getDescription(); // описание $path = \CFile::GetPath($fileId); @@ -925,14 +973,18 @@ $element = $elementNewsClass::query() ->setSelect(['ID', 'NAME', 'GALLERY']) ->where('CODE', 'news-image') ->setLimit(1) - ->fetchObject(); + ->fetchObject() +; -if ($element) { +if ($element) +{ $gallery = $element->get('GALLERY'); - if ($gallery) { + if ($gallery) + { // коллекция PropertyValueCollection - foreach ($gallery->getAll() as $other) { + foreach ($gallery->getAll() as $other) + { $fileId = $other->getValue(); $description = $other->getDescription(); @@ -974,7 +1026,8 @@ $elements = ->fetchCollection() ; -foreach ($elements as $element) { +foreach ($elements as $element) +{ echo $element->getName() . ': ' . $element->get('SOURCE')->getValue() . "\n"; } ``` @@ -1115,13 +1168,16 @@ foreach ($elements as $element) ```php $element = $elementNewsClass::query() ->where('CODE', 'security-update') - ->fetchObject(); + ->fetchObject() +; -if ($element) { +if ($element) +{ $element ->setName('Критическое обновление') ->removeAll('TAGS') - ->addTo('TAGS', 'критическое'); + ->addTo('TAGS', 'критическое') + ; $element->save(); } @@ -1144,9 +1200,11 @@ if ($element) { ```php $element = $elementNewsClass::query() ->where('CODE', 'security-update') // символьный код элемента Обновление системы безопасности - ->fetchObject(); + ->fetchObject() +; -if ($element) { +if ($element) +{ $element->delete(); \CIBlockElement::UpdateSearch($element->getId()); } @@ -1322,9 +1380,11 @@ $news = $elementNewsClass::query() ->where('ACTIVE', 'Y') ->setOrder(['DATE_ACTIVE_FROM' => 'DESC']) ->setLimit(10) - ->fetchCollection(); + ->fetchCollection() + ; -foreach ($news as $item) { +foreach ($news as $item) +{ $arResult['NEWS'][] = [ 'ID' => $item->getId(), 'NAME' => $item->getName(), @@ -1352,9 +1412,11 @@ $element = $elementNewsClass::query() ]) ->where('CODE', $arParams['ELEMENT_CODE'] ?? '') ->setLimit(1) - ->fetchObject(); + ->fetchObject() + ; -if ($element) { +if ($element) +{ $arResult['ITEM'] = [ 'ID' => $element->getId(), 'NAME' => $element->getName(), @@ -1364,7 +1426,8 @@ if ($element) { // Фото $photo = $element->get('PHOTO'); - if ($photo) { + if ($photo) + { $arResult['ITEM']['PHOTO'] = [ 'SRC' => \CFile::GetPath($photo->getValue()), 'ALT' => $photo->getDescription(), @@ -1373,7 +1436,8 @@ if ($element) { // Раздел $section = $element->getIblockSection(); - if ($section) { + if ($section) + { $arResult['ITEM']['SECTION_NAME'] = $section->getName(); $arResult['ITEM']['SECTION_CODE'] = $section->getCode(); } @@ -1391,17 +1455,23 @@ $elements = $elementNewsClass::query() ->setSelect(['ID', 'NAME', 'DETAIL_TEXT']) ->where('ACTIVE', 'Y') ->setLimit(5) - ->fetchCollection(); + ->fetchCollection() +; -foreach ($elements as $item) { +foreach ($elements as $item) +{ $text = $item->getDetailText(); - if ($text) { + if ($text) + { $preview = strip_tags($text); $preview = mb_substr($preview, 0, 300); - if (mb_strlen($text) > mb_strlen($preview)) { + if (mb_strlen($text) > mb_strlen($preview)) + { $preview .= '…'; } - } else { + } + else + { $preview = ''; } @@ -1420,7 +1490,8 @@ foreach ($elements as $item) { $current = $elementNewsClass::query() ->setSelect(['ID', 'SOURCE']) ->where('CODE', $arParams['ELEMENT_CODE']) - ->fetchObject(); + ->fetchObject() +; if (!$current) return; @@ -1433,10 +1504,12 @@ $similar = $elementNewsClass::query() ->where('SOURCE.VALUE', $sourceId) // фильтр по идентификатору источника ->whereNot('ID', $current->getId()) ->setLimit(5) - ->fetchCollection(); + ->fetchCollection() +; $arResult['MORE_FROM_SOURCE'] = []; -foreach ($similar as $item) { +foreach ($similar as $item) +{ $arResult['MORE_FROM_SOURCE'][] = [ 'NAME' => $item->getName(), 'URL' => '/news/' . $item->getCode() . '/', // единый URL-паттерн diff --git a/pages/modules/iblocks/architecture.md b/pages/modules/iblocks/architecture.md index 3b2b597..1292efb 100644 --- a/pages/modules/iblocks/architecture.md +++ b/pages/modules/iblocks/architecture.md @@ -38,7 +38,8 @@ use Bitrix\Iblock\Elements\ElementClothesTable; $collection = ElementClothesTable::getList()->fetchCollection(); // 2. Collection: работаем с набором -foreach ($collection as $element) { +foreach ($collection as $element) +{ // 3. Object: меняем каждую запись $element->setSort(100); } @@ -124,7 +125,8 @@ $items = ElementClothesTable::query() ) ) ->setSelect(['ID', 'NAME', 'NAME_LENGTH']) - ->fetchAll(); + ->fetchAll() +; ``` В результате в выборке появится поле `NAME_LENGTH`. Оно действует только в этом запросе и не меняет карту класса. @@ -154,7 +156,8 @@ $items = ElementClothesTable::query() ```php use Bitrix\Iblock\Elements\ElementClothesTable; -if (ElementClothesTable::getEntity()->hasField('BRAND')) { +if (ElementClothesTable::getEntity()->hasField('BRAND')) +{ // Свойство BRAND доступно в карте класса } ``` diff --git a/pages/modules/iblocks/overview.md b/pages/modules/iblocks/overview.md index fab9917..5d9f767 100644 --- a/pages/modules/iblocks/overview.md +++ b/pages/modules/iblocks/overview.md @@ -141,9 +141,11 @@ $element->save(); // Получить элемент по ID $existingElement = $entityClass::getByPrimary($element->getId()) - ->fetchObject(); + ->fetchObject() +; -if ($existingElement) { +if ($existingElement) +{ // Работать со свойствами элемента $value = $existingElement->getSomeProperty(); } diff --git a/pages/modules/iblocks/performance.md b/pages/modules/iblocks/performance.md index 7439486..a7fbac6 100644 --- a/pages/modules/iblocks/performance.md +++ b/pages/modules/iblocks/performance.md @@ -73,10 +73,14 @@ description: 'Производительность и частые ошибки. function updateActiveElementsStat() { $cache = new \CPHPCache(); - if ($cache->InitCache(3600, 'active_elements_count', '/stats/')) { + if ($cache->InitCache(3600, 'active_elements_count', '/stats/')) + { $count = $cache->GetVars()['count']; - } else { - if ($cache->StartDataCache()) { + } + else + { + if ($cache->StartDataCache()) + { // Выбираем только ID и дату начала активности $iterator = \Bitrix\Iblock\ElementTable::getList([ 'select' => ['ID', 'DATE_ACTIVE_FROM'], @@ -89,7 +93,8 @@ function updateActiveElementsStat() ]); $count = 0; - while ($element = $iterator->fetch()) { + while ($element = $iterator->fetch()) + { $count++; } @@ -124,7 +129,8 @@ $taggedCache->clearByTag('iblock_id_123'); ```php $row = $result->Fetch(); -if ($row) { +if ($row) +{ $row['NAME'] = \Bitrix\Main\Text\HtmlFilter::encode($row['NAME']); } ``` @@ -213,7 +219,8 @@ CIBlockElement::GetList([], [ // query() автоматически использует %= \Bitrix\Iblock\ElementTable::query() ->where('CODE', 'news') - ->exec(); + ->exec() +; ``` ### Проанализировать SQL-запросы @@ -314,7 +321,8 @@ $res = CIBlockElement::GetList([], $filter, false, false, $arSelect); ```php $element = \Bitrix\Iblock\Elements\ElementNewsTable::createObject() ->setName('Новость') - ->set('SOURCE', 105); // 105 — ID варианта в b_iblock_property_enum + ->set('SOURCE', 105) // 105 — ID варианта в b_iblock_property_enum +; $element->save(); ``` @@ -327,7 +335,8 @@ $element->save(); $element = \Bitrix\Iblock\Elements\ElementNewsTable::createObject() ->setName('Обзор товара') // RELATED_ITEM — код свойства типа Привязка к элементу - ->set('RELATED_ITEM', 789); // 789 — ID элемента в инфоблоке Товары + ->set('RELATED_ITEM', 789) // 789 — ID элемента в инфоблоке Товары +; $element->save(); ``` @@ -336,7 +345,8 @@ $element->save(); ```php $element = \Bitrix\Iblock\Elements\ElementNewsTable::createObject() ->setName('Обзор') - ->set('RELATED_ITEM', 'product-2026'); // XML_ID из инфоблока Товары + ->set('RELATED_ITEM', 'product-2026') // XML_ID из инфоблока Товары +; $element->save(); ``` @@ -372,7 +382,8 @@ CIBlockElement::GetList( Чтобы исправить проблему, в шаблоне компонента до вывода HTML установите код 404: ```php -if (!$arResult['ELEMENT']) { +if (!$arResult['ELEMENT']) +{ \CHTTP::SetStatus('404 Not Found'); require $_SERVER['DOCUMENT_ROOT'].'/404.php'; exit; diff --git a/pages/orm/annotations.md b/pages/orm/annotations.md index 019a7df..830ca6c 100644 --- a/pages/orm/annotations.md +++ b/pages/orm/annotations.md @@ -33,7 +33,8 @@ namespace Bitrix\Main { * @method mixed get($fieldName) * ... */ - class EO_User extends \Bitrix\Main\ORM\Objectify\EntityObject { + class EO_User extends \Bitrix\Main\ORM\Objectify\EntityObject + { /* @var \Bitrix\Main\UserTable */ static public $dataClass = '\Bitrix\Main\UserTable'; /** diff --git a/pages/orm/collections.md b/pages/orm/collections.md index 08314ae..968cb8d 100644 --- a/pages/orm/collections.md +++ b/pages/orm/collections.md @@ -17,7 +17,8 @@ description: 'Коллекции. ORM Bitrix Framework: ключевые кон ```php $books = \Bitrix\Main\Test\Typography\BookTable::getList() - ->fetchCollection(); + ->fetchCollection() +; ``` `$books` — это коллекция объектов класса `Book` с методами для групповых операций. @@ -69,8 +70,10 @@ class Books extends EO_Book_Collection ```php $books = \Bitrix\Main\Test\Typography\BookTable::getList() - ->fetchCollection(); -foreach ($books as $book) { + ->fetchCollection() +; +foreach ($books as $book) +{ // ... } ``` @@ -81,7 +84,8 @@ foreach ($books as $book) { ```php $books = \Bitrix\Main\Test\Typography\BookTable::getList() - ->fetchCollection(); + ->fetchCollection() +; $bookObjects = $books->getAll(); echo $bookObjects[0]->getId(); // выведет значение ID первого объекта @@ -99,13 +103,15 @@ $books = $bookCollection->collectValues(); ```php // Пример с простым первичным ключом $books = \Bitrix\Main\Test\Typography\BookTable::getList() - ->fetchCollection(); + ->fetchCollection() +; $book = $books->getByPrimary(1); // книга с ID=1 // Пример с составным первичным ключом $booksToAuthor = \Bitrix\Main\Test\Typography\BookAuthorTable::getList() - ->fetchCollection(); + ->fetchCollection() +; $bookToAuthor = $booksToAuthor->getByPrimary(['BOOK_ID' => 2, 'AUTHOR_ID' => 18]); // объект отношения книги ID=2 с автором ID=18 ``` @@ -120,7 +126,8 @@ $book2 = \Bitrix\Main\Test\Typography\Book::wakeUp(2); $books = \Bitrix\Main\Test\Typography\BookTable::query() ->addSelect('*') ->whereIn('ID', [2, 3, 4]) - ->fetchCollection(); + ->fetchCollection() +; var_dump($books->has($book1)); // false var_dump($books->has($book2)); // true @@ -132,7 +139,8 @@ var_dump($books->has($book2)); // true $books = \Bitrix\Main\Test\Typography\BookTable::query() ->addSelect('*') ->whereIn('ID', [2, 3, 4]) - ->fetchCollection(); + ->fetchCollection() +; var_dump($books->hasByPrimary(1)); // false var_dump($books->hasByPrimary(2)); // true @@ -144,7 +152,8 @@ var_dump($books->hasByPrimary(2)); // true $books = \Bitrix\Main\Test\Typography\BookTable::query() ->addSelect('*') ->whereIn('ID', [2, 3, 4]) - ->fetchCollection(); + ->fetchCollection() +; $isEmpty = $books->isEmpty(); ``` @@ -158,7 +167,8 @@ $book1 = \Bitrix\Main\Test\Typography\Book::wakeUp(1); $books = \Bitrix\Main\Test\Typography\BookTable::query() ->addSelect('*') ->whereIn('ID', [2, 3, 4]) - ->fetchCollection(); + ->fetchCollection() +; $books->add($book1); // или @@ -172,7 +182,8 @@ $books[] = $book1; ```php $book1 = \Bitrix\Main\Test\Typography\Book::wakeUp(1); $books = \Bitrix\Main\Test\Typography\BookTable::getList() - ->fetchCollection(); + ->fetchCollection() +; $books->remove($book1); // удалится книга с ID=1 $books->removeByPrimary(2); @@ -196,7 +207,8 @@ $books[] = (new Book)->setTitle('Title 112'); $books[] = (new Book)->setTitle('Title 113'); $books[] = (new Book) ->setTitle('Title 114') - ->setIsbn('114-000'); + ->setIsbn('114-000') +; $books->save(true); // INSERT INTO ... (`TITLE`, `ISBN`) VALUES @@ -217,7 +229,8 @@ use Bitrix\Main\Test\Typography\BookTable; $books = BookTable::getList()->fetchCollection(); $publisher = PublisherTable::wakeUpObject(254); -foreach ($books as $book) { +foreach ($books as $book) +{ $book->setPublisher($publisher); } $books->save(); @@ -274,9 +287,11 @@ $books->fill(\Bitrix\Main\ORM\Fields\FieldTypeMask::FLAT); ```php $books = \Bitrix\Main\Test\Typography\BookTable::getList() - ->fetchCollection(); + ->fetchCollection() +; $books->walk(static function($book) { - if ($book->getPrice() > 1000) { + if ($book->getPrice() > 1000) + { $book->setActive(false); } }); @@ -304,7 +319,8 @@ $saveResult = \Bitrix\Main\Test\Typography\BookTable::query() ```php $books = \Bitrix\Main\Test\Typography\BookTable::getList() - ->fetchCollection(); + ->fetchCollection() +; $titles = $books->getTitleList(); ``` @@ -350,11 +366,13 @@ $books = \Bitrix\Main\Test\Typography\Books::wakeUp([ ```php $books = \Bitrix\Main\Test\Typography\BookTable::getList() ->whereIn('ID', [1, 2]) - ->fetchCollection(); + ->fetchCollection() +; $anotherBooks = \Bitrix\Main\Test\Typography\BookTable::getList() ->whereIn('ID', [3, 4]) - ->fetchCollection(); + ->fetchCollection() +; $books = $books->merge($anotherBooks); ``` diff --git a/pages/orm/entity-operations.md b/pages/orm/entity-operations.md index 94c7649..ef27871 100644 --- a/pages/orm/entity-operations.md +++ b/pages/orm/entity-operations.md @@ -136,7 +136,8 @@ class BookTable extends Entity\DataManager $result = new Entity\EventResult; $data = $event->getParameter("fields"); - if (isset($data['ISBN'])) { + if (isset($data['ISBN'])) + { $cleanIsbn = str_replace('-', '', $data['ISBN']); // Удаляем дефисы из ISBN $result->modifyFields(['ISBN' => $cleanIsbn]); // Модифицируем поле ISBN } @@ -196,7 +197,8 @@ public static function onBeforeUpdate(Entity\Event $event) $result = new Entity\EventResult; $data = $event->getParameter("fields"); - if (isset($data['ISBN'])) { + if (isset($data['ISBN'])) + { $result->unsetFields(['ISBN']); // Удаляет поле ISBN из данных для обновления } @@ -212,7 +214,8 @@ public static function onBeforeUpdate(Entity\Event $event) $result = new Entity\EventResult; $data = $event->getParameter("fields"); - if (isset($data['ISBN'])) { + if (isset($data['ISBN'])) + { // Получает объект поля ISBN и выдает сообщение об ошибке $result->addError(new Entity\FieldError( $event->getEntity()->getField('ISBN'), diff --git a/pages/orm/entity-relations.md b/pages/orm/entity-relations.md index 9f8ac32..7c3dcca 100644 --- a/pages/orm/entity-relations.md +++ b/pages/orm/entity-relations.md @@ -231,7 +231,8 @@ $publisher = \Bitrix\Main\Test\Typography\PublisherTable::getByPrimary(253, [ ])->fetchObject(); // Перебор всех книг, связанных с издательством -foreach ($publisher->getBooks() as $book) { +foreach ($publisher->getBooks() as $book) +{ echo $book->getTitle(); // Вывод названия каждой книги } // Цикл выведет "Title 1" и "Title 2" @@ -278,12 +279,14 @@ Array ( ```php // Инициализация объекта издательства $publisher = \Bitrix\Main\Test\Typography\PublisherTable::getByPrimary(253) - ->fetchObject(); + ->fetchObject() +; // Метод getByPrimary загружает объект издательства с первичным ключом 253 из базы данных // Инициализация объекта книги $book = \Bitrix\Main\Test\Typography\BookTable::getByPrimary(2) - ->fetchObject(); + ->fetchObject() +; // Метод getByPrimary загружает объект книги с первичным ключом 2 из базы данных // Добавление книги в коллекцию книг издательства @@ -735,10 +738,12 @@ class ... extends \Bitrix\Main\ORM\Data\DataManager ```php $author = \Bitrix\Main\Test\Typography\AuthorTable::getByPrimary(17) - ->fetchObject(); // Получаем объект автора с ID 17 + ->fetchObject() // Получаем объект автора с ID 17 +; $book = \Bitrix\Main\Test\Typography\BookTable::getByPrimary(1) - ->fetchObject(); // Получаем объект книги с ID 1 + ->fetchObject() // Получаем объект книги с ID 1 +; $author->addToBooks($book); // Добавляем книгу к автору $author->save(); // Сохраняем изменения @@ -755,7 +760,8 @@ $book = \Bitrix\Main\Test\Typography\BookTable::getByPrimary(2, [ 'select' => ['*', 'AUTHORS'] // Выбираем все поля книги и связанных авторов ])->fetchObject(); -foreach ($book->getAuthors() as $author) { +foreach ($book->getAuthors() as $author) +{ echo $author->getLastName(); // Выводим фамилию каждого автора } // Цикл выведет "Last name 17" и "Last name 18" @@ -767,10 +773,12 @@ foreach ($book->getAuthors() as $author) { ```php $author = \Bitrix\Main\Test\Typography\AuthorTable::getByPrimary(17) - ->fetchObject(); // Получаем объект автора с ID 17 + ->fetchObject() // Получаем объект автора с ID 17 +; $book = \Bitrix\Main\Test\Typography\BookTable::getByPrimary(1) - ->fetchObject(); // Получаем объект книги с ID 1 + ->fetchObject() // Получаем объект книги с ID 1 +; $author->addToBooks($book); // Добавляем книгу к автору $author->save(); // Сохраняем изменения @@ -780,10 +788,12 @@ $author->save(); // Сохраняем изменения ```php $author = \Bitrix\Main\Test\Typography\AuthorTable::getByPrimary(17) - ->fetchObject(); // Получаем объект автора с ID 17 + ->fetchObject() // Получаем объект автора с ID 17 +; $book = \Bitrix\Main\Test\Typography\BookTable::getByPrimary(1) - ->fetchObject(); // Получаем объект книги с ID 1 + ->fetchObject() // Получаем объект книги с ID 1 +; $book->addToAuthors($author); // Добавляем автора к книге $book->save(); // Сохраняем изменения @@ -857,15 +867,18 @@ class StoreBookTable extends DataManager ```php // Объект книги $book = \Bitrix\Main\Test\Typography\BookTable::getByPrimary(1) - ->fetchObject(); + ->fetchObject() +; // Объект магазина $store = \Bitrix\Main\Test\Typography\StoreTable::getByPrimary(34) - ->fetchObject(); + ->fetchObject() +; // Новый объект связи книги с магазином $item = \Bitrix\Main\Test\Typography\StoreBookTable::createObject() ->setBook($book) ->setStore($store) - ->setQuantity(5); + ->setQuantity(5) +; // Сохранение $item->save(); ``` diff --git a/pages/orm/objects.md b/pages/orm/objects.md index 2b7b546..d21b98c 100644 --- a/pages/orm/objects.md +++ b/pages/orm/objects.md @@ -9,7 +9,8 @@ description: 'Объекты. ORM Bitrix Framework: ключевые конце ```php $book = \Bitrix\Main\Test\Typography\BookTable::getByPrimary(1) - ->fetchObject(); + ->fetchObject() +; ``` Теперь `$book` — это объект сущности `Book`, который предоставляет методы для работы с данными книги и ее связями с другими сущностями. Методы объекта можно использовать для получения и изменения данных, например, `$book->getTitle()` для получения названия книги или `$book->setTitle('New Title')` для его изменения. @@ -113,7 +114,8 @@ class Book extends EO_Book } $book = \Bitrix\Main\Test\Typography\BookTable::getByPrimary(1) - ->fetchObject(); + ->fetchObject() +; echo $book->getTitle(); // 'custom title' echo $book->get('TITLE'); // 'custom title' @@ -133,7 +135,8 @@ echo $book->get('TITLE'); // 'custom title' ```php $book = \Bitrix\Main\Test\Typography\BookTable::getByPrimary(1) - ->fetchObject(); + ->fetchObject() +; var_dump($book->getId()); // int 1 var_dump($book->getTitle()); // string 'Title 1' (length=7) ``` @@ -145,7 +148,8 @@ var_dump($book->getTitle()); // string 'Title 1' (length=7) // ->configureValues('N', 'Y'), $book = \Bitrix\Main\Test\Typography\BookTable::getByPrimary(1) - ->fetchObject(); + ->fetchObject() +; var_dump($book->getIsArchived()); // boolean true // При установке значений также ожидается boolean @@ -162,7 +166,8 @@ $book->setIsArchived(false); ```php $book = \Bitrix\Main\Test\Typography\BookTable::getByPrimary(1) - ->fetchObject(); + ->fetchObject() +; $title = $book->getTitle(); ``` @@ -172,7 +177,8 @@ $title = $book->getTitle(); ```php $book = \Bitrix\Main\Test\Typography\BookTable::getByPrimary(1) - ->fetchObject(); + ->fetchObject() +; $title = $book->requireTitle(); ``` @@ -180,7 +186,8 @@ $title = $book->requireTitle(); ```php $book = \Bitrix\Main\Test\Typography\BookTable::getByPrimary(1, ['select' => ['ID', 'PUBLISHER_ID', 'ISBN']]) - ->fetchObject(); + ->fetchObject() +; $title = $book->requireTitle(); // SystemException: "TITLE value is required for further operations" ``` @@ -191,7 +198,8 @@ $title = $book->requireTitle(); ```php $book = \Bitrix\Main\Test\Typography\BookTable::getByPrimary(1) - ->fetchObject(); + ->fetchObject() +; echo $book->getTitle(); // "Title 1" $book->setTitle("New title"); echo $book->getTitle(); // "New title" @@ -213,7 +221,8 @@ $title = $book->remindActual($fieldName); ```php $book = \Bitrix\Main\Test\Typography\BookTable::getByPrimary(1) - ->fetchObject(); + ->fetchObject() +; $primary = $book->primary; // ['ID' => 1] $id = $book->getId(); // 1 ``` @@ -224,7 +233,8 @@ $id = $book->getId(); // 1 ```php $book = \Bitrix\Main\Test\Typography\BookTable::getByPrimary(1) - ->fetchObject(); + ->fetchObject() +; $values = $book->collectValues(); ``` @@ -263,7 +273,8 @@ $author = \Bitrix\Main\Test\Typography\AuthorTable::query() ->addSelect('ID') ->addSelect('FULL_NAME') ->where('ID', 17) - ->fetchObject(); + ->fetchObject() +; echo $author->get('FULL_NAME'); // 'Name 17 Last name 17' ``` @@ -279,7 +290,8 @@ echo $author->get('FULL_NAME'); // 'Name 17 Last name 17' ```php $book = \Bitrix\Main\Test\Typography\BookTable::getByPrimary(1) - ->fetchObject(); + ->fetchObject() +; $book->setTitle("New title"); ``` @@ -300,7 +312,8 @@ $book->remindActualTitle(); // актуальное значение ```php $book = \Bitrix\Main\Test\Typography\BookTable::getByPrimary(1) - ->fetchObject(); + ->fetchObject() +; echo $book->getTitle(); // "Title 1" $book->setTitle("New title"); echo $book->getTitle(); // "New title" @@ -314,7 +327,8 @@ echo $book->getTitle(); // "Title 1" ```php $book = \Bitrix\Main\Test\Typography\BookTable::getByPrimary(1) - ->fetchObject(); + ->fetchObject() +; echo $book->getTitle(); // "Title 1" $book->unsetTitle(); echo $book->getTitle(); // null @@ -417,7 +431,8 @@ var_dump($book->state === State::DELETED); // true ```php $book = \Bitrix\Main\Test\Typography\BookTable::getByPrimary(1) - ->fetchObject(); + ->fetchObject() +; $book->setTitle("New title"); $book->save(); ``` @@ -432,7 +447,8 @@ $book->save(); ```php $book = \Bitrix\Main\Test\Typography\BookTable::getByPrimary(1) - ->fetchObject(); + ->fetchObject() +; echo $book->remindActualTitle(); // "Title 1" $book->setTitle("New title"); echo $book->remindActualTitle(); // "Title 1" @@ -482,7 +498,8 @@ echo $book->remindActualTitle(); // "New title" ```php // Удаление записи $book = \Bitrix\Main\Test\Typography\BookTable::getByPrimary(1) - ->fetchObject(); + ->fetchObject() +; $book->delete(); // Удаление по primary ключу @@ -608,10 +625,12 @@ $author->fill( ```php // Инициализация издателя $publisher = \Bitrix\Main\Test\Typography\PublisherTable::getByPrimary(253) - ->fetchObject(); + ->fetchObject() +; // Инициализация книги $book = \Bitrix\Main\Test\Typography\BookTable::getByPrimary(2) - ->fetchObject(); + ->fetchObject() +; // Добавление книги в коллекцию отношения $publisher->addToBooks($book); // Сохранение @@ -627,10 +646,12 @@ $publisher->save(); ```php // Инициализация издателя $publisher = \Bitrix\Main\Test\Typography\PublisherTable::getByPrimary(253) - ->fetchObject(); + ->fetchObject() +; // Инициализация книги $book = \Bitrix\Main\Test\Typography\BookTable::getByPrimary(2) - ->fetchObject(); + ->fetchObject() +; // Удаление одной конкретной книги издателя $publisher->removeFromBooks($book); // Сохранение @@ -646,7 +667,8 @@ $publisher->save(); ```php // Инициализация издателя $publisher = \Bitrix\Main\Test\Typography\PublisherTable::getByPrimary(253) - ->fetchObject(); + ->fetchObject() +; // Удаление всех книг издателя $publisher->removeAllBooks(); @@ -697,7 +719,8 @@ $author = \Bitrix\Main\Test\Typography\AuthorTable::query() ->addSelect('ID') ->addSelect('FULL_NAME') ->where('ID', 17) - ->fetchObject(); + ->fetchObject() +; echo $author['FULL_NAME']; // Аналогично вызову метода $author->get('FULL_NAME') diff --git a/pages/orm/orm-concepts.md b/pages/orm/orm-concepts.md index 294607b..66e8be5 100644 --- a/pages/orm/orm-concepts.md +++ b/pages/orm/orm-concepts.md @@ -568,7 +568,9 @@ new Entity\StringField('ISBN', [ if (preg_match('/^\d{13}$/', $clean)) { // Проверяем, что значение состоит из 13 цифр return true; // Если условие выполняется, валидация успешна - } else { + } + else + { return 'Код ISBN должен содержать 13 цифр.'; // Сообщение об ошибке, если условие не выполняется } } @@ -617,7 +619,9 @@ new Entity\StringField('ISBN', [ $clean = str_replace('-', '', $value); // Удаляем дефисы из значения if (preg_match('/^\d{13}$/', $clean)) { // Проверяем, что значение состоит из 13 цифр return true; // Если условие выполняется, валидация успешна - } else { + } + else + { return 'Код ISBN должен содержать 13 цифр.'; // Сообщение об ошибке, если условие не выполняется } }, @@ -636,12 +640,15 @@ new Entity\StringField('ISBN', [ ```php // выполняем операцию $result = BookTable::update(...); -if (!$result->isSuccess()) { +if (!$result->isSuccess()) +{ // Получаем список ошибок $errors = $result->getErrors(); - foreach ($errors as $error) { - if ($error->getCode() == 'MY_ISBN_CHECKSUM') { + foreach ($errors as $error) + { + if ($error->getCode() == 'MY_ISBN_CHECKSUM') + { // Обработка ошибки, связанной с нашим валидатором контрольной цифры ISBN } } diff --git a/pages/orm/query-builder.md b/pages/orm/query-builder.md index 1e5a7d4..fded6d2 100644 --- a/pages/orm/query-builder.md +++ b/pages/orm/query-builder.md @@ -45,7 +45,8 @@ function attachSelect(Entity\Query $query): void $query->addSelect('ID'); // Условие для добавления поля ISBN - if (/* условие */) { + if (/* условие */) + { $query->addSelect('ISBN'); } } @@ -53,12 +54,14 @@ function attachSelect(Entity\Query $query): void function attachOthers(Entity\Query $query): void { // Условие для добавления фильтра - if (/* условие */) { + if (/* условие */) + { $query->setFilter(/* параметры фильтра */); } // Условие для добавления сортировки - if (/* условие */) { + if (/* условие */) + { $query->setOrder(/* параметры сортировки */); } } diff --git a/pages/orm/querying-data.md b/pages/orm/querying-data.md index ede4c84..06ceba1 100644 --- a/pages/orm/querying-data.md +++ b/pages/orm/querying-data.md @@ -51,7 +51,8 @@ $result = BookTable::getList([ // Получение данных построчно $rows = []; $result = BookTable::getList($parameters); -while ($row = $result->fetch()) { +while ($row = $result->fetch()) +{ $rows[] = $row; } @@ -71,7 +72,8 @@ class BookTable extends \Bitrix\Main\Entity\DataManager return [ function ($data) { - if (isset($data['PUBLISH_DATE'])) { + if (isset($data['PUBLISH_DATE'])) + { $data['PUBLISH_DATE'] = date('d.m.Y', strtotime($data['PUBLISH_DATE'])); } return $data; @@ -546,7 +548,8 @@ class UserTable // Использование метода withActive $activeUsers = UserTable::query() ->withActive() // Применяем фильтр для активных пользователей - ->fetchCollection(); // Выполняем запрос и получаем коллекцию + ->fetchCollection() // Выполняем запрос и получаем коллекцию +; // WHERE `ACTIVE`='Y' ``` @@ -566,14 +569,16 @@ class UserTable { $query ->addSelect('LOGIN') // Добавляем поле LOGIN в выборку - ->where('ACTIVE', $value); // Фильтр ACTIVE = $value + ->where('ACTIVE', $value) // Фильтр ACTIVE = $value + ; } } // Использование метода withActive $activeUsers = UserTable::query() ->withActive(false) // Применяем фильтр для неактивных пользователей - ->fetchCollection(); // Выполняем запрос и получаем коллекцию + ->fetchCollection() // Выполняем запрос и получаем коллекцию +; // SELECT `LOGIN` ... WHERE `ACTIVE`='N' ``` @@ -619,9 +624,12 @@ public static function getTableName() { public function quote($identifier) { - if (self::isKnownFunctionCall($identifier)) { + if (self::isKnownFunctionCall($identifier)) + { return $identifier; - } else { + } + else + { return parent::quote($identifier); } } @@ -648,7 +656,8 @@ public static function getTableName() $query = BookTable::query() ->addSelect('NAME') ->addSelect('AUTHORS') - ->setLimit(5); + ->setLimit(5) +; $books = $query->fetchCollection(); // SQL-запрос: @@ -668,7 +677,8 @@ $query = BookTable::query() ->addSelect('NAME') ->addSelect('AUTHORS') ->addSelect('CATEGORIES') - ->addSelect('TAGS'); + ->addSelect('TAGS') +; $books = $query->fetchCollection(); // SQL-запрос @@ -721,7 +731,8 @@ public static function decompose(Query $query, $fairLimit = true, $separateRelat ```php \Bitrix\Main\UserTable::query() ->where("ID", 1) - ->exec(); + ->exec() + ; // WHERE `main_user`.`ID` = 1 ``` @@ -732,7 +743,8 @@ public static function decompose(Query $query, $fairLimit = true, $separateRelat ```php \Bitrix\Main\UserTable::query() ->where("ID", "<", 10) - ->exec(); + ->exec() + ; // WHERE `main_user`.`ID` < 10 ``` @@ -755,7 +767,8 @@ public static function decompose(Query $query, $fairLimit = true, $separateRelat ```php \Bitrix\Main\UserTable::query() ->whereNull("ID") - ->exec(); + ->exec() + ; // WHERE `main_user`.`ID` IS NULL ``` @@ -768,7 +781,8 @@ public static function decompose(Query $query, $fairLimit = true, $separateRelat ```php \Bitrix\Main\UserTable::query() ->whereNotNull("ID") - ->exec(); + ->exec() + ; // WHERE `main_user`.`ID` IS NOT NULL ``` @@ -779,7 +793,8 @@ public static function decompose(Query $query, $fairLimit = true, $separateRelat ```php \Bitrix\Main\UserTable::query() ->whereExpr('JSON_CONTAINS(%s, 4)', ['SOME_JSON_FIELD']) - ->exec(); + ->exec() + ; // WHERE JSON_CONTAINS(`main_user`.`SOME_JSON_FIELD`, 4) ``` @@ -792,7 +807,8 @@ public static function decompose(Query $query, $fairLimit = true, $separateRelat ```php \Bitrix\Main\UserTable::query() ->whereColumn('NAME', 'LOGIN') - ->exec(); + ->exec() + ; // WHERE `main_user`.`NAME` = `main_user`.`LOGIN` ``` @@ -801,7 +817,8 @@ public static function decompose(Query $query, $fairLimit = true, $separateRelat ```php \Bitrix\Main\UserTable::query() ->where('NAME', new Query\Filter\Expression\Column('LOGIN')) - ->exec(); + ->exec() + ; // WHERE `main_user`.`NAME` = `main_user`.`LOGIN` ``` @@ -813,7 +830,8 @@ public static function decompose(Query $query, $fairLimit = true, $separateRelat new Column('NAME'), new Column('LAST_NAME') ]) - ->exec(); + ->exec() + ; // WHERE `main_user`.`LOGIN` IN (`main_user`.`NAME`, `main_user`.`LAST_NAME`) ``` @@ -829,7 +847,8 @@ public static function decompose(Query $query, $fairLimit = true, $separateRelat ->where('ACTIVE', true) ->whereNotNull('PERSONAL_BIRTHDAY') ->whereLike('NAME', 'A%') - ->exec(); + ->exec() +; // WHERE `main_user`.`ID` > 1 AND `main_user`.`ACTIVE` = 'Y' AND `main_user`.`PERSONAL_BIRTHDAY` IS NOT NULL AND `main_user`.`NAME` LIKE 'A%' ``` @@ -849,7 +868,8 @@ public static function decompose(Query $query, $fairLimit = true, $separateRelat ['PERSONAL_BIRTHDAY', '<>', null], ['NAME', 'like', 'A%'] ]) - ->exec(); + ->exec() +; // WHERE `main_user`.`ID` > 1 AND `main_user`.`ACTIVE` = 'Y' AND `main_user`.`PERSONAL_BIRTHDAY` IS NOT NULL AND `main_user`.`NAME` LIKE 'A%' ``` @@ -865,7 +885,8 @@ public static function decompose(Query $query, $fairLimit = true, $separateRelat ['ID', '>', 1], ['ACTIVE', true] ]) - ->exec(); + ->exec() +; // WHERE `main_user`.`ID` > 1 AND `main_user`.`ACTIVE` = 'Y' ``` @@ -879,7 +900,8 @@ use Bitrix\Main\ORM\Query\Query; ->where(Query::filter()->where([ ["ID", '>', 1], ['ACTIVE', true] - ]))->exec(); + ]))->exec() +; // WHERE `main_user`.`ID` > 1 AND `main_user`.`ACTIVE` = 'Y' ``` @@ -897,7 +919,8 @@ use Bitrix\Main\ORM\Query\Query; ['ID', 1], ['LOGIN', 'admin'] ]) - )->exec(); + )->exec() +; // WHERE `main_user`.`ACTIVE` = 'Y' AND (`main_user`.`ID` = 1 OR `main_user`.`LOGIN` = 'admin') ``` @@ -906,6 +929,7 @@ use Bitrix\Main\ORM\Query\Query; ```php use Bitrix\Main\ORM\Query\Query; + \Bitrix\Main\UserTable::query() ->where('ACTIVE', true) ->where(Query::filter() @@ -913,7 +937,8 @@ use Bitrix\Main\ORM\Query\Query; ->where('ID', 1) ->where('LOGIN', 'admin') ) - ->exec(); + ->exec() +; // WHERE `main_user`.`ACTIVE` = 'Y' AND (`main_user`.`ID` = 1 OR `main_user`.`LOGIN` = 'admin') ``` @@ -926,7 +951,8 @@ use Bitrix\Main\ORM\Fields\ExpressionField; \Bitrix\Main\UserTable::query() ->where(new ExpressionField('LNG', 'LENGTH(%s)', 'LAST_NAME'), '>', 10) - ->exec(); + ->exec() +; // WHERE LENGTH(`main_user`.`LAST_NAME`) > '10' ``` @@ -936,12 +962,14 @@ use Bitrix\Main\ORM\Fields\ExpressionField; use Bitrix\Main\ORM\Query\Query; \Bitrix\Main\UserTable::query() ->where(Query::expr()->length("LAST_NAME"), '>', 10) - ->exec(); + ->exec() +; // WHERE LENGTH(`main_user`.`LAST_NAME`) > '10' \Bitrix\Main\UserTable::query() ->addSelect(Query::expr()->count("ID"), 'CNT') - ->exec(); + ->exec() +; // SELECT COUNT(`main_user`.`ID`) AS `CNT` FROM `b_user` `main_user` ``` @@ -1017,7 +1045,8 @@ new Entity\ReferenceField('GROUP', GroupTable::class, Везде, где указывается имя поля, можно указать любую цепочку переходов: ```php -->whereColumn('this.AUTHOR.UserGroup:USER.GROUP.OWNER.ID', 'ref.ID'); +->whereColumn('this.AUTHOR.UserGroup:USER.GROUP.OWNER.ID', 'ref.ID') +; ``` ### Формат массива diff --git a/pages/performance/caching.md b/pages/performance/caching.md index 46e25f6..bd700d5 100644 --- a/pages/performance/caching.md +++ b/pages/performance/caching.md @@ -53,10 +53,13 @@ $cache = Bitrix\Main\Application::getInstance()->getCache(); ```php // Проверяем наличие кеша -if ($cache->initCache(3600, 'cache_key')) { +if ($cache->initCache(3600, 'cache_key')) +{ // Получаем данные из кеша $data = $cache->getVars(); -} elseif ($cache->startDataCache()) { +} +elseif ($cache->startDataCache()) +{ // Если кеша нет, получаем данные из базы $data = getDataFromDatabase(); @@ -76,10 +79,13 @@ if ($cache->initCache( )) { $result = $cache->getVars(); -} elseif ($cache->startDataCache()) { - $result = array(); +} +elseif ($cache->startDataCache()) +{ + $result = []; // Если данные недействительны, отменяем кеширование - if ($isInvalid) { + if ($isInvalid) + { $cache->abortDataCache(); } // Сохраняем валидные данные @@ -93,7 +99,8 @@ if ($cache->initCache( $cache = Bitrix\Main\Data\Cache::createInstance(); // Если есть закешированные данные, они выведутся в буфер в методе Cache::startDataCache -if ($cache->startDataCache(3600, 'xxxx')) { +if ($cache->startDataCache(3600, 'xxxx')) +{ echo 'Какой-нибудь HTML'; $cache->endDataCache(); @@ -136,10 +143,13 @@ use Bitrix\Main\Application; $cache = Application::getInstance()->getCache(); // Проверяем наличие кеша -if ($cache->initCache(3600, 'cache_key')) { +if ($cache->initCache(3600, 'cache_key')) +{ // Получаем данные из кеша $data = $cache->getVars(); -} elseif ($cache->startDataCache()) { +} +elseif ($cache->startDataCache()) +{ // Если кеша нет, получаем данные из базы $data = getDataFromDatabase(); @@ -189,10 +199,13 @@ $managedCache = Application::getInstance()->getManagedCache(); $cacheKey = 'user_list'; // Проверяем наличие кеша с помощью read -if ($managedCache->read(3600, $cacheKey)) { +if ($managedCache->read(3600, $cacheKey)) +{ // Получаем данные из кеша с помощью get $data = $managedCache->get($cacheKey); -} else { +} +else +{ // Если кеша нет, загружаем данные и сохраняем их в кеш $data = loadUsers(); $managedCache->set($cacheKey, $data); @@ -216,7 +229,8 @@ use Bitrix\Main\Application; $managedCache = Application::getInstance()->getManagedCache(); $cacheKey = 'user_list'; -if (!$managedCache->read(3600, $cacheKey)) { +if (!$managedCache->read(3600, $cacheKey)) +{ $data = loadUsers(); $managedCache->setImmediate($cacheKey, $data); } @@ -232,9 +246,12 @@ $cacheKey = 'active_user_list'; $cacheDir = 'orm_b_user'; // Проверяем наличие кеша с помощью read -if ($managedCache->read(3600, $cacheKey, $cacheDir)) { +if ($managedCache->read(3600, $cacheKey, $cacheDir)) +{ $users = $managedCache->get($cacheKey); -} else { +} +else +{ $users = loadActiveUsers(); $managedCache->set($cacheKey, $users); } @@ -576,10 +593,13 @@ $cacheDir = 'my_cache_dir'; $taggedCache = Application::getInstance()->getTaggedCache(); // Проверяем наличие кеша -if ($cache->initCache(3600, 'cache_key', $cacheDir)) { +if ($cache->initCache(3600, 'cache_key', $cacheDir)) +{ // Получаем данные из кеша $data = $cache->getVars(); -} elseif ($cache->startDataCache()) { +} +elseif ($cache->startDataCache()) +{ // Если кеша нет, получаем данные из базы $data = getDataFromDatabase(); diff --git a/pages/performance/query-optimization.md b/pages/performance/query-optimization.md index 3a79318..0840645 100644 --- a/pages/performance/query-optimization.md +++ b/pages/performance/query-optimization.md @@ -14,8 +14,10 @@ description: 'Как оптимизировать запросы к базе д - Неправильный подход: выполнить запрос в цикле. Для каждого товара в корзине выполняется отдельный запрос к базе данных. Это неэффективно, так как количество запросов растет с увеличением числа товаров. ```php - foreach ($arResult["ORDERS"] as $key => $val) { - foreach ($val["BASKET_ITEMS"] as $vvval) { + foreach ($arResult["ORDERS"] as $key => $val) + { + foreach ($val["BASKET_ITEMS"] as $vvval) + { $rsEls = CIBlockElement::GetByID($vvval["PRODUCT_ID"]); // Запрос в цикле } } @@ -28,15 +30,18 @@ description: 'Как оптимизировать запросы к базе д $arIDs = array(); // Перебираем заказы и товары в корзине - foreach($arResult["ORDERS"] as $key => $val) { - foreach($val["BASKET_ITEMS"] as $vvval) { + foreach($arResult["ORDERS"] as $key => $val) + { + foreach($val["BASKET_ITEMS"] as $vvval) + { // Добавляем ID товара в массив $arIDs[] = $vvval["PRODUCT_ID"]; } } // Если массив не пустой, выполняем один запрос - if (!empty($arIDs)) { + if (!empty($arIDs)) + { $rsEls = CIBlockElement::GetList( [], ["ID" => $arIDs], @@ -46,8 +51,10 @@ description: 'Как оптимизировать запросы к базе д ); // Наполняем данные, используя ID - foreach($arResult["ORDERS"] as $key => $val) { - foreach($val["BASKET_ITEMS"] as $vvval) { + foreach($arResult["ORDERS"] as $key => $val) + { + foreach($val["BASKET_ITEMS"] as $vvval) + { // Работа с данными } } @@ -102,7 +109,8 @@ $rs = CIBlockElement::GetList( ); // Сохраняем результаты -while($ar = $rs->GetNext()) { +while($ar = $rs->GetNext()) +{ $arResult['ITEMS'][] = $ar; } ``` @@ -129,7 +137,8 @@ while($ar = $rs->GetNext()) { ```php Bitrix\Iblock\ElementTable::query() ->setSelect(['ID', 'NAME', 'CODE']) - ->where('CODE','xxx')->exec(); + ->where('CODE','xxx')->exec() + ; ``` Здесь фильтр `where('CODE', 'xxx')` отбирает элементы, у которых поле `CODE` равно `'xxx'`. diff --git a/pages/security/captcha.md b/pages/security/captcha.md index 5fe2068..1298a5d 100644 --- a/pages/security/captcha.md +++ b/pages/security/captcha.md @@ -93,7 +93,8 @@ $cpt = new CCaptcha(); // Получаем или генерируем пароль для CAPTCHA $captchaPass = COption::GetOptionString("main", "captcha_password", ""); -if (strlen($captchaPass) <= 0) { +if (strlen($captchaPass) <= 0) +{ $captchaPass = randString(10); // Генерируем случайный пароль с помощью функции randString COption::SetOptionString("main", "captcha_password", $captchaPass); // Сохраняем пароль } @@ -123,10 +124,13 @@ $cpt->SetCodeCrypt($captchaPass); ```php CaptchaCheckCode($_POST["captcha_word"], $_POST["captcha_code"])) { +if (!$APPLICATION->CaptchaCheckCode($_POST["captcha_word"], $_POST["captcha_code"])) +{ // Неправильное значение echo "CAPTCHA введена неверно. Попробуйте еще раз."; -} else { +} +else +{ // Правильное значение echo "CAPTCHA введена верно."; } @@ -166,7 +170,8 @@ $code = $APPLICATION->CaptchaGetCode(); ```php // Проверяем введенный пользователем код CAPTCHA -if (!$APPLICATION->CaptchaCheckCode($_POST["captcha_word"], $_POST["captcha_sid"])) { +if (!$APPLICATION->CaptchaCheckCode($_POST["captcha_word"], $_POST["captcha_sid"])) +{ echo 'Неверный код CAPTCHA'; } ``` diff --git a/pages/security/cipher.md b/pages/security/cipher.md index 5b4ea2b..a719a57 100644 --- a/pages/security/cipher.md +++ b/pages/security/cipher.md @@ -123,7 +123,8 @@ $decrypted = $cipher->decrypt($decoded, $cryptoKey); Обрабатывайте ошибки с помощью `try/catch`. ```php -try { +try +{ $cipher = new \Bitrix\Main\Security\Cipher(); $originalData = 'Конфиденциальная информация'; @@ -137,7 +138,9 @@ try { // Результат должен совпадать с исходными данными echo $decryptedData; // Конфиденциальная информация -} catch(\Bitrix\Main\Security\SecurityException $e) { +} +catch(\Bitrix\Main\Security\SecurityException $e) +{ // Обрабатываем ошибку echo 'Ошибка шифрования: ' . $e->getMessage(); } diff --git a/pages/security/cryptofield.md b/pages/security/cryptofield.md index 75be68b..af7b846 100644 --- a/pages/security/cryptofield.md +++ b/pages/security/cryptofield.md @@ -49,7 +49,8 @@ description: 'Криптографические поля в ORM. Руковод - поддержку OpenSSL на сервере. ```php -if (\Bitrix\Main\ORM\Fields\CryptoField::cryptoAvailable()) { +if (\Bitrix\Main\ORM\Fields\CryptoField::cryptoAvailable()) +{ // можно работать с CryptoField и SecretField } ``` @@ -160,7 +161,8 @@ BookTable::enableCrypto('ISBN'); Если таблица только создается и в ней еще нет данных, сразу включите шифрование для нужной колонки в установщике модуля. ```php -if (\Bitrix\Main\ORM\Fields\CryptoField::cryptoAvailable()) { +if (\Bitrix\Main\ORM\Fields\CryptoField::cryptoAvailable()) +{ BookTable::enableCrypto('ISBN'); } ``` @@ -209,12 +211,14 @@ class TempBookTable extends DataManager } } -if (CryptoField::cryptoAvailable()) { +if (CryptoField::cryptoAvailable()) +{ $connection = Application::getConnection(); $result = $connection->query('SELECT ID, ISBN FROM book'); // Перебираем все записи и обновляем ISBN через временный класс - while ($row = $result->fetch()) { + while ($row = $result->fetch()) + { // Передаем то же значение, но поле crypto зашифрует его TempBookTable::update($row['ID'], ['ISBN' => $row['ISBN']]); } @@ -273,7 +277,8 @@ public static function getMap() Как и для `CryptoField`, после создания таблицы или добавления поля с уже существующими данными, нужно включить шифрование с помощью `enableCrypto()`. ```php -if (\Bitrix\Main\ORM\Fields\CryptoField::cryptoAvailable()) { +if (\Bitrix\Main\ORM\Fields\CryptoField::cryptoAvailable()) +{ MyTable::enableCrypto('API_TOKEN'); } ``` diff --git a/pages/security/csrf-ssrf.md b/pages/security/csrf-ssrf.md index e43edca..ec8f408 100644 --- a/pages/security/csrf-ssrf.md +++ b/pages/security/csrf-ssrf.md @@ -71,7 +71,8 @@ Bitrix Framework предоставляет функции для работы В общем виде для проверки корректности запроса достаточно добавить `check_bitrix_sessid` в условие: ```php -if (check_bitrix_sessid()) { +if (check_bitrix_sessid()) +{ // Действие выполняется } ``` @@ -199,11 +200,15 @@ $http->get($_GET['uri']); // Пытаемся отправить запрос ```php $file = CFile::MakeFileArray($_GET['uri']); -if ($file) { +if ($file) +{ $res = CFile::CheckImageFile($file); - if ($res === null) { + if ($res === null) + { // Изображение корректно, можно продолжать - } else { + } + else + { // Обработка ошибки } } diff --git a/pages/security/jwt.md b/pages/security/jwt.md index 4dc1c3b..fab4b53 100644 --- a/pages/security/jwt.md +++ b/pages/security/jwt.md @@ -96,11 +96,14 @@ use Bitrix\Main\Web\JWT; $secret = 'ваш-секретный-ключ'; $jwt = 'токен-полученный-от-клиента'; -try { +try +{ $payload = JWT::decode($jwt, $secret, ['HS256']); // Токен верный, работаем с данными: echo 'Пользователь: ' . $payload->name; -} catch (Exception $e) { +} +catch (Exception $e) +{ // Токен не прошёл проверку echo 'Ошибка: ' . $e->getMessage(); } From 97c257e960b89ee4549390779dceea2138a9d0cb Mon Sep 17 00:00:00 2001 From: shoman4eg Date: Thu, 23 Jul 2026 22:16:33 +0200 Subject: [PATCH 3/3] =?UTF-8?q?=D0=B8=D0=B7=D0=BC=D0=B5=D0=BD=D0=B5=D0=BD?= =?UTF-8?q?=20=D0=BF=D0=BE=D1=80=D1=8F=D0=B4=D0=BE=D0=BA=20=D0=B8=D0=BC?= =?UTF-8?q?=D0=BF=D0=BE=D1=80=D1=82=D0=BE=D0=B2,=20=D1=83=D0=B1=D1=80?= =?UTF-8?q?=D0=B0=D0=BD=D1=8B=20=D0=BB=D0=B8=D1=88=D0=BD=D0=B8=D0=B5=20?= =?UTF-8?q?=D0=BF=D1=80=D0=BE=D0=B1=D0=B5=D0=BB=D1=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pages/cms-basics/mail.md | 4 +++- pages/cms-basics/menu.md | 13 +++++++------ pages/cms-basics/page-templates.md | 14 ++++++++------ pages/framework/background-jobs.md | 2 +- pages/framework/components.md | 11 +++++++---- pages/get-started/create-component.md | 3 +-- pages/get-started/create-controller.md | 9 +++++---- 7 files changed, 32 insertions(+), 24 deletions(-) diff --git a/pages/cms-basics/mail.md b/pages/cms-basics/mail.md index 590f19a..d5acc7c 100644 --- a/pages/cms-basics/mail.md +++ b/pages/cms-basics/mail.md @@ -577,9 +577,11 @@ define("BX_CRONTAB_SUPPORT", false); - В редакторе отображаются компоненты, у которых в файле `.description.php` указан тип `"TYPE" => "mail"`. ```php - Loc::getMessage('SBBS_DEFAULT_TEMPLATE_NAME'), 'TYPE' => 'mail', diff --git a/pages/cms-basics/menu.md b/pages/cms-basics/menu.md index 55cd214..39623ee 100644 --- a/pages/cms-basics/menu.md +++ b/pages/cms-basics/menu.md @@ -149,9 +149,10 @@ $aMenuLinks = [ ```php +
    +
    @@ -725,7 +726,7 @@ $aMenuLinks = [ 9. Допишите проверку включения кода из ядра: ```php - IncludeComponent(… @@ -740,7 +741,7 @@ $aMenuLinks = [ В результате код в файле должен быть следующим: ```php - IncludeComponent( diff --git a/pages/cms-basics/page-templates.md b/pages/cms-basics/page-templates.md index 351579f..817a75e 100644 --- a/pages/cms-basics/page-templates.md +++ b/pages/cms-basics/page-templates.md @@ -193,7 +193,7 @@ $MESS['sect_inc'] = "Включаемая область для раздела"; ```php use Bitrix\Main\Localization\Loc; - $TEMPLATE["announcement.php"] = ["name" => Loc::etMessage("announcement"), "sort"=>2]; + $TEMPLATE["announcement.php"] = ["name" => Loc::getMessage("announcement"), "sort" => 2]; ``` 4. Настройте языковые файлы: @@ -207,7 +207,7 @@ $MESS['sect_inc'] = "Включаемая область для раздела"; - для английского языка в файле `/local/templates/.default/lang/en/page_templates/.content.php`. ```php - $MESS ['announcement'] = "Important announcement"; + $MESS['announcement'] = "Important announcement"; ``` В результате шаблон будет доступен при создании страницы. @@ -235,10 +235,11 @@ $MESS['sect_inc'] = "Включаемая область для раздела"; {% cut "Код файла template.php шаблона bootstrap" %} ```php - Loc::getMessage("ADV_BANNER_NAME"), "DESCRIPTION" => Loc::getMessage("ADV_BANNER_DESC"), @@ -632,11 +634,12 @@ $MESS["SORT_BY1_TIP"] = "Это подсказка для первой сорт - `.parameters.php` — описание дополнительных параметров. Пример файла: ```php - { ```php