Skip to content

Commit dc02480

Browse files
committed
Регистрация команд битриксовых модулей
1 parent ed93c75 commit dc02480

File tree

3 files changed

+98
-2
lines changed

3 files changed

+98
-2
lines changed

Services/Console/ConsoleCommandConfigurator.php

Lines changed: 74 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
use Symfony\Component\Console\Exception\CommandNotFoundException;
1010
use Symfony\Component\DependencyInjection\ContainerInterface;
1111
use Symfony\Component\HttpKernel\Bundle\Bundle;
12+
use Bitrix\Main\ModuleManager;
1213

1314
/**
1415
* Class ConsoleCommandConfigurator
@@ -17,6 +18,7 @@
1718
* @since 10.12.2020
1819
* @since 20.12.2020 Рефакторинг. Форк нативного способа подключения команд.
1920
* @since 26.02.2021 Убрал array_merge в цикле.
21+
* @since 12.01.2021 Подхватывание команд установленных битриксовых модулей.
2022
*/
2123
class ConsoleCommandConfigurator
2224
{
@@ -126,6 +128,51 @@ public function setAutoExit(bool $autoexit) : void
126128
$this->application->setAutoExit($autoexit);
127129
}
128130

131+
/**
132+
* Регистрация команд битриксовых модулей.
133+
*
134+
* @return void
135+
*
136+
* @since 12.01.2021
137+
*
138+
* @internal Формат файла cli.php в папке модуля.
139+
* return [
140+
* new SampleCommand(), // Должен наследоваться от \Symfony\Component\Console\Command\Command
141+
* container()->get('sample.command') // Из контейнера
142+
* ]
143+
*/
144+
private function registerModuleCommands() : void
145+
{
146+
// Проверка - в Битриксе мы или нет.
147+
if (!class_exists(ModuleManager::class)) {
148+
return;
149+
}
150+
151+
$result = [];
152+
153+
$documentRoot = $this->container->getParameter('kernel.project_dir');
154+
155+
foreach (glob($documentRoot . '/local/modules/*/cli.php') as $path) {
156+
$moduleName = $this->getModuleNameByPath($path);
157+
if (ModuleManager::isModuleInstalled($moduleName)) {
158+
$result = require_once $path;
159+
}
160+
}
161+
162+
foreach (glob($documentRoot . '/bitrix/modules/*/cli.php') as $path) {
163+
$moduleName = $this->getModuleNameByPath($path);
164+
if (ModuleManager::isModuleInstalled($moduleName)) {
165+
$result = require_once $path;
166+
}
167+
}
168+
169+
foreach ((array)$result as $item) {
170+
if (is_subclass_of($item, Command::class)) {
171+
$this->application->add($item);
172+
}
173+
}
174+
}
175+
129176
/**
130177
* Регистрация команд.
131178
*
@@ -160,5 +207,31 @@ private function registerCommands() : void
160207
}
161208
}
162209
}
210+
211+
$this->registerModuleCommands();
212+
}
213+
214+
/**
215+
* Название битриксового модуля по пути.
216+
*
217+
* @param string $path
218+
*
219+
* @return string
220+
* @since 12.01.2021
221+
*/
222+
private function getModuleNameByPath(string $path): string
223+
{
224+
$documentRoot = $this->container->getParameter('kernel.project_dir');
225+
226+
$path = str_replace(
227+
[
228+
$documentRoot . '/bitrix/modules/',
229+
$documentRoot . '/local/modules/',
230+
],
231+
'',
232+
$path
233+
);
234+
235+
return current(explode('/', $path));
163236
}
164-
}
237+
}

composer.json

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,14 @@
6767
"league/html-to-markdown": "^5.0"
6868
},
6969
"require-dev": {
70-
"proklung/phpunit-testing-tools": "^1.0",
70+
"proklung/phpunit-testing-tools": "^1.5",
7171
"icanhazstring/composer-unused": "^0.7.5"
72+
},
73+
"config": {
74+
"allow-plugins": {
75+
"composer/package-versions-deprecated": true,
76+
"phpstan/extension-installer": true,
77+
"icanhazstring/composer-unused": true
78+
}
7279
}
7380
}

readme.MD

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,22 @@ framework:
134134
- `debug:autowiring`
135135
- `config:dump-reference`
136136

137+
### Автоматическое подхватывание команд установленых битриксовых модулей
138+
139+
Конструкция пробегает по установленным (в папках `local` и `bitrix` модулям), где ищет файл `cli.php`.
140+
Он должен возвращать массив с инициализированными командами этого модуля.
141+
142+
```php
143+
return [
144+
new ExampleCommand(), // Должен наследоваться от \Symfony\Component\Console\Command\Command
145+
container()->get('console.command.about') // Из глобального контейнера
146+
];
147+
```
148+
149+
Эти команды регистрируются в общем для приложения контейнере команд и доступны через `php bin/console`.
150+
151+
Если пакет запускается не в Битриксе - ничего страшного, функционал игнорируется.
152+
137153
## Расширения
138154

139155
Любое расширение может быть отключено проставлением `false` параметру `enabled` соответствующего раздела файла

0 commit comments

Comments
 (0)