-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNode.php
More file actions
590 lines (488 loc) · 17.9 KB
/
Node.php
File metadata and controls
590 lines (488 loc) · 17.9 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
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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
<?php
namespace Onimla\HTML;
use ArrayIterator;
use Countable;
use IteratorAggregate;
use Serializable;
/**
* An HTML node.
*
* @author AlminoMelo at gmail.com
*/
class Node implements Countable, IteratorAggregate, Serializable {
/**
* String to put before the instance string
* @var string
*/
public $before;
/**
* String to put after the instance string
* @var string
*/
public $after;
/**
* @var array
*/
protected $children = array();
/**
* Whether or not to store actions in a log
* @var boolean
*/
public static $log = FALSE;
/**
* Prints pretty source-code
* @var boolean
*/
public $indentSource = FALSE;
const TAB = " ";
public function __construct($children = FALSE) {
self::log('Created new instance of `' . get_class($this) . '`.', TRUE);
$children = self::filterChildren(func_get_args());
if (count($children)) {
call_user_func_array(array($this, 'append'), $children);
}
}
public function __destruct() {
self::log('Destroyed instance of `' . get_class($this) . '`.', TRUE);
}
public function __get($name) {
self::log("Using magical method to GET a child named `{$name}`.", TRUE);
if (array_key_exists($name, $this->children)) {
return $this->children[$name];
}
$trace = debug_backtrace();
trigger_error(
'Undefined property via __get(): ' . $name .
' in ' . $trace[0]['file'] .
' on line ' . $trace[0]['line'], E_USER_NOTICE);
return FALSE;
}
public function __set($name, $value) {
self::log("Using magical method to SET a child named `{$name}`.", TRUE);
$this->children[$name] = $value;
}
public function __unset($name) {
self::log("Using magical method to UNSET a child named `{$name}`.", TRUE);
unset($this->children[$name]);
}
public function __isset($name) {
return isset($this->children[$name]);
}
/**
* Don't forget to update references to sub trees.
*/
public function __clone() {
$new = array();
foreach ($this->children as $key => $child) {
if (is_object($child)) {
$new[$key] = clone $child;
} else {
$new[$key] = $child;
}
}
$this->children = $new;
}
public function __toString() {
self::log('Casting instance of ' . get_class($this) . ' to `string`.', TRUE);
$glue = $this->indentSource ? $this->after . PHP_EOL . $this->before : "{$this->after}{$this->before}";
return $this->before . implode($glue, $this->children) . $this->after;
}
public function count() {
return count($this->children);
}
public function length() {
return $this->count();
}
public function countChildren() {
return $this->count();
}
public function getIterator() {
return new ArrayIterator($this->children);
}
public function serialize() {
return serialize(array(
$this->before,
$this->after,
$this->children,
));
}
public function unserialize($serialized) {
list(
$this->before,
$this->after,
$this->children,
) = unserialize($serialized);
}
/**
* Same as PHP's <code>array_merge</code>
* @param self|array $arrayOrInstance As many as you want
*/
public function merge($arrayOrInstance) {
foreach (self::arrayFlatten(func_get_args()) as $arrayOrInstance) {
if ($arrayOrInstance instanceof self) {
$arrayOrInstance = $arrayOrInstance->getChildren();
}
if (count($arrayOrInstance) > 0) {
call_user_func_array(array($this, 'append'), $arrayOrInstance);
}
}
}
public function getChildren() {
return $this->children;
}
public function eq($index) {
# Reseta as chaves/índices dos filhos
$temp = array_values($this->children);
if (key_exists($index, $temp)) {
return $temp[$index];
}
return FALSE;
}
public function index($index) {
if (key_exists($index, $this->children)) {
return $this->children[$index];
}
return FALSE;
}
protected final function addChildren($children) {
# Reduz todos os elementos passados para a função a um array de uma dimensão
$children = self::filterChildren(func_get_args());
foreach ($children as $child) {
$this->children[] = ($child instanceof self) ? $child : (string) $child;
}
array_merge($this->children, array_map(function ($child) {
return ($child instanceof self) ? $child : (string) $child;
}, $children));
}
protected function unshiftChildren($children) {
# Reduz todos os elementos passados para a função a um array de uma dimensão
$children = self::arrayFlatten(func_get_args());
# Coloca o parâmetro no início do array
array_unshift($this->children, ...$children);
# !!! Não precisa reatribuir $this->children
}
public function prepend($children) {
$this->unshiftChildren(...func_get_args());
return $this;
}
public function prependTo($parent) {
foreach (self::arrayFlatten(func_get_args()) as $parent) {
if (method_exists($parent, 'prepend')) {
$parent->prepend($this);
}
}
return $this;
}
public function append($children) {
$this->addChildren(...func_get_args());
return $this;
}
public function appendTo($parent) {
foreach (self::arrayFlatten(func_get_args()) as $parent) {
if (method_exists($parent, 'append')) {
$parent->append($this);
}
}
return $this;
}
public function removeChild($grandchildren) {
# Se não há filhos, nada a fazer
if ($this->length() < 1) {
self::log("No child at \"{$this->path()}\"", TRUE);
return FALSE;
}
# Retorno padrão
$removed = new Node();
# Percorre os parâmetros recebidos
foreach (self::arrayFlatten(func_get_args()) as $c) {
if (is_bool($c) AND function_exists('log_hr') AND function_exists('log_backtrace')) {
self::log('No booleans accepted here!', TRUE, 'error');
continue;
}
# Procura nos filhos
$key = array_search($c, $this->children);
# Se encontrar
if ($key !== FALSE) {
# Coloca o filho no array
$removed->append($this->children[$key]);
if (method_exists($this->children[$key], 'unsetParent')) {
# Remove o elemento pai
$this->children[$key]->unsetParent();
}
# Remove o filho do array
unset($this->children[$key]);
self::log((is_object($c) AND method_exists($c, 'path') ? "\"{$c->path()}\"" : "`{$c}`") . ' REMOVED from `' . get_class($this) . '`');
} else {
self::log((is_object($c) AND method_exists($c, 'path') ? "\"{$c->path()}\"" : "`{$c}`") . ' NOT FOUND in `' . get_class($this) . '`');
}
# Procura nos netos
foreach ($this->children as $child) {
# Só pergunta aos netos que tem o método removeChild();
if (is_object($child) AND method_exists($child, __FUNCTION__)) {
# Faz o que foi feito acima
$grandchildren = $child->removeChild($c);
# Junta os dois arrays, caso encontre algum neto para remover
if ($grandchildren !== FALSE AND $grandchildren->length() > 0) {
$removed->merge($grandchildren);
}
}
}
}
return $removed;
}
/**
* Remove children and return it
* @return array
*/
public function removeChildren() {
$children = $this->children;
$this->children = array();
return $children;
}
/**
* Get or replace first child
* @param string|self $child As many as you want
* @return string|self The first child before replacement
*/
public function first($child = FALSE) {
/*
# Garante que estamos trabalhando com o primeiro filho
reset($this->children);
*/
# Caso redefinir o primeiro filho
if (func_num_args() > 0) {
/*
# Pega a chave do priemiro filho
$key = key($this->children);
# Coloca o filho na primeira posição do array
$this->children[$key] = $child;
# Method chaining
return $this;
*/
# Armazena temporariamente e remove o primeiro filho
$temp = array_shift($this->children);
# Coloca os filhos no início do array
call_user_func_array(array($this, 'prepend'), func_get_args());
return $temp;
}
/*
# Verifica se há algum filho
if (!empty($this->children)) {
switch ($output) {
case 'html':
# Pode ser usado para debug da instância, por exemplo
return htmlentities(current($this->children));
case 'string':
case 'str':
# Por algum motivo, você quer chamar o método __toString da instância
return (string) current($this->children);
default:
# Retorna o primeiro filho do jeito que ele é
return current($this->children);
}
}
*/
# Garante que estamos trabalhando com o primeiro filho
reset($this->children);
# Retorna o primeiro filho do jeito que ele é
return current($this->children);
/*
# Caso tudo dê errado
return FALSE;
*/
}
/**
* Get or replace last child
* @param string|self $child As many as you want
* @return string|self The last child before replacement
*/
public function last($child = FALSE) {
/*
if (!empty($this->children)) {
# Garante que estamos trabalhando com o último filho
end($this->children);
}
*/
# Caso redefinir o último filho
if (func_num_args() > 0) {
/*
# Caso não haja filhos, o primeiro também é o último
$key = empty($this->children) ? 0 : key($this->children);
# Redefine o último filho
$this->children[$key] = $child;
*/
# Armazena temporariamente e remove o último filho
$temp = array_pop($this->children);
# Coloca os filhos no final do array
call_user_func_array(array($this, 'append'), func_get_args());
return $temp;
}
/*
# Verifica se há algum filho
if (!empty($this->children)) {
switch ($output) {
case 'encode':
case 'html':
# Pode ser usado para debug da instância, por exemplo
return htmlentities(end($this->children));
case 'string':
case 'str':
# Por algum motivo, você quer chamar o método __toString da instância
return (string) end($this->children);
default:
# Retorna o último filho do jeito que ele é
return end($this->children);
}
}
*/
# Garante que estamos trabalhando com o último filho
end($this->children);
# Retorna o último filho do jeito que ele é
return end($this->children);
}
public function isChild($child) {
/*
if (!count($this->children)) {
return FALSE;
}
*/
$found = in_array($child, $this->children);
# Caso não seja filho desta instância
if (!$found) {
# Pergunta aos filhos desta instância
foreach ($this->children as $c) {
# Verifica se o método existe na instância
if (method_exists($c, 'isChild')) {
$found = $c->isChild($child);
# Se encontrar
if ($found) {
return TRUE;
}
}
}
}
# Caso tenha encontrado
return $found;
}
/**
*
* @param callable|string $callable e.g. function ($instance) { $instance->trim(); }
* @param array $params optional
* @return self
*/
public function each($callableOrMethod, $params = FALSE) {
$parameters = func_get_args();
# Remove o primeiro parâmetro passado para a função
array_shift($parameters);
foreach ($this->children as &$child) {
if (get_class($child) == self::class) {
call_user_func_array(array($child, __FUNCTION__), func_get_args());
} elseif (is_string($callableOrMethod) AND method_exists($child, $callableOrMethod)) {
call_user_func_array(array($child, $callableOrMethod), $parameters);
} elseif (is_callable($callableOrMethod)) {
$callableOrMethod($child);
}
}
return $this;
}
/**
* Recursively reduces deep arrays to single-dimensional arrays
* @see http://php.net/manual/pt_BR/function.array-values.php#77671
* @param array $array
* @param int $preserve_keys (0=>never, 1=>strings, 2=>always)
* @param array $newArray
* @return array
*/
public static function arrayFlatten($array, $preserve_keys = 0, &$newArray = Array()) {
foreach (new \ArrayIterator($array) as $key => $child) {
if ($child instanceof \stdClass) {
$child = (array) $child;
}
if (is_array($child)) {
$newArray = self::arrayFlatten($child, $preserve_keys, $newArray);
$newArray = & $newArray;
} elseif ($preserve_keys + is_string($key) > 1) {
$newArray[$key] = $child;
} else {
$newArray[] = $child;
}
}
return $newArray;
}
public static function log($message, $showCaller = FALSE, $debugBacktrace = FALSE) {
if (self::$log) {
$dir = __DIR__ . DIRECTORY_SEPARATOR . 'logs';
$class = str_replace('\\', '-', __CLASS__);
$date = date('Y-m-d');
$timestamp = $date . date(' H:i:s -- ');
$caller = NULL;
$destination = $dir . DIRECTORY_SEPARATOR . "{$date}_{$class}.log";
$message = implode(PHP_EOL . str_repeat(' ', strlen($timestamp)), explode(PHP_EOL, $message));
if ($showCaller) {
$trace = ($debugBacktrace === FALSE) ? debug_backtrace() : $debugBacktrace;
$trace = (object) $trace[1];
$caller = (property_exists($trace, 'class') ? $trace->class . $trace->type : NULL)
. $trace->function . ' »»» ';
#var_dump($trace->file);
#var_dump(str_replace('\\', '/', $trace->class));
#var_dump(strstr($trace->file, str_replace('\\', '/', $trace->class)));
# Log file name if it differs from class name
if (property_exists($trace, 'file') AND strstr($trace->file, str_replace('\\', DIRECTORY_SEPARATOR, $trace->class)) === FALSE) {
# Try to remove unecessary stuff from path string
$filename = trim(substr($trace->file, strlen(__DIR__)), DIRECTORY_SEPARATOR) . ':' . $trace->line . PHP_EOL . str_repeat(' ', strlen($timestamp));
#var_dump($filename);
#var_dump($caller);
#var_dump($message);
$message = implode(PHP_EOL . str_repeat(' ', strlen($caller) - 3), explode(PHP_EOL, $message));
$caller = $filename . $caller;
}
#var_dump($caller . $message);
}
/*
echo '<pre>';
echo $timestamp;
echo $caller;
echo $message;
echo '</pre>';
die();
*/
# Creates a file, if it does not exists
if (!file_exists($destination)) {
mkdir($dir, 0755, TRUE);
}
return error_log($timestamp . $caller . trim($message) . PHP_EOL, 3, $destination);
#return file_put_contents($filename, $message, FILE_APPEND);
} else {
return TRUE;
}
}
/**
* Return an array without NULLs, FALSEs and empty strings.
* @param mixed $children
* @return array
*/
public static function filterChildren($children) {
# Can't use strlen. It will throw errors when working
# with any other types like arrays and objects.
return array_filter(self::arrayFlatten(func_get_args()), function($val) {
return ($val !== NULL AND $val !== FALSE AND $val !== '');
});
}
/**
* Add a <code>data-</code> parameter to each \Onimla\HTML\Element to identify the key used
* @param Node $instance
*/
public static function debug(self $instance) {
foreach (self::arrayFlatten(func_get_args()) as $instance) {
foreach ($instance as $key => $child) {
if (is_object($child)) {
if (method_exists($child, 'data')) {
$child->data('node:key', $key);
} elseif ($child instanceof Node) {
self::debug($child);
}
}
}
}
}
}