Formatter.php
1.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
<?php
namespace AC\Helper\Select;
use AC\ArrayIterator;
abstract class Formatter extends ArrayIterator {
/**
* @var Entities
*/
private $entities;
/**
* @var Value
*/
protected $value;
public function __construct( Entities $entities, Value $value = null ) {
$this->entities = $entities;
$this->value = $value;
parent::__construct( $this->get_labels() );
}
/**
* @return Entities
*/
public function get_entities() {
return $this->entities;
}
/**
* @param $value
*
* @return mixed
*/
public function get_entity( $value ) {
if ( ! $this->entities->has_offset( $value ) ) {
return false;
}
return $this->entities->get_offset( $value );
}
/**
* @return Option[]
*/
protected function get_labels() {
$labels = [];
foreach ( $this->entities as $value => $entity ) {
$labels[ $value ] = $this->get_label( $entity );
}
if ( $this->value ) {
$labels = $this->get_labels_unique( $labels );
}
return $this->get_options( $labels );
}
/**
* @param $entity
*
* @return string
*/
protected abstract function get_label( $entity );
/**
* @param array $labels
*
* @return array
*/
protected function get_labels_unique( array $labels ) {
$duplicates = array_diff_assoc( $labels, array_unique( $labels ) );
foreach ( $labels as $value => $label ) {
if ( ! in_array( $label, $duplicates ) ) {
continue;
}
$labels[ $value ] = $this->get_label_unique( $label, $this->get_entity( $value ) );
}
return $labels;
}
/**
* @param string $label
* @param mixed $entity
*
* @return string
*/
protected function get_label_unique( $label, $entity ) {
return $label . sprintf( ' (%s)', $this->value->get_value( $entity ) );
}
/**
* @param array $labels
*
* @return Option[]
*/
private function get_options( array $labels ): array {
$options = [];
foreach ( $labels as $value => $label ) {
$options[] = new Option( $value, $label );
}
return $options;
}
}