Passed
Push — render-xml ( 61b7f8 )
by Colin
02:12
created

FallbackNodeXmlRenderer::isValueUsable()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
c 1
b 0
f 0
cc 4
nc 4
nop 1
crap 4
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the league/commonmark package.
7
 *
8
 * (c) Colin O'Dell <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace League\CommonMark\Xml;
15
16
use League\CommonMark\Node\Block\AbstractBlock;
17
use League\CommonMark\Node\Inline\AbstractInline;
18
use League\CommonMark\Node\Node;
19
20
/**
21
 * @internal
22
 */
23
final class FallbackNodeXmlRenderer implements XmlNodeRendererInterface
24
{
25
    /**
26
     * @var array<string, string>
27
     *
28
     * @psalm-allow-private-mutation
29
     */
30
    private $classCache = [];
31
32
    /**
33
     * @psalm-allow-private-mutation
34
     */
35 3
    public function getXmlTagName(Node $node): string
36
    {
37 3
        $className = \get_class($node);
38 3
        if (isset($this->classCache[$className])) {
39
            return $this->classCache[$className];
40
        }
41
42 3
        $type      = $node instanceof AbstractBlock ? 'block' : 'inline';
43 3
        $shortName = \strtolower((new \ReflectionClass($node))->getShortName());
44
45 3
        return $this->classCache[$className] = \sprintf('custom_%s_%s', $type, $shortName);
46
    }
47
48
    /**
49
     * {@inheritDoc}
50
     */
51 3
    public function getXmlAttributes(Node $node): array
52
    {
53 3
        $attrs = [];
54 3
        foreach ($node->data->export() as $k => $v) {
55 3
            if (self::isValueUsable($v)) {
56
                $attrs[$k] = $v;
57
            }
58
        }
59
60 3
        $reflClass = new \ReflectionClass($node);
61 3
        foreach ($reflClass->getProperties() as $property) {
62 3
            if (\in_array($property->getDeclaringClass()->getName(), [Node::class, AbstractBlock::class, AbstractInline::class], true)) {
63 3
                continue;
64
            }
65
66 3
            $property->setAccessible(true);
67 3
            $value = $property->getValue($node);
68 3
            if (self::isValueUsable($value)) {
69 3
                $attrs[$property->getName()] = $value;
70
            }
71
        }
72
73 3
        return $attrs;
74
    }
75
76
    /**
77
     * @param mixed $var
78
     *
79
     * @psalm-pure
80
     */
81 3
    private static function isValueUsable($var): bool
82
    {
83 3
        return \is_string($var) || \is_int($var) || \is_float($var) || \is_bool($var);
84
    }
85
}
86