QueueBus.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Robin Appelman <robin@icewind.nl>
  6. *
  7. * @license AGPL-3.0
  8. *
  9. * This code is free software: you can redistribute it and/or modify
  10. * it under the terms of the GNU Affero General Public License, version 3,
  11. * as published by the Free Software Foundation.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU Affero General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU Affero General Public License, version 3,
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>
  20. *
  21. */
  22. namespace OC\Command;
  23. use OCP\Command\IBus;
  24. use OCP\Command\ICommand;
  25. class QueueBus implements IBus {
  26. /**
  27. * @var (ICommand|callable)[]
  28. */
  29. private $queue = [];
  30. /**
  31. * Schedule a command to be fired
  32. *
  33. * @param \OCP\Command\ICommand | callable $command
  34. */
  35. public function push($command) {
  36. $this->queue[] = $command;
  37. }
  38. /**
  39. * Require all commands using a trait to be run synchronous
  40. *
  41. * @param string $trait
  42. */
  43. public function requireSync($trait) {
  44. }
  45. /**
  46. * @param \OCP\Command\ICommand | callable $command
  47. */
  48. private function runCommand($command) {
  49. if ($command instanceof ICommand) {
  50. // ensure the command can be serialized
  51. $serialized = serialize($command);
  52. if(strlen($serialized) > 4000) {
  53. throw new \InvalidArgumentException('Trying to push a command which serialized form can not be stored in the database (>4000 character)');
  54. }
  55. $unserialized = unserialize($serialized);
  56. $unserialized->handle();
  57. } else {
  58. $command();
  59. }
  60. }
  61. public function run() {
  62. while ($command = array_shift($this->queue)) {
  63. $this->runCommand($command);
  64. }
  65. }
  66. }