-
Notifications
You must be signed in to change notification settings - Fork 1
/
TreeView.php
147 lines (127 loc) · 3.09 KB
/
TreeView.php
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
<?php
namespace iutbay\yii2bootstrap;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\helpers\Json;
use yii\helpers\Url;
use iutbay\yii2fontawesome\FontAwesome as FA;
/**
* TreeView widget
* @author Kevin LEVRON <[email protected]>
*/
class TreeView extends \yii\base\Widget
{
/**
* Items
* @var array
*/
public $items;
/**
* @var string
*/
public $itemLabelAttribute = 'label';
/**
* @var string
*/
public $itemChildrenAttribute = 'items';
/**
* @var \Closure
*/
public $renderItemLabel;
/**
* List selector
* @var string
*/
public $listSelector;
/**
* Treeview client options
* @var array
*/
public $clientOptions = [];
/**
* @inheritdoc
*/
public function run()
{
echo $this->renderItems();
$this->registerClientScript();
}
/**
* Render items
* @return type
*/
public function renderItems()
{
return $this->renderUL($this->items, ['id' => $this->getId()]);
}
/**
* Register js
*/
public function registerClientScript()
{
$view = $this->getView();
TreeViewAsset::register($view);
$id = $this->listSelector === null ? '#' . $this->getId() : $this->listSelector;
$options = Json::encode($this->clientOptions);
$view->registerJs("jQuery('{$id}').treeview($options);");
}
/**
* Render ul
* @param array $items
* @param array $options
* @return string
*/
public function renderUL($items, $options = [])
{
if (!is_array($items) || count($items) === 0)
return;
$lis = '';
foreach ($items as $item) {
$lis.= $this->renderLI($item);
}
return Html::tag('ul', $lis, $options);
}
/**
* Render li
* @param mixed $item
* @param array $options
* @return string
*/
public function renderLI($item, $options = [])
{
if ($this->renderItemLabel instanceof \Closure) {
$li = call_user_func($this->renderItemLabel, $item);
} else {
$li = $this->getItemLabel($item);
}
$li.= $this->renderUL($this->getItemChildren($item));
return Html::tag('li', $li, $options);
}
/**
* @param mixed $item
* @return string
*/
public function getItemLabel($item)
{
return $this->getItemAttribute($item, $this->itemLabelAttribute);
}
/**
* @param mixed $item
* @return array
*/
public function getItemChildren($item)
{
return $this->getItemAttribute($item, $this->itemChildrenAttribute);
}
/**
* @param mixed $item
* @return array
*/
public function getItemAttribute($item, $attribute)
{
if (is_array($item))
return $item[$attribute];
if (is_object($item))
return $item->{$attribute};
}
}