AsyncBus.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OC\Command;
  8. use OCP\Command\IBus;
  9. use OCP\Command\ICommand;
  10. /**
  11. * Asynchronous command bus that uses the background job system as backend
  12. */
  13. abstract class AsyncBus implements IBus {
  14. /**
  15. * List of traits for command which require sync execution
  16. *
  17. * @var string[]
  18. */
  19. private $syncTraits = [];
  20. /**
  21. * Schedule a command to be fired
  22. *
  23. * @param \OCP\Command\ICommand | callable $command
  24. */
  25. public function push($command) {
  26. if ($this->canRunAsync($command)) {
  27. $this->queueCommand($command);
  28. } else {
  29. $this->runCommand($command);
  30. }
  31. }
  32. /**
  33. * Queue a command in the bus
  34. *
  35. * @param \OCP\Command\ICommand | callable $command
  36. */
  37. abstract protected function queueCommand($command);
  38. /**
  39. * Require all commands using a trait to be run synchronous
  40. *
  41. * @param string $trait
  42. */
  43. public function requireSync($trait) {
  44. $this->syncTraits[] = trim($trait, '\\');
  45. }
  46. /**
  47. * @param \OCP\Command\ICommand | callable $command
  48. */
  49. private function runCommand($command) {
  50. if ($command instanceof ICommand) {
  51. $command->handle();
  52. } else {
  53. $command();
  54. }
  55. }
  56. /**
  57. * @param \OCP\Command\ICommand | callable $command
  58. * @return bool
  59. */
  60. private function canRunAsync($command) {
  61. $traits = $this->getTraits($command);
  62. foreach ($traits as $trait) {
  63. if (in_array($trait, $this->syncTraits)) {
  64. return false;
  65. }
  66. }
  67. return true;
  68. }
  69. /**
  70. * @param \OCP\Command\ICommand | callable $command
  71. * @return string[]
  72. */
  73. private function getTraits($command) {
  74. if ($command instanceof ICommand) {
  75. return class_uses($command);
  76. } else {
  77. return [];
  78. }
  79. }
  80. }