Completed
Push — master ( e4992c...6d0a35 )
by
unknown
10:42
created

Import::getArrayFromFile()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * @author Joas Schilling <[email protected]>
4
 *
5
 * @copyright Copyright (c) 2018, ownCloud GmbH
6
 * @license AGPL-3.0
7
 *
8
 * This code is free software: you can redistribute it and/or modify
9
 * it under the terms of the GNU Affero General Public License, version 3,
10
 * as published by the Free Software Foundation.
11
 *
12
 * This program is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
 * GNU Affero General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU Affero General Public License, version 3,
18
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
19
 *
20
 */
21
22
namespace OC\Core\Command\Config;
23
24
use OCP\IConfig;
25
use Symfony\Component\Console\Command\Command;
26
use Symfony\Component\Console\Input\InputArgument;
27
use Symfony\Component\Console\Input\InputInterface;
28
use Symfony\Component\Console\Output\OutputInterface;
29
30
class Import extends Command {
31
	protected $validRootKeys = ['system', 'apps'];
32
33
	/** @var IConfig */
34
	protected $config;
35
36
	/**
37
	 * @param IConfig $config
38
	 */
39
	public function __construct(IConfig $config) {
40
		parent::__construct();
41
		$this->config = $config;
42
	}
43
44
	protected function configure() {
45
		$this
46
			->setName('config:import')
47
			->setDescription('Import a list of configs.')
48
			->addArgument(
49
				'file',
50
				InputArgument::OPTIONAL,
51
				'File with the JSON array to import.'
52
			)
53
		;
54
	}
55
56
	protected function execute(InputInterface $input, OutputInterface $output) {
57
		$importFile = $input->getArgument('file');
58
		if ($importFile !== null) {
59
			$content = $this->getArrayFromFile($importFile);
60
		} else {
61
			$content = $this->getArrayFromStdin();
62
		}
63
64
		try {
65
			$configs = $this->validateFileContent($content);
66
		} catch (\UnexpectedValueException $e) {
67
			$output->writeln('<error>' . $e->getMessage(). '</error>');
68
			return;
69
		}
70
71
		if (!empty($configs['system'])) {
72
			$this->config->setSystemValues($configs['system']);
73
		}
74
75
		if (!empty($configs['apps'])) {
76
			foreach ($configs['apps'] as $app => $appConfigs) {
77
				foreach ($appConfigs as $key => $value) {
78
					if ($value === null) {
79
						$this->config->deleteAppValue($app, $key);
80
					} else {
81
						$this->config->setAppValue($app, $key, $value);
82
					}
83
				}
84
			}
85
		}
86
87
		$output->writeln('<info>Config successfully imported from: ' . $importFile . '</info>');
88
	}
89
90
	/**
91
	 * Get the content from stdin ("config:import < file.json")
92
	 *
93
	 * @return string
94
	 */
95
	protected function getArrayFromStdin() {
96
		// Read from stdin. stream_set_blocking is used to prevent blocking
97
		// when nothing is passed via stdin.
98
		\stream_set_blocking(STDIN, 0);
99
		$content = \file_get_contents('php://stdin');
100
		\stream_set_blocking(STDIN, 1);
101
		return $content;
102
	}
103
104
	/**
105
	 * Get the content of the specified file ("config:import file.json")
106
	 *
107
	 * @param string $importFile
108
	 * @return string
109
	 */
110
	protected function getArrayFromFile($importFile) {
111
		$content = \file_get_contents($importFile);
112
		return $content;
113
	}
114
115
	/**
116
	 * @param string $content
117
	 * @return array
118
	 * @throws \UnexpectedValueException when the array is invalid
119
	 */
120
	protected function validateFileContent($content) {
121
		$decodedContent = \json_decode($content, true);
122
		if (!\is_array($decodedContent) || empty($decodedContent)) {
123
			throw new \UnexpectedValueException('The file must contain a valid json array');
124
		}
125
126
		$this->validateArray($decodedContent);
127
128
		return $decodedContent;
129
	}
130
131
	/**
132
	 * Validates that the array only contains `system` and `apps`
133
	 *
134
	 * @param array $array
135
	 */
136
	protected function validateArray($array) {
137
		$arrayKeys = \array_keys($array);
138
		$additionalKeys = \array_diff($arrayKeys, $this->validRootKeys);
139
		$commonKeys = \array_intersect($arrayKeys, $this->validRootKeys);
140
		if (!empty($additionalKeys)) {
141
			throw new \UnexpectedValueException('Found invalid entries in root: ' . \implode(', ', $additionalKeys));
142
		}
143
		if (empty($commonKeys)) {
144
			throw new \UnexpectedValueException('At least one key of the following is expected: ' . \implode(', ', $this->validRootKeys));
145
		}
146
147
		if (isset($array['system'])) {
148
			if (\is_array($array['system'])) {
149
				foreach ($array['system'] as $name => $value) {
150
					$this->checkTypeRecursively($value, $name);
151
				}
152
			} else {
153
				throw new \UnexpectedValueException('The system config array is not an array');
154
			}
155
		}
156
157
		if (isset($array['apps'])) {
158
			if (\is_array($array['apps'])) {
159
				$this->validateAppsArray($array['apps']);
160
			} else {
161
				throw new \UnexpectedValueException('The apps config array is not an array');
162
			}
163
		}
164
	}
165
166
	/**
167
	 * @param mixed $configValue
168
	 * @param string $configName
169
	 */
170
	protected function checkTypeRecursively($configValue, $configName) {
171
		if (!\is_array($configValue) && !\is_bool($configValue) && !\is_int($configValue) && !\is_string($configValue) && $configValue !== null) {
172
			throw new \UnexpectedValueException('Invalid system config value for "' . $configName . '". Only arrays, bools, integers, strings and null (delete) are allowed.');
173
		}
174
		if (\is_array($configValue)) {
175
			foreach ($configValue as $key => $value) {
176
				$this->checkTypeRecursively($value, $configName);
177
			}
178
		}
179
	}
180
181
	/**
182
	 * Validates that app configs are only integers and strings
183
	 *
184
	 * @param array $array
185
	 */
186
	protected function validateAppsArray($array) {
187
		foreach ($array as $app => $configs) {
188
			foreach ($configs as $name => $value) {
189
				if (!\is_int($value) && !\is_string($value) && $value !== null) {
190
					throw new \UnexpectedValueException('Invalid app config value for "' . $app . '":"' . $name . '". Only integers, strings and null (delete) are allowed.');
191
				}
192
			}
193
		}
194
	}
195
}
196