This repository has been archived by the owner on Jan 26, 2021. It is now read-only.
/
textwheel.php
529 lines (477 loc) · 13.5 KB
/
textwheel.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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
<?php
/*
* TextWheel 0.1
*
* let's reinvent the wheel one last time
*
* This library of code is meant to be a fast and universal replacement
* for any and all text-processing systems written in PHP
*
* It is dual-licensed for any use under the GNU/GPL2 and MIT licenses,
* as suits you best
*
* (c) 2009 Fil - fil@rezo.net
* Documentation & http://zzz.rezo.net/-TextWheel-
*
* Usage: $wheel = new TextWheel(); echo $wheel->text($text);
*
*/
require_once dirname(__FILE__)."/textwheelruleset.php";
class TextWheel {
protected $ruleset;
protected static $subwheel = array();
/**
* Constructor
* @param TextWheelRuleSet $ruleset
*/
public function TextWheel($ruleset = null) {
$this->setRuleSet($ruleset);
}
/**
* Set RuleSet
* @param TextWheelRuleSet $ruleset
*/
public function setRuleSet($ruleset){
if (!is_object($ruleset))
$ruleset = new TextWheelRuleSet ();
$this->ruleset = $ruleset;
}
/**
* Apply all rules of RuleSet to a text
*
* @param string $t
* @return string
*/
public function text($t) {
$rules = & $this->ruleset->getRules();
## apply each in order
foreach ($rules as $name => $rule) #php4+php5
{
$this->apply($rules[$name], $t);
}
#foreach ($this->rules as &$rule) #smarter &reference, but php5 only
# $this->apply($rule, $t);
return $t;
}
private function export($x) {
return addcslashes(var_export($x, true), "\n\r\t");
}
public function compile() {
$rules = & $this->ruleset->getRules();
## apply each in order
$comp = array();
foreach ($rules as $name => $rule)
{
$this->initRule($rule);
$r = "/* $name */\n";
if ($rule->require)
$r .= 'require_once '.TextWheel::export($rule->require).';'."\n";
if ($rule->if_str)
$r .= 'if_str('.TextWheel::export($rule->if_str).', $t)'."\n";
if ($rule->if_stri)
$r .= 'if_stri('.TextWheel::export($rule->if_stri).', $t)'."\n";
if ($rule->if_match)
$r .= 'if_match('.TextWheel::export($rule->if_match).', $t)'."\n";
if ($rule->func_replace !== 'replace_identity') {
$fun = 'TextWheel::'.$rule->func_replace;
$r .= '$t = '.$fun.'('.TextWheel::export($rule->match).', '.TextWheel::export($rule->replace).', $t);'."\n";
}
$comp[] = $r;
}
return join ("\n", $comp);
}
/**
* Get an internal global subwheel
* read acces for annymous function only
*
* @param int $n
* @return TextWheel
*/
public static function &getSubWheel($n){
return TextWheel::$subwheel[$n];
}
/**
* Create SubWheel (can be overriden in debug class)
* @param TextWheelRuleset $rules
* @return TextWheel
*/
protected function &createSubWheel(&$rules){
return new TextWheel($rules);
}
/**
* Initializing a rule a first call
* including file, creating function or wheel
* optimizing tests
*
* @param TextWheelRule $rule
*/
protected function initRule(&$rule){
# language specific
if ($rule->require)
require_once $rule->require;
# optimization: strpos or stripos?
if (isset($rule->strpos)) {
if (strtolower($rule->if_str) !== strtoupper($rule->if_str)) {
$rule->if_stri = $rule->if_str;
unset($rule->if_str);
}
}
if ($rule->create_replace){
$rule->replace = create_function('$m', $rule->replace);
$rule->create_replace = false;
$rule->is_callback = true;
}
elseif ($rule->is_wheel){
$n = count(TextWheel::$subwheel);
TextWheel::$subwheel[] = $this->createSubWheel($rule->replace);
$var = '$m['.intval($rule->pick_match).']';
if ($rule->type=='all' OR $rule->type=='str' OR $rule->type=='split' OR !isset($rule->match))
$var = '$m';
$code = 'return TextWheel::getSubWheel('.$n.')->text('.$var.');';
$rule->replace = create_function('$m', $code);
$rule->is_wheel = false;
$rule->is_callback = true;
}
# optimization
$rule->func_replace = '';
if (isset($rule->replace)) {
switch($rule->type) {
case 'all':
$rule->func_replace = 'replace_all';
break;
case 'str':
$rule->func_replace = 'replace_str';
// test if quicker strtr usable
if (!$rule->is_callback
AND is_array($rule->match) AND is_array($rule->replace)
AND $c = array_map('strlen',$rule->match)
AND $c = array_unique($c)
AND count($c)==1
AND reset($c)==1
AND $c = array_map('strlen',$rule->replace)
AND $c = array_unique($c)
AND count($c)==1
AND reset($c)==1
){
$rule->match = implode('',$rule->match);
$rule->replace = implode('',$rule->replace);
$rule->func_replace = 'replace_strtr';
}
break;
case 'split':
$rule->func_replace = 'replace_split';
$rule->match = array($rule->match, is_null($rule->glue)?$rule->match:$rule->glue);
break;
case 'preg':
default:
$rule->func_replace = 'replace_preg';
break;
}
if ($rule->is_callback)
$rule->func_replace .= '_cb';
}
if (!method_exists("TextWheel", $rule->func_replace)){
$rule->disabled = true;
$rule->func_replace = 'replace_identity';
}
# /end
}
/**
* Apply a rule to a text
*
* @param TextWheelRule $rule
* @param string $t
* @param int $count
*/
protected function apply(&$rule, &$t, &$count=null) {
if ($rule->disabled)
return;
if (isset($rule->if_chars) AND (strpbrk($t, $rule->if_chars) === false))
return;
if (isset($rule->if_str) AND strpos($t, $rule->if_str) === false)
return;
if (isset($rule->if_stri) AND stripos($t, $rule->if_str) === false)
return;
if (isset($rule->if_match) AND !preg_match($rule->if_match, $t))
return;
if (!isset($rule->func_replace))
$this->initRule($rule);
$func = $rule->func_replace;
TextWheel::$func($rule->match,$rule->replace,$t,$count);
}
/**
* No Replacement function
* fall back in case of unknown method for replacing
* should be called max once per rule
*
* @param mixed $match
* @param mixed $replace
* @param string $t
* @param int $count
*/
protected static function replace_identity(&$match,&$replace,&$t,&$count){
}
/**
* Static replacement of All text
* @param mixed $match
* @param mixed $replace
* @param string $t
* @param int $count
*/
protected static function replace_all(&$match,&$replace,&$t,&$count){
# special case: replace $0 with $t
# replace: "A$0B" will surround the string with A..B
# replace: "$0$0" will repeat the string
if (strpos($replace, '$0')!==FALSE)
$t = str_replace('$0', $t, $replace);
else
$t = $replace;
}
/**
* Call back replacement of All text
* @param mixed $match
* @param mixed $replace
* @param string $t
* @param int $count
*/
protected static function replace_all_cb(&$match,&$replace,&$t,&$count){
$t = $replace($t);
}
/**
* Static string replacement
*
* @param mixed $match
* @param mixed $replace
* @param string $t
* @param int $count
*/
protected static function replace_str(&$match,&$replace,&$t,&$count){
if (!is_string($match) OR strpos($t,$match)!==FALSE)
$t = str_replace($match, $replace, $t, $count);
}
/**
* Fast Static string replacement one char to one char
*
* @param mixed $match
* @param mixed $replace
* @param string $t
* @param int $count
*/
protected static function replace_strtr(&$match,&$replace,&$t,&$count){
$t = strtr( $t, $match, $replace);
}
/**
* Callback string replacement
*
* @param mixed $match
* @param mixed $replace
* @param string $t
* @param int $count
*/
protected static function replace_str_cb(&$match,&$replace,&$t,&$count){
if (strpos($t,$match)!==FALSE)
if (count($b = explode($match, $t)) > 1)
$t = join($replace($match), $b);
}
/**
* Static Preg replacement
*
* @param mixed $match
* @param mixed $replace
* @param string $t
* @param int $count
*/
protected static function replace_preg(&$match,&$replace,&$t,&$count){
$t = preg_replace($match, $replace, $t, -1, $count);
}
/**
* Callback Preg replacement
* @param mixed $match
* @param mixed $replace
* @param string $t
* @param int $count
*/
protected static function replace_preg_cb(&$match,&$replace,&$t,&$count){
$t = preg_replace_callback($match, $replace, $t, -1, $count);
}
/**
* Static split replacement : invalid
* @param mixed $match
* @param mixed $replace
* @param string $t
* @param int $count
*/
protected static function replace_split(&$match,&$replace,&$t,&$count){
throw new InvalidArgumentException('split rule allways needs a callback function as replace');
}
/**
* Callback split replacement
* @param array $match
* @param mixed $replace
* @param string $t
* @param int $count
*/
protected static function replace_split_cb(&$match,&$replace,&$t,&$count){
$a = explode($match[0], $t);
$t = join($match[1], array_map($replace,$a));
}
}
class TextWheelDebug extends TextWheel {
static protected $t; #tableaux des temps
static protected $tu; #tableaux des temps (rules utilises)
static protected $tnu; #tableaux des temps (rules non utilises)
static protected $u; #compteur des rules utiles
static protected $w; #compteur des rules appliques
static $total;
/**
* Timer for profiling
*
* @staticvar int $time
* @param string $t
* @param bool $raw
* @return int/strinf
*/
protected function timer($t='rien', $raw = false) {
static $time;
$a=time(); $b=microtime();
// microtime peut contenir les microsecondes et le temps
$b=explode(' ',$b);
if (count($b)==2) $a = end($b); // plus precis !
$b = reset($b);
if (!isset($time[$t])) {
$time[$t] = $a + $b;
} else {
$p = ($a + $b - $time[$t]) * 1000;
unset($time[$t]);
if ($raw) return $p;
if ($p < 1000)
$s = '';
else {
$s = sprintf("%d ", $x = floor($p/1000));
$p -= ($x*1000);
}
return $s . sprintf("%.3f ms", $p);
}
}
/**
* Apply all rules of RuleSet to a text
*
* @param string $t
* @return string
*/
public function text($t) {
$rules = & $this->ruleset->getRules();
## apply each in order
foreach ($rules as $name => $rule) #php4+php5
{
if (is_int($name))
$name .= ' '.$rule->match;
$this->timer($name);
$b = $t;
$this->apply($rule, $t);
TextWheelDebug::$w[$name] ++; # nombre de fois appliquee
$v = $this->timer($name, true); # timer
TextWheelDebug::$t[$name] += $v;
if ($t !== $b) {
TextWheelDebug::$u[$name] ++; # nombre de fois utile
TextWheelDebug::$tu[$name] += $v;
} else {
TextWheelDebug::$tnu[$name] += $v;
}
}
#foreach ($this->rules as &$rule) #smarter &reference, but php5 only
# $this->apply($rule, $t);
return $t;
}
/**
* Ouputs data stored for profiling/debuging purposes
*/
public static function outputDebug(){
if (isset(TextWheelDebug::$t)) {
$time = array_flip(array_map('strval', TextWheelDebug::$t));
krsort($time);
echo "
<div class='textwheeldebug'>
<style type='text/css'>
.textwheeldebug table { margin:1em 0; }
.textwheeldebug th,.textwheeldebug td { padding-left: 15px }
.textwheeldebug .prof-0 .number { padding-right: 60px }
.textwheeldebug .prof-1 .number { padding-right: 30px }
.textwheeldebug .prof-1 .name { padding-left: 30px }
.textwheeldebug .prof-2 .name { padding-left: 60px }
.textwheeldebug .zero { color:orange; }
.textwheeldebug .number { text-align:right; }
.textwheeldebug .strong { font-weight:bold; }
</style>
<table class='sortable'>
<caption>Temps par rule</caption>
<thead><tr><th>temps (ms)</th><th>rule</th><th>application</th><th>t/u (ms)</th><th>t/n-u (ms)</th></tr></thead>\n";
foreach($time as $t => $r) {
$applications = intval(TextWheelDebug::$u[$r]);
$total += $t;
if(intval($t*10))
echo "<tr>
<td class='number strong'>".number_format(round($t*10)/10,1)."</td><td> ".htmlspecialchars($r)."</td>
<td"
. (!$applications ? " class='zero'" : "")
.">".$applications."/".intval(TextWheelDebug::$w[$r])."</td>
<td class='number'>".($applications?number_format(round(TextWheelDebug::$tu[$r]/$applications*100)/100,2):"") ."</td>
<td class='number'>".(($nu = intval(TextWheelDebug::$w[$r])-$applications)?number_format(round(TextWheelDebug::$tnu[$r]/$nu*100)/100,2):"") ."</td>
</tr>";
}
echo "</table>\n";
echo "
<table>
<caption>Temps total par rule</caption>
<thead><tr><th>temps</th><th>rule</th></tr></thead>\n";
ksort($GLOBALS['totaux']);
TextWheelDebug::outputTotal($GLOBALS['totaux']);
echo "</table>";
# somme des temps des rules, ne tient pas compte des subwheels
echo "<p>temps total rules: ".round($total)." ms</p>\n";
echo "</div>\n";
}
}
public static function outputTotal($liste, $profondeur=0) {
ksort($liste);
foreach ($liste as $cause => $duree) {
if (is_array($duree)) {
TextWheelDebug::outputTotal($duree, $profondeur+1);
} else {
echo "<tr class='prof-$profondeur'>
<td class='number'><b>".intval($duree)."</b> ms</td>
<td class='name'>".htmlspecialchars($cause)."</td>
</tr>\n";
}
}
}
/**
* Create SubWheel (can be overriden in debug class)
* @param TextWheelRuleset $rules
* @return TextWheel
*/
protected function &createSubWheel(&$rules){
return new TextWheelDebug($rules);
}
}
/**
* stripos for php4
*/
if (!function_exists('stripos')) {
function stripos($haystack, $needle) {
return strpos($haystack, stristr( $haystack, $needle ));
}
}
/**
* approximation of strpbrk for php4
* return false if no char of $char_list is in $haystack
*/
if (!function_exists('strpbrk')) {
function strpbrk($haystack, $char_list) {
$result = strcspn($haystack, $char_list);
if ($result != strlen($haystack)) {
return $result;
}
return false;
}
}