Passed
Push — master ( f10a02...88f473 )
by 世昌
01:41
created

AttachTrait::addAttribute()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
namespace nebula\component\debug\attach;
3
4
/**
5
 * 多行附加属性
6
 */
7
trait AttachTrait
8
{
9
    /**
10
     * 属性数组
11
     *
12
     * @var array
13
     */
14
    protected $attribute=[];
15
    
16
    public function addAttribute(array $value)
17
    {
18
        $this->attribute = array_merge($this->attribute, $value);
19
    }
20
21
    protected function analyse(array $context)
22
    {
23
        $replace = [];
24
        $attach  =[] ;
25
        foreach ($context as $key => $val) {
26
            if (!is_array($val) && (!is_object($val) || method_exists($val, '__toString')) && ! $val instanceof \Exception) {
27
                $replace['{' . $key . '}'] = $val;
28
            } else {
29
                $attach[$key] = $val;
30
            }
31
        }
32
        return [$attach, $replace];
33
    }
34
35
    public function interpolate(string $message, array $context, array $attribute)
36
    {
37
        list($attach, $replace) =  $this->analyse($context);
38
        $attribute = array_merge($this->attribute, $attribute);
39
        foreach ($attribute as $key => $val) {
40
            $replace['%' . $key . '%'] = $val;
41
        }
42
        $message = strtr($message, $replace);
43
        $attachInfo = '';
44
        foreach ($attach as $name => $value) {
45
            $attachInfo = $name.' = ';
46
            if ($value instanceof AttachValueInterface) {
47
                $attachInfo.= $value->getLogAttach().PHP_EOL;
48
            } else {
49
                $attachInfo.= DumpTrait::parameterToString($value).PHP_EOL;
50
            }
51
        }
52
        if (strlen($attachInfo) > 0) {
53
            return $message.PHP_EOL.$attachInfo;
54
        }
55
        return $message;
56
    }
57
}
58