Completed
Push — master ( 528f7d...f4b721 )
by Kacper
04:19
created

Dumper::getDumper()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
cc 5
eloc 9
nc 5
nop 1
dl 0
loc 17
rs 8.8571
c 0
b 0
f 0
ccs 0
cts 9
cp 0
crap 30
1
<?php
2
/**
3
 * XMPP Library
4
 *
5
 * Copyright (C) 2016, Some right 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
19
use Kadet\Highlighter\Utils\Console;
20
21
class Dumper
22
{
23
    use Singleton;
24
25
    /** @var callable[string] */
26
    private $_dumpers;
27
28
    public function register(string $class, callable $dumper)
29
    {
30
        $this->_dumpers[$class] = $dumper;
31
    }
32
33
    public function dump($value)
34
    {
35
        return trim(($this->getDumper($value))($value));
36
    }
37
38
    private function getDumper($value)
39
    {
40
        if(is_object($value)) {
41
            $class = get_class($value);
42
            foreach (array_merge([$class], class_parents($class), class_implements($class)) as $class) {
43
                if(isset($this->_dumpers[$class])) {
44
                    return $this->_dumpers[$class];
45
                }
46
            }
47
        }
48
49
        if(isset($this->_dumpers[gettype($value)])) {
50
            return $this->_dumpers[gettype($value)];
51
        }
52
53
        return [$this, '_dumpDefault'];
54
    }
55
56
    private function _dumpDefault($value)
57
    {
58
        return helper\format('{type} {value}', [
59
            'type'  => Console::get()->styled(['color' => 'red'], \Kadet\Xmpp\Utils\helper\typeof($value)),
60
            'value' => var_export($value, true)
61
        ]);
62
    }
63
64
    private function _dumpObject($value)
65
    {
66
        ob_start();
67
            var_dump($value);
1 ignored issue
show
Security Debugging Code introduced by
var_dump($value); looks like debug code. Are you sure you do not want to remove it? This might expose sensitive data.
Loading history...
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