1 | <?php |
||
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; |
||
|
|||
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; |
|
66 |