Passed
Push — master ( 139055...9d4e71 )
by Roeland
10:30
created

InitialStateService::getInitialStates()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 7
nc 3
nop 0
dl 0
loc 13
rs 10
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
/**
4
 * @copyright Copyright (c) 2019, Roeland Jago Douma <[email protected]>
5
 *
6
 * @author Roeland Jago Douma <[email protected]>
7
 *
8
 * @license GNU AGPL version 3 or any later version
9
 *
10
 * This program is free software: you can redistribute it and/or modify
11
 * it under the terms of the GNU Affero General Public License as
12
 * published by the Free Software Foundation, either version 3 of the
13
 * License, or (at your option) any later version.
14
 *
15
 * This program is distributed in the hope that it will be useful,
16
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18
 * GNU Affero General Public License for more details.
19
 *
20
 * You should have received a copy of the GNU Affero General Public License
21
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
22
 *
23
 */
24
25
namespace OC;
26
27
use OCP\IInitialStateService;
28
use OCP\ILogger;
29
30
class InitialStateService implements IInitialStateService {
31
32
	/** @var ILogger */
33
	private $logger;
34
35
	/** @var array */
36
	private $states = [];
37
38
	/** @var array */
39
	private $lazyStates = [];
40
41
	public function __construct(ILogger $logger) {
42
		$this->logger = $logger;
43
	}
44
45
	public function provideInitialState(string $appName, $data) {
46
		// Scalars and JsonSerializable are fine
47
		if (is_scalar($data) || $data instanceof \JsonSerializable || is_array($data)) {
48
			$this->states[$appName] = json_encode($data);
49
			return;
50
		}
51
52
		$this->logger->warning('Invalid data provided to provideInitialState by ' . $appName);
53
	}
54
55
	public function provideLazyInitialState(string $appName, \Closure $closure) {
56
		$this->lazyStates[$appName] = $closure;
57
	}
58
59
	public function getInitialStates(): array {
60
		$states = $this->states;
61
		foreach ($this->lazyStates as $app => $lazyState) {
62
			$state = $lazyState();
63
64
			if (!($lazyState instanceof \JsonSerializable)) {
65
				$this->logger->warning($app . ' provided an invalid lazy state');
66
			}
67
68
			$states[$app] = json_encode($state);
69
		}
70
71
		return $states;
72
	}
73
74
}
75