Skip to content

Commit

Permalink
Сортировка по приоритету для автозапуска сервисов
Browse files Browse the repository at this point in the history
  • Loading branch information
ProklUng committed Aug 6, 2021
1 parent e1d16c0 commit 947dad4
Show file tree
Hide file tree
Showing 3 changed files with 89 additions and 7 deletions.
12 changes: 12 additions & 0 deletions readme.MD
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,18 @@ var_dump(container($micro)->getParameter('example'));
tags: ['service.bootstrap']
```

Поддерживается приоритет запуска. Тогда надо так:

```yaml
app.options:
class: Local\Services\AppOptions
arguments: ['%kernel.environment%', '@parameter_bag']
tags:
- { name: 'service.bootstrap', priority: 100 }
```

Сервис с приоритетом 100 запустится раньше сервиса с приоритетом 200.

## Автоматическая подвязка на события Битрикс

Тэг: `bitrix.events.init`.
Expand Down
28 changes: 24 additions & 4 deletions src/PostLoadingPass/BootstrapServices.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,10 @@
*
* @package Prokl\ServiceProvider\PostLoadingPass
*
* @since 28.09.2020
* @since 26.09.2020
* @since 27.09.2020 Доработки.
* @since 04.05.2021 Исключения сервисов автозагрузки больше не глушатся.
* @since 06.08.2021 Сортировка по приоритету.
*/
final class BootstrapServices implements PostLoadingPassInterface
{
Expand All @@ -25,7 +28,7 @@ final class BootstrapServices implements PostLoadingPassInterface

/**
* @inheritDoc
* @throws Exception
* @throws Exception Когда проблемы с получением сервиса из контейнера.
*/
public function action(Container $containerBuilder) : bool
{
Expand All @@ -39,10 +42,27 @@ public function action(Container $containerBuilder) : bool
return false;
}

$result = [];
foreach ($bootstrapServices as $service => $value) {
$containerBuilder->get($service);
$priority = 0;
if (array_key_exists(0, $value) && is_array($value[0])) {
if (array_key_exists('priority', $value[0])) {
$priority = (int)$value[0]['priority'];
}
}

$result[] = ['service' => $service, 'priority' => $priority];
}

usort($result, static function ($a, $b) : bool {
// @phpstan-ignore-line
return $a['priority'] > $b['priority'];
});

foreach ($result as $service) {
$containerBuilder->get($service['service']);
}

return true;
}
}
}
56 changes: 53 additions & 3 deletions tests/Cases/PostLoadingPasses/BootstrapServicesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ class BootstrapServicesTest extends BaseTestCase
*/
private $stubService;


/**
* @inheritDoc
*/
Expand All @@ -44,7 +45,6 @@ protected function setUp(): void
*
* @return void
* @throws Exception
*
*/
public function testAction(): void
{
Expand Down Expand Up @@ -78,6 +78,56 @@ public function testActionNoListener(): void
);
}

/**
* Сортировка по приоритету.
*
* @return void
* @throws Exception
*/
public function testPriority() : void
{
ob_start();
$fooService = new class {
public function __construct()
{
echo 'First';
}
};

$booService = new class {
public function __construct()
{
echo 'Second';
}
};
ob_get_clean();

$container = new ContainerBuilder();
$container
->register('fooService', get_class($fooService))
->setPublic(true)
->setTags(['bootstrap.service' => ['priority' => 200]])
;

$container
->register('barService', get_class($booService))
->setPublic(true)
->setTags(['bootstrap.service' => ['priority' => 100]])
;

$container->setParameter('_bootstrap', [
'fooService' => [['priority' => 200]], 'barService' => [['priority' => 100]],
]);

ob_start();
$result = $this->obTestObject->action($container);
$content = ob_get_clean();

$this->assertTrue($result);
// Второй по порядку, но первый по сортировке сервис отработал первым.
$this->assertSame('SecondFirst', $content);
}

/**
* Мок обработчика.
*
Expand Down Expand Up @@ -106,7 +156,7 @@ public function addEvent(): void
* Тестовый контейнер.
*
* @param string $serviceId ID сервиса.
* @param array $params Параметры.
* @param array $params
*
* @return ContainerBuilder
*/
Expand Down Expand Up @@ -147,4 +197,4 @@ private function process(ContainerBuilder $container): void
{
(new RemoveUnusedDefinitionsPass())->process($container);
}
}
}

0 comments on commit 947dad4

Please sign in to comment.