Passed
Push — master ( 147f66...7138a8 )
by Richard
17:47 queued 12:18
created

HasSettings::hasSettings()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 2
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
1
<?php
2
3
namespace Riclep\Storyblok\Traits;
4
5
use Illuminate\Support\Str;
6
7
trait HasSettings
8
{
9
	/**
10
	 * @var
11
	 */
12
	protected $_settings;
13
14
	/**
15
	 * @param $content
16
	 * @return array
17
	 */
18
	public function preprocessHasSettings($content): array
19
	{
20
		if (array_key_exists(config('storyblok.settings_field'), $content)) {
21
			$this->_settings = collect($content[config('storyblok.settings_field')])
22
				->keyBy(fn($setting) => Str::slug($setting['component'], '_'))
23
				->map(fn($setting) => collect(array_diff_key($setting, array_flip(['_editable', '_uid', 'component'])))
0 ignored issues
show
Bug introduced by
array_diff_key($setting,... '_uid', 'component'))) of type array is incompatible with the type Illuminate\Contracts\Support\Arrayable expected by parameter $value of collect(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

23
				->map(fn($setting) => collect(/** @scrutinizer ignore-type */ array_diff_key($setting, array_flip(['_editable', '_uid', 'component'])))
Loading history...
24
					->map(function ($setting) {
25
						if ($this->isCommaSeparatedList($setting)) {
26
							return $this->isCommaSeparatedList($setting);
27
						}
28
29
						return $setting;
30
					})
31
				);
32
		}
33
34
		// remove the processed item for future items
35
		unset($content[config('storyblok.settings_field')]);
36
37
		return $content;
38
	}
39
40
	/**
41
	 * @param $string
42
	 * @return array|false|int[]|string[]
43
	 */
44
	protected function isCommaSeparatedList($string): array|bool
45
	{
46
		if (!preg_match('/^[\w]+(,[\w]*)+$/', $string)) {
47
			return false;
48
		}
49
50
		return array_map(function($item) {
51
			$item = trim($item);
52
53
			// return $item as a int if it is a string of an int
54
			if (preg_match('/^\d+$/', $item)) {
55
				return (int) $item;
56
			}
57
58
			return $item;
59
		}, explode(',', $string));
60
	}
61
62
	/**
63
	 * @param $setting
64
	 * @return mixed
65
	 */
66
	public function settings($setting = null): mixed
67
	{
68
		if ($setting) {
69
			return $this->_settings[$setting];
70
		}
71
72
		return $this->_settings;
73
	}
74
75
	/**
76
	 * @param $setting
77
	 * @return false|mixed
78
	 */
79
	public function hasSetting($setting): mixed
80
	{
81
		if ($this->_settings?->has($setting)) {
82
			return $this->_settings[$setting];
83
		}
84
85
		return false;
86
	}
87
88
	/**
89
	 * @return false|mixed
90
	 */
91
	public function hasSettings(): mixed
92
	{
93
		return $this->_settings;
94
	}
95
}