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

StructuredDataExtension::getStructuredData()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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