aboutsummaryrefslogtreecommitdiffstats
path: root/core/Command/Config/System/CastHelper.php
blob: f2b838bdf9b9521479b25bed2bcd768b730dd208 (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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<?php

declare(strict_types=1);
/**
 * SPDX-FileCopyrightText: 2025 Nextcloud GmbH and Nextcloud contributors
 * SPDX-License-Identifier: AGPL-3.0-or-later
 */

namespace OC\Core\Command\Config\System;

class CastHelper {
	/**
	 * @return array{value: mixed, readable-value: string}
	 */
	public function castValue(?string $value, string $type): array {
		switch ($type) {
			case 'integer':
			case 'int':
				if (!is_numeric($value)) {
					throw new \InvalidArgumentException('Non-numeric value specified');
				}
				return [
					'value' => (int)$value,
					'readable-value' => 'integer ' . (int)$value,
				];

			case 'double':
			case 'float':
				if (!is_numeric($value)) {
					throw new \InvalidArgumentException('Non-numeric value specified');
				}
				return [
					'value' => (float)$value,
					'readable-value' => 'double ' . (float)$value,
				];

			case 'boolean':
			case 'bool':
				$value = strtolower($value);
				return match ($value) {
					'true' => [
						'value' => true,
						'readable-value' => 'boolean ' . $value,
					],
					'false' => [
						'value' => false,
						'readable-value' => 'boolean ' . $value,
					],
					default => throw new \InvalidArgumentException('Unable to parse value as boolean'),
				};

			case 'null':
				return [
					'value' => null,
					'readable-value' => 'null',
				];

			case 'string':
				$value = (string)$value;
				return [
					'value' => $value,
					'readable-value' => ($value === '') ? 'empty string' : 'string ' . $value,
				];

			case 'json':
				$value = json_decode($value, true);
				return [
					'value' => $value,
					'readable-value' => 'json ' . json_encode($value),
				];

			default:
				throw new \InvalidArgumentException('Invalid type');
		}
	}
}