Passed
Push — master ( aab447...5fbf30 )
by Roeland
14:01
created

ServiceEventListener   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 36
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 17
c 1
b 0
f 0
dl 0
loc 36
rs 10
wmc 4

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A __invoke() 0 14 3
1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * @copyright 2019 Christoph Wurst <[email protected]>
7
 *
8
 * @author 2019 Christoph Wurst <[email protected]>
9
 *
10
 * @license GNU AGPL version 3 or any later version
11
 *
12
 * This program is free software: you can redistribute it and/or modify
13
 * it under the terms of the GNU Affero General Public License as
14
 * published by the Free Software Foundation, either version 3 of the
15
 * License, or (at your option) any later version.
16
 *
17
 * This program is distributed in the hope that it will be useful,
18
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
 * GNU Affero General Public License for more details.
21
 *
22
 * You should have received a copy of the GNU Affero General Public License
23
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
24
 */
25
26
namespace OC\EventDispatcher;
27
28
use OCP\AppFramework\QueryException;
29
use OCP\EventDispatcher\Event;
30
use OCP\EventDispatcher\IEventListener;
31
use OCP\IContainer;
32
use OCP\ILogger;
33
34
/**
35
 * Lazy service event listener
36
 *
37
 * Makes it possible to lazy-route a dispatched event to a service instance
38
 * created by the service container
39
 */
40
final class ServiceEventListener {
41
42
	/** @var IContainer */
43
	private $container;
44
45
	/** @var string */
46
	private $class;
47
48
	/** @var ILogger */
49
	private $logger;
50
51
	/** @var null|IEventListener */
52
	private $service;
53
54
	public function __construct(IContainer $container,
55
								string $class,
56
								ILogger $logger) {
57
		$this->container = $container;
58
		$this->class = $class;
59
		$this->logger = $logger;
60
	}
61
62
	public function __invoke(Event $event) {
63
		if ($this->service === null) {
64
			try {
65
				$this->service = $this->container->query($this->class);
66
			} catch (QueryException $e) {
67
				$this->logger->logException($e, [
68
					'level' => ILogger::ERROR,
69
					'message' => "Could not load event listener service " . $this->class,
70
				]);
71
				return;
72
			}
73
		}
74
75
		$this->service->handle($event);
76
	}
77
78
}
79