aboutsummaryrefslogtreecommitdiffstats
path: root/lib/private/Command/CronBus.php
blob: 1ff9bb7099aec7ee66e563381b2c33bb2521406e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<?php
/**
 * SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
 * SPDX-License-Identifier: AGPL-3.0-or-later
 */
namespace OC\Command;

use Laravel\SerializableClosure\SerializableClosure;
use OCP\BackgroundJob\IJob;
use OCP\BackgroundJob\IJobList;
use OCP\Command\ICommand;

class CronBus extends AsyncBus {
	public function __construct(
		private IJobList $jobList,
	) {
	}

	protected function queueCommand($command): void {
		$this->jobList->add($this->getJobClass($command), $this->serializeCommand($command));
	}

	/**
	 * @param ICommand|callable $command
	 * @return class-string<IJob>
	 */
	private function getJobClass($command): string {
		if ($command instanceof \Closure) {
			return ClosureJob::class;
		} elseif (is_callable($command)) {
			return CallableJob::class;
		} elseif ($command instanceof ICommand) {
			return CommandJob::class;
		} else {
			throw new \InvalidArgumentException('Invalid command');
		}
	}

	/**
	 * @param ICommand|callable $command
	 * @return string
	 */
	private function serializeCommand($command): string {
		if ($command instanceof \Closure) {
			return serialize(new SerializableClosure($command));
		} elseif (is_callable($command) or $command instanceof ICommand) {
			return serialize($command);
		} else {
			throw new \InvalidArgumentException('Invalid command');
		}
	}
}