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

StructuredDataExtension::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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