1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Nucleus - XMPP Library for PHP |
4
|
|
|
* |
5
|
|
|
* Copyright (C) 2016, Some rights reserved. |
6
|
|
|
* |
7
|
|
|
* @author Kacper "Kadet" Donat <[email protected]> |
8
|
|
|
* |
9
|
|
|
* Contact with author: |
10
|
|
|
* Xmpp: [email protected] |
11
|
|
|
* E-mail: [email protected] |
12
|
|
|
* |
13
|
|
|
* From Kadet with love. |
14
|
|
|
*/ |
15
|
|
|
|
16
|
|
|
namespace Kadet\Xmpp\Utils; |
17
|
|
|
|
18
|
|
|
use Kadet\Highlighter\Utils\Console; |
19
|
|
|
|
20
|
|
|
class Dumper |
21
|
|
|
{ |
22
|
|
|
use Singleton; |
23
|
|
|
|
24
|
|
|
/** @var callable[string] */ |
25
|
|
|
private $_dumpers; |
26
|
|
|
|
27
|
|
|
public function register(string $class, callable $dumper) |
28
|
|
|
{ |
29
|
|
|
$this->_dumpers[$class] = $dumper; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
public function dump($value) |
33
|
|
|
{ |
34
|
|
|
return trim(($this->getDumper($value))($value)); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
private function getDumper($value) |
38
|
|
|
{ |
39
|
|
|
if (is_object($value)) { |
40
|
|
|
$class = get_class($value); |
41
|
|
|
foreach (array_merge([$class], class_parents($class), class_implements($class)) as $class) { |
42
|
|
|
if (isset($this->_dumpers[$class])) { |
43
|
|
|
return $this->_dumpers[$class]; |
44
|
|
|
} |
45
|
|
|
} |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
if (isset($this->_dumpers[gettype($value)])) { |
49
|
|
|
return $this->_dumpers[gettype($value)]; |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
return [$this, '_dumpDefault']; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
private function _dumpDefault($value) |
56
|
|
|
{ |
57
|
|
|
return helper\format('{type} {value}', [ |
58
|
|
|
'type' => Console::get()->styled(['color' => 'red'], \Kadet\Xmpp\Utils\helper\typeof($value)), |
59
|
|
|
'value' => var_export($value, true) |
60
|
|
|
]); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
private function _dumpObject($value) |
64
|
|
|
{ |
65
|
|
|
ob_start(); |
66
|
|
|
var_dump($value); |
67
|
|
|
|
68
|
|
|
return trim(ob_get_flush()); |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
private function _dumpArray(array $array) |
72
|
|
|
{ |
73
|
|
|
$console = Console::get(); |
74
|
|
|
|
75
|
|
|
$result = $console->styled(['color' => 'yellow'], 'array').' with '.$console->styled(['color' => 'magenta'], count($array)).' elements:'.PHP_EOL; |
76
|
|
|
foreach ($array as $key => $value) { |
77
|
|
|
$result .= "\t".str_replace("\n", "\n\t", '['.$this->dump($key).']: '.$this->dump($value)).PHP_EOL; |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
return $result; |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
public function init() |
84
|
|
|
{ |
85
|
|
|
$this->register('array', [$this, '_dumpArray']); |
86
|
|
|
$this->register('object', [$this, '_dumpObject']); |
87
|
|
|
} |
88
|
|
|
} |
89
|
|
|
|