Completed
Pull Request — 2.x (#266)
by Maximilian
01:36
created

StructuredDataExtension::getFunctions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
c 0
b 0
f 0
rs 9.4285
cc 1
eloc 3
nc 1
nop 0
1
<?php
2
3
namespace Sonata\SeoBundle\Twig\Extension;
4
5
use Sonata\SeoBundle\Seo\StructuredDataAwarePage;
6
use Twig\Extension\AbstractExtension;
7
use Twig\TwigFunction;
8
9
/**
10
 * @author Maximilian Berghoff <[email protected]>
11
 */
12
class StructuredDataExtension extends AbstractExtension
13
{
14
    /**
15
     * @var StructuredDataAwarePage
16
     */
17
    protected $page;
18
19
    /**
20
     * @var string
21
     */
22
    protected $encoding;
23
24
    /**
25
     * @param StructuredDataAwarePage $page
26
     */
27
    public function __construct(StructuredDataAwarePage $page)
28
    {
29
        $this->page = $page;
30
    }
31
32
    /**
33
     * {@inheritdoc}
34
     */
35
    public function getFunctions()
36
    {
37
        return [
38
            new TwigFunction('sonata_seo_structured_data', [$this, 'getStructuredData'], ['is_safe' => ['html']]),
39
        ];
40
    }
41
42
    /**
43
     * Creates a script tag with type 'json-ld' and the JSON-LD string stored in page object.
44
     *
45
     * @return string
46
     */
47
    public function getStructuredData()
48
    {
49
        if (empty($this->page->getStructuredData())) {
50
            return '';
51
        }
52
53
        return sprintf("<script type=\"application/ld+json\">%s</script>\n", $this->page->getStructuredData());
54
    }
55
}
56