This repository has been archived by the owner on Jan 17, 2018. It is now read-only.
/
ImpTable.php
executable file
·279 lines (231 loc) · 9.06 KB
/
ImpTable.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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
<?php
/*
Simple HTML table generation using YUI DataTable
Basic Usage:
$IT = new ImpTable($data_array);
$IT->generate();
Customization:
$IT->Caption = "My ImpTable!";
$IT->Attributes['id'] = 'My_Custom_CSS_ID';
$QueryTable->AutoSort('aColumn', 'Descending');
$QueryTable->ColumnHeaders = array(
'aColumn' => array('text' => 'Column Name', 'type'=> 'number', 'sortable' => true, 'formatter' => 'myCustomYUIFormatter'),
);
See http://improbable.org/chris/Software/ImpPHP/ImpTable/ for more information.
*/
class ImpTable {
public $Data = array();
public $Attributes = array('class' => 'ImpTable');
public $DefaultSortOrder = 'Ascending';
public $DefaultSortKey;
public $JSRenderQueue = 'ImpTable_Generators'; // This is the name of the JavaScript array which we will add the renderer for the table to
public $JSRendererName = 'ImpTable_Renderer';
public $yuiDataTableOptions = array();
private $_dataType = 'internal';
private $_dataSource;
private $_dataSourceOptions;
private $_SortKey;
private $_SortOrder;
/*
This variable is used to control whether the necessary JavaScript
libraries have been included. If true ImpTable assumes that the
YUI DataTable and DataSource are ready to use.
*/
protected static $JS_Initialized = false;
function ImpTable(array $Data = array()) {
$this->Data = array_values($Data);
}
function AutoSort($Key = false, $Order = false) {
assert(is_array($this->Data));
if (empty($this->Data)) return;
if (!empty($this->_autoSorted)) return;
$this->_autoSorted = true;
$this->_SortOrder = $this->DefaultSortOrder == 'Descending' ? 'Descending' : 'Ascending';
$this->_SortKey = !empty($this->DefaultSortKey) ? $this->DefaultSortKey : current(array_keys(reset($this->Data)));
assert(array_key_exists($this->_SortKey, reset($this->Data)));
reset($this->Data);
if (!empty($this->_SortKey) and array_key_exists($this->_SortKey, current($this->Data))) {
usort($this->Data, array($this, ($this->_SortOrder == "Ascending" ? "_compare" : "_reverse_compare")));
}
}
protected function _compare($k1, $k2) {
return strnatcasecmp($k1[$this->_SortKey], $k2[$this->_SortKey]);
}
protected function _reverse_compare($k1, $k2) {
return strnatcasecmp($k2[$this->_SortKey], $k1[$this->_SortKey]);
}
function __get($p) {
switch($p) {
case "ColumnHeaders":
if (!empty($this->ColumnHeaders)) {
return $this->ColumnHeaders;
} elseif ($this->_dataType == 'internal') {
return array_combine(array_keys(reset($this->Data)), array_keys(reset($this->Data)));
} elseif (!empty($this->_dataSourceOptions['fields'])) {
return array_combine(array_values($this->_dataSourceOptions['fields']), array_values($this->_dataSourceOptions['fields']));
}
throw new RuntimeException("ColumnHeaders has not been defined and there is no data source to generate it from!");
default:
return $this->$p;
}
}
function generate() {
if (!ImpTable::$JS_Initialized) {
$this->initializeJavaScriptEnvironment();
}
if (empty($this->Attributes['id'])) {
$this->Attributes['id'] = uniqid('ImpTable_');
}
$this->JSName = $this->Attributes['id'];
assert(preg_match('/^\w+$/', $this->JSName)); // The list of safe CSS and JavaScript names is extremely similar so we leave it up to the developer to pick a valid name
$attrs = array();
foreach ($this->Attributes as $k => $v) {
$attrs[] = "$k=\"$v\"";
}
echo '<div ', implode(" ", $attrs), '></div>';
$this->generateDataSource();
?>
<script type="text/javascript">//<![CDATA[
<?=$this->JSRenderQueue?>.push(function () {
<?=$this->JSName?>_DataTable = new YAHOO.widget.DataTable(
document.getElementById('<?=$this->JSName?>'),
<?=json_encode($this->getYUIColumnDefinitions())?>,
<?=$this->JSDataSourceName?>,
<?=json_encode($this->getYUIDataTableOptions())?>
);
});
//]]>
</script>
<?
flush();
}
protected function generateDataSource() {
if (empty($this->JSDataSourceName)) {
$this->JSDataSourceName = $this->JSName . "_DataSource";
}
switch ($this->_dataType) {
case 'datasource':
break;
case 'internal':
$this->generateInternalDataSource();
break;
case 'xml':
case 'json':
case 'text':
$this->generateExternalDataSource();
break;
default:
throw new InvalidArgumentException("useData() called with unknown data type: {$this->_dataType}");
}
flush(); // Large data sources may take time to process and we want remote ones to start loading as quickly as possible
}
private function generateInternalDataSource() {
assert(is_array($this->Data));
if (empty($this->Data)) {
return;
}
reset($this->Data);
if (!is_array(current($this->Data))) {
throw new InvalidArgumentException(__CLASS__ . '->Data is not a two-dimensional array!');
}
// This is currently necessary because YUI DataSources assume associative arrays and will display '[Object object]' for the value of a numeric array:
if (isset($this->Data[0][0])) {
$this->makeDataYUISafe();
}
?>
<script type="text/javascript">//<![CDATA[
<?=$this->JSRenderQueue?>.push(function () {
<?=$this->JSDataSourceName?> = new YAHOO.util.DataSource(<?=json_encode($this->Data)?>);
<?=$this->JSDataSourceName?>.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
<?=$this->JSDataSourceName?>.responseSchema = { fields: ["<?=implode(array_keys($this->ColumnHeaders), '","')?>"] };
});
//]]>
</script>
<?php
}
private function generateExternalDataSource() {
assert(!empty($this->_dataType));
assert(!empty($this->_dataSource));
assert(!empty($this->_dataSourceOptions));
switch ($this->_dataType) {
case 'xml': $dsType = 'TYPE_XML'; break;
case 'json': $dsType = 'TYPE_JSON'; break;
case 'text': $dsType = 'TYPE_TEXT'; break;
default: throw new InvalidArgumentException("generateExternalDataSource() called with unknown data type: {$this->_dataType}");
}
$ds = $this->_dataSource;
if (strpos('?', $ds) === FALSE) $ds .= '?'; // We'll avoid messing with existing query strings but help the user out if they forgot to begin one
?>
<script type="text/javascript">//<![CDATA[
<?=$this->JSRenderQueue?>.push(function () {
<?=$this->JSDataSourceName?> = new YAHOO.util.DataSource(<?=json_encode($ds)?>);
<?=$this->JSDataSourceName?>.responseType = YAHOO.util.DataSource.<?=$dsType?>;
<?=$this->JSDataSourceName?>.responseSchema = <?=json_encode($this->_dataSourceOptions)?>;
});
//]]>
</script>
<?php
}
public function useData($type, $source, $args = array()) {
$this->_dataType = strtolower($type);
$this->_dataSource = $source;
$this->_dataSourceOptions = $args;
if ($this->_dataType == "datasource") {
$this->JSDataSourceName = $source;
}
}
protected function makeDataYUISafe() {
$formatKey = create_function('$s', 'return "Column " . ($s + 1);');
foreach ($this->Data as $k => $v) {
$this->Data[$k] = array_combine(array_map($formatKey, array_keys($v)), array_values($v));
}
}
protected function getYUIColumnDefinitions() {
$Columns = array();
foreach ($this->ColumnHeaders as $name => $display) {
$def = array('key' => $name, 'sortable' => true);
if (is_array($display)) {
$def = array_merge($def, $display);
}
$Columns[] = $def;
}
return $Columns;
}
protected function getYUIDataTableOptions() {
if (!empty($this->Caption) and empty($this->yuiDataTableOptions['caption'])) {
$this->yuiDataTableOptions['caption'] = $this->Caption;
}
if (!empty($this->DefaultSortKey) and empty($this->yuiDataTableOptions['sortedBy'])) {
$this->yuiDataTableOptions['sortedBy'] = array('colKey' => $this->DefaultSortKey, 'dir' => $this->DefaultSortOrder == 'Ascending' ? 'asc' : 'desc');
}
return $this->yuiDataTableOptions;
}
public function initializeJavaScriptEnvironment() {
ImpTable::$JS_Initialized = true;
?>
<script type="text/javascript" charset="utf-8">//<![CDATA[
if (!window.YAHOO || !YAHOO.util || !YAHOO.util.YUILoader) {
document.write(unescape('%3Cscript%20type%3D%22text%2Fjavascript%22%20src%3D%22http%3A%2F%2Fyui.yahooapis.com%2F2.5.1%2Fbuild%2Fyuiloader%2Fyuiloader-beta-min.js%22%3E%3C%2Fscript%3E'));
}
//]]>
</script>
<script type="text/javascript" charset="utf-8">//<![CDATA[
<?=$this->JSRenderQueue?> = new Array();
<?=$this->JSRendererName?> = function() { while(f = <?=$this->JSRenderQueue?>.shift()){ f(); }; };
if (!(window.YAHOO && YAHOO.widget && YAHOO.widget.DataTable && YAHOO.util && YAHOO.util.DataSource)) {
ImpTable_Loader = new YAHOO.util.YUILoader({
require: ['datatable', 'datasource'],
loadOptional:true,
onSuccess:<?=$this->JSRendererName?>
});
ImpTable_Loader.insert();
} else {
YAHOO.util.Event.onDOMReady(<?=$this->JSRendererName?>);
}
//]]>
</script>
<?
flush();
}
}
?>