2015-02-17 10:49:14 -05:00
|
|
|
<?php
|
2024-05-23 03:26:56 -04:00
|
|
|
|
2025-10-14 07:56:42 -04:00
|
|
|
declare(strict_types=1);
|
|
|
|
|
|
2015-02-17 10:49:14 -05:00
|
|
|
/**
|
2024-05-23 03:26:56 -04:00
|
|
|
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
|
|
|
|
|
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
|
|
|
|
|
* SPDX-License-Identifier: AGPL-3.0-only
|
2015-02-17 10:49:14 -05:00
|
|
|
*/
|
|
|
|
|
namespace OC\Command;
|
|
|
|
|
|
|
|
|
|
use OCP\Command\IBus;
|
|
|
|
|
use OCP\Command\ICommand;
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Asynchronous command bus that uses the background job system as backend
|
|
|
|
|
*/
|
2017-08-24 10:06:37 -04:00
|
|
|
abstract class AsyncBus implements IBus {
|
2015-02-23 09:25:59 -05:00
|
|
|
/**
|
|
|
|
|
* List of traits for command which require sync execution
|
|
|
|
|
*
|
|
|
|
|
* @var string[]
|
|
|
|
|
*/
|
2025-10-14 07:56:42 -04:00
|
|
|
private array $syncTraits = [];
|
2015-02-23 09:25:59 -05:00
|
|
|
|
2015-02-17 10:49:14 -05:00
|
|
|
/**
|
|
|
|
|
* Schedule a command to be fired
|
|
|
|
|
*/
|
2025-10-14 07:56:42 -04:00
|
|
|
public function push(ICommand $command): void {
|
2015-02-23 09:25:59 -05:00
|
|
|
if ($this->canRunAsync($command)) {
|
2017-08-24 10:06:37 -04:00
|
|
|
$this->queueCommand($command);
|
2015-02-23 09:25:59 -05:00
|
|
|
} else {
|
|
|
|
|
$this->runCommand($command);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2017-08-24 10:06:37 -04:00
|
|
|
/**
|
|
|
|
|
* Queue a command in the bus
|
|
|
|
|
*/
|
2025-10-14 07:56:42 -04:00
|
|
|
abstract protected function queueCommand(ICommand $command);
|
2017-08-24 10:06:37 -04:00
|
|
|
|
2015-02-23 09:25:59 -05:00
|
|
|
/**
|
|
|
|
|
* Require all commands using a trait to be run synchronous
|
|
|
|
|
*
|
|
|
|
|
* @param string $trait
|
|
|
|
|
*/
|
2025-10-14 07:56:42 -04:00
|
|
|
public function requireSync(string $trait): void {
|
2015-02-23 09:25:59 -05:00
|
|
|
$this->syncTraits[] = trim($trait, '\\');
|
|
|
|
|
}
|
|
|
|
|
|
2025-10-14 07:56:42 -04:00
|
|
|
private function runCommand(ICommand $command): void {
|
|
|
|
|
$command->handle();
|
2015-02-17 10:49:14 -05:00
|
|
|
}
|
|
|
|
|
|
2015-02-23 09:25:59 -05:00
|
|
|
/**
|
|
|
|
|
* @return bool
|
|
|
|
|
*/
|
2025-10-14 07:56:42 -04:00
|
|
|
private function canRunAsync(ICommand $command): bool {
|
2015-02-23 09:25:59 -05:00
|
|
|
$traits = $this->getTraits($command);
|
|
|
|
|
foreach ($traits as $trait) {
|
2025-10-14 07:56:42 -04:00
|
|
|
if (in_array($trait, $this->syncTraits, true)) {
|
2015-02-23 09:25:59 -05:00
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* @return string[]
|
|
|
|
|
*/
|
2025-10-14 07:56:42 -04:00
|
|
|
private function getTraits(ICommand $command): array {
|
|
|
|
|
return class_uses($command);
|
2015-02-23 09:25:59 -05:00
|
|
|
}
|
2015-02-17 10:49:14 -05:00
|
|
|
}
|