Completed
Push — master ( ea28d3...1760c1 )
by Dennis
04:45
created

MslsJson::compare()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 2
dl 0
loc 3
rs 10
c 0
b 0
f 0
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 = array();
22
23
	/**
24
	 * add
25
	 * @param int $value
26
	 * @param string $label
27
	 * @return MslsJson
28
	 */
29
	public function add( $value, $label ) {
30
		$this->arr[] = array(
31
			'value' => (int) $value,
32
			'label' => (string) $label,
33
		);
34
		return $this;
35
	}
36
37
	/**
38
	 * compare
39
	 *
40
	 * Compare the item with the key "label" of the array $a and the
41
	 * array $b
42
	 * @param array $a
43
	 * @param array $b
44
	 * @return int
45
	 */
46
	public static function compare( array $a, array $b ) {
47
		return strnatcmp( $a['label'], $b['label'] );
48
	}
49
50
	/**
51
	 * get
52
	 *
53
	 * Get the array container sorted by label
54
	 * @return array
55
	 */
56
	public function get() {
57
		$arr = $this->arr;
58
59
		usort( $arr, [ __CLASS__, 'compare' ] );
60
61
		return $arr;
62
	}
63
64
	/**
65
	 * encode
66
	 *
67
	 * Encodes object and returns it as a json-string
68
	 * @return string
69
	 */
70
	public function encode() {
71
		return json_encode( $this->get() );
72
	}
73
74
	/**
75
	 * __toString
76
	 *
77
	 * Return the encoded object as a string using the encode-method
78
	 * @uses encode
79
	 * @return string
80
	 */
81
	public function __toString() {
82
		return $this->encode();
83
	}
84
85
}
86