AssocArray   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 10
lcom 1
cbo 1
dl 0
loc 52
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 2
A getValue() 0 7 2
A byJsonString() 0 17 6
1
<?php
2
/**
3
 * @author Threema GmbH
4
 * @copyright Copyright (c) 2015-2016 Threema GmbH
5
 */
6
7
8
namespace Threema\Core;
9
10
class AssocArray {
11
12
	/**
13
	 * @var array
14
	 */
15
	private $data;
16
17
	/**
18
	 * @param array $data
19
	 */
20
	public function __construct(array $data) {
21
		//be sure a array is set
22
		$this->data = null !== $data ? $data : array();
23
	}
24
25
	/**
26
	 * @param string $key
27
	 * @param null $defaultValue
28
	 * @return mixed|null return the key value or the default value
29
	 */
30
	public function getValue($key, $defaultValue = null) {
31
		if(false === array_key_exists($key, $this->data)) {
32
			return $defaultValue;
33
		}
34
35
		return $this->data[$key];
36
	}
37
38
	/**
39
	 * @param $string
40
	 * @param array|null $requiredKeys
41
	 * @return AssocArray
42
	 * @throws Exception
43
	 */
44
	public static final function byJsonString($string, array $requiredKeys = null) {
45
		$v = json_decode($string, true);
46
		if(null === $v || false === $v) {
47
			throw new Exception('invalid json string');
48
		}
49
50
		//validate first
51
		if(null !== $requiredKeys) {
52
			//validate array first
53
			foreach($requiredKeys as $requiredKey) {
54
				if(false === array($v)) {
55
					throw new Exception('required key '.$requiredKey.' failed');
56
				}
57
			}
58
		}
59
		return new AssocArray($v);
60
	}
61
}
62