Passed
Pull Request — master (#11)
by Ryosuke
01:46
created

Publisher   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Test Coverage

Coverage 95.65%

Importance

Changes 0
Metric Value
eloc 27
dl 0
loc 48
ccs 22
cts 23
cp 0.9565
rs 10
c 0
b 0
f 0
wmc 9

1 Method

Rating   Name   Duplication   Size   Complexity  
B generateHtml() 0 35 9
1
<?php
2
3
namespace Mpyw\OpenGraph;
4
5
use DateTimeInterface;
6
use Mpyw\OpenGraph\Exceptions\UnexpectedValueException;
7
use Mpyw\OpenGraph\Objects\ObjectBase;
8
9
/**
10
 * Class for generating Open Graph tags from objects.
11
 */
12
class Publisher
13
{
14
    public const DOCTYPE_HTML5 = 1;
15
    public 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
     * @var int
22
     */
23
    public $doctype = self::DOCTYPE_HTML5;
24
25 12
    public function generateHtml(ObjectBase $object)
26
    {
27 12
        $html = '';
28 12
        $format = '<meta property="%s" content="%s"' . ($this->doctype == self::DOCTYPE_XHTML ? ' />' : '>');
29
30 12
        foreach ($object->getProperties() as $property) {
31 12
            if ($html !== '') {
32
                $html .= "\n";
33
            }
34
35 12
            if ($property->value === null) {
36 1
                continue;
37
            }
38 11
            if ($property->value instanceof DateTimeInterface) {
39 1
                $value = $property->value->format('c');
40 10
            } elseif (is_object($property->value)) {
41 1
                throw new UnexpectedValueException(
42 1
                    sprintf(
43 1
                        "Cannot handle value of type '%s' for property '%s'.",
44 1
                        get_class($property->value),
45 1
                        $property->key
46
                    )
47
                );
48 9
            } elseif ($property->value === true) {
49 1
                $value = '1';
50 8
            } elseif ($property->value === false) {
51 1
                $value = '0';
52
            } else {
53 7
                $value = (string)$property->value;
54
            }
55
56 10
            $html .= sprintf($format, $property->key, htmlspecialchars($value));
57
        }
58
59 11
        return $html;
60
    }
61
}
62