ArrayDotTrait   A
last analyzed

Complexity

Total Complexity 17

Size/Duplication

Total Lines 122
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 29
dl 0
loc 122
rs 10
c 0
b 0
f 0
wmc 17

10 Methods

Rating   Name   Duplication   Size   Complexity  
A delete() 0 3 1
A isEmpty() 0 3 1
A set() 0 9 3
A add() 0 5 1
A __construct() 0 3 1
A getArray() 0 8 3
A has() 0 3 1
A clear() 0 3 1
A get() 0 13 4
A all() 0 3 1
1
<?php
2
3
namespace Win\Common\Traits;
4
5
/**
6
 * Armazena Dados
7
 */
8
trait ArrayDotTrait
9
{
10
	/**
11
	 * Dados que estão armazenados
12
	 * @var mixed[]
13
	 */
14
	protected $data = [];
15
16
	/**
17
	 * Define todos os valores
18
	 * @param mixed[] $values
19
	 */
20
	public function __construct($values = [])
21
	{
22
		$this->data = $values;
23
	}
24
25
	/**
26
	 * Retorna todos os valores
27
	 * @return mixed[]
28
	 */
29
	public function all()
30
	{
31
		return $this->data;
32
	}
33
34
	/** Exclui todos os dados */
35
	public function clear()
36
	{
37
		$this->data = [];
38
	}
39
40
	/**
41
	 * Define um valor
42
	 * @param string $key
43
	 * @param mixed $value
44
	 */
45
	public function set($key, $value)
46
	{
47
		$p = &$this->data;
48
		$keys = explode('.', $key);
49
		foreach ($keys as $k) {
50
			$p = &$p[$k];
51
		}
52
		if ($value) {
53
			$p = $value;
54
		}
55
	}
56
57
	/**
58
	 * Adiciona um valor ao array
59
	 * @param string $key
60
	 * @param mixed $value
61
	 */
62
	public function add($key, $value)
63
	{
64
		$values = $this->getArray($key);
65
		array_push($values, $value);
66
		$this->set($key, $values);
67
	}
68
69
	/**
70
	 * Retorna um valor
71
	 * @param string $key
72
	 * @param mixed $default Valor default, caso a $key não exista
73
	 */
74
	public function get($key, $default = null)
75
	{
76
		$data = $this->data;
77
		$keys = explode('.', $key);
78
		foreach ($keys as $k) {
79
			if (is_array($data) && array_key_exists($k, $data)) {
80
				$data = $data[$k];
81
			} else {
82
				return $default;
83
			}
84
		}
85
86
		return $data;
87
	}
88
89
	/**
90
	 * Retorna sempre um array
91
	 * @param string $key
92
	 * @return mixed
93
	 */
94
	private function getArray($key)
95
	{
96
		$values = $this->get($key, []);
97
		if (!is_array($values) && $this->has($key)) {
98
			$values = [$this->get($key)];
99
		}
100
101
		return $values;
102
	}
103
104
	/**
105
	 * Remove o valor
106
	 * @param string $key
107
	 */
108
	public function delete($key)
109
	{
110
		unset($this->data[$key]);
111
	}
112
113
	/**
114
	 * Retorna TRUE se $key existe
115
	 * @param string $key
116
	 * @return bool
117
	 */
118
	public function has($key)
119
	{
120
		return !is_null($this->get($key, null));
121
	}
122
123
	/**
124
	 * Retorna TRUE se estiver vazio
125
	 * @return bool
126
	 */
127
	public function isEmpty()
128
	{
129
		return empty($this->data);
130
	}
131
}
132