MslsJson   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 69
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

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

5 Methods

Rating   Name   Duplication   Size   Complexity  
A encode() 0 3 1
A add() 0 8 1
A compare() 0 3 1
A get() 0 7 1
A __toString() 0 3 1
1
<?php
2
/**
3
 * MslsJson
4
 * @author Dennis Ploetner <[email protected]>
5
 * @since 0.9.9
6
 */
7
8
namespace lloc\Msls;
9
10
/**
11
 * Container for an array which will used in JavaScript as object in JSON
12
 * @example https://gist.githubusercontent.com/lloc/2c232cef3f910acf692f/raw/1c4f62e1de57ca48f19c37e3a63e7dc311b76b2f/MslsJson.php
13
 * @package Msls
14
 */
15
class MslsJson {
16
17
	/**
18
	 * Container
19
	 * @var array
20
	 */
21
	protected $arr = [];
22
23
	/**
24
	 * Adds a value label pair to the internal class container
25
	 *
26
	 * @param int $value
27
	 * @param string $label
28
	 *
29
	 * @return MslsJson
30
	 */
31
	public function add( $value, $label ) {
32
		$this->arr[] = [
33
			'value' => intval( $value ),
34
			'label' => strval( $label ),
35
		];
36
37
		return $this;
38
	}
39
40
	/**
41
	 * Compare the item with the key "label" of the array $a and the array $b
42
	 *
43
	 * @param array $a
44
	 * @param array $b
45
	 *
46
	 * @return int
47
	 */
48
	public static function compare( array $a, array $b ) {
49
		return strnatcmp( $a['label'], $b['label'] );
50
	}
51
52
	/**
53
	 * Get the array container sorted by label
54
	 *
55
	 * @return array
56
	 */
57
	public function get(): array {
58
		$arr = $this->arr;
59
60
		usort( $arr, [ __CLASS__, 'compare' ] );
61
62
		return $arr;
63
	}
64
65
	/**
66
	 * Encodes object and returns it as a json-string
67
	 *
68
	 * @return string
69
	 */
70
	public function encode(): string {
71
		return json_encode( $this->get() );
72
	}
73
74
	/**
75
	 * Return the encoded object as a string using the encode-method
76
	 *
77
	 * @return string
78
	 */
79
	public function __toString() {
80
		return $this->encode();
81
	}
82
83
}
84