Passed
Push — master ( 730218...5f362f )
by Matthias
10:39 queued 08:10
created

Publisher::generateHtml()   D

Complexity

Conditions 9
Paths 26

Size

Total Lines 35
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 26
CRAP Score 9.0294

Importance

Changes 0
Metric Value
dl 0
loc 35
ccs 26
cts 28
cp 0.9286
rs 4.909
c 0
b 0
f 0
cc 9
eloc 24
nc 26
nop 1
crap 9.0294
1
<?php
2
3
namespace Fusonic\OpenGraph;
4
5
use DateTimeInterface;
6
use Fusonic\OpenGraph\Objects\ObjectBase;
7
use UnexpectedValueException;
8
9
/**
10
 * Class for generating Open Graph tags from objects.
11
 */
12
class Publisher
13
{
14
    const DOCTYPE_HTML5 = 1;
15
    const DOCTYPE_XHTML = 2;
16
17
    /**
18
     * Defines the style in which HTML tags should be written. Use one of Publisher::DOCTYPE_HTML5 or
19
     * Publisher::DOCTYPE_XHTML.
20
     */
21
    public int $doctype = self::DOCTYPE_HTML5;
0 ignored issues
show
Bug introduced by
This code did not parse for me. Apparently, there is an error somewhere around this line:

Syntax error, unexpected T_STRING, expecting T_FUNCTION or T_CONST
Loading history...
22
23 12
    public function __construct()
24
    {
25 12
    }
26
27
    /**
28
     * Generated HTML tags from the given object.
29
     */
30 12
    public function generateHtml(ObjectBase $object): string
31
    {
32 12
        $html = "";
33 12
        $format = "<meta property=\"%s\" content=\"%s\"" . ($this->doctype == self::DOCTYPE_XHTML ? " />" : ">");
34
35 12
        foreach ($object->getProperties() as $property) {
36 12
            if ($html !== "") {
37
                $html .= "\n";
38
            }
39
40 12
            if ($property->value === null) {
41 1
                continue;
42 11
            } elseif ($property->value instanceof DateTimeInterface) {
43 1
                $value = $property->value->format("c");
44 10
            } elseif (is_object($property->value)) {
45 1
                throw new UnexpectedValueException(
46
                    sprintf(
47 1
                        "Cannot handle value of type '%0' for property '%1'.",
48 1
                        get_class($property->value),
49 1
                        $property->key
50
                    )
51
                );
52 9
            } elseif ($property->value === true) {
53 1
                $value = "1";
54 8
            } elseif ($property->value === false) {
55 1
                $value = "0";
56
            } else {
57 7
                $value = (string)$property->value;
58
            }
59
60 10
            $html .= sprintf($format, $property->key, htmlspecialchars($value));
61
        }
62
63 11
        return $html;
64
    }
65
}
66