Completed
Pull Request — master (#73)
by Mikołaj
16:15
created

RenderPageLinkByCodeExtension::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 8
c 1
b 0
f 0
rs 9.4285
cc 1
eloc 5
nc 1
nop 2
1
<?php
2
3
/**
4
 * This file was created by the developers from BitBag.
5
 * Feel free to contact us once you face any issues or want to start
6
 * another great project.
7
 * You can find more information about us on https://bitbag.shop and write us
8
 * an email on [email protected].
9
 */
10
11
namespace BitBag\CmsPlugin\Twig\Extension;
12
13
use BitBag\CmsPlugin\Entity\PageInterface;
14
use BitBag\CmsPlugin\Repository\PageRepositoryInterface;
15
use Psr\Log\LoggerInterface;
16
17
/**
18
 * @author Mikołaj Król <[email protected]>
19
 */
20
final class RenderPageLinkByCodeExtension extends \Twig_Extension
21
{
22
    const PAGE_LINK_TEMPLATE = 'BitBagCmsPlugin:Shop:Page:_link.html.twig';
23
24
    /**
25
     * @var PageRepositoryInterface
26
     */
27
    private $pageRepository;
28
29
    /**
30
     * @var LoggerInterface
31
     */
32
    private $logger;
33
34
    /**
35
     * @param PageRepositoryInterface $pageRepository
36
     * @param LoggerInterface $logger
37
     */
38
    public function __construct(
39
        PageRepositoryInterface $pageRepository,
40
        LoggerInterface $logger
41
    )
42
    {
43
        $this->pageRepository = $pageRepository;
44
        $this->logger = $logger;
45
    }
46
47
    /**
48
     * @return \Twig_SimpleFunction[]
49
     */
50
    public function getFunctions()
51
    {
52
        return [
53
            new \Twig_SimpleFunction('bitbag_render_page_link_by_code', [$this, 'renderPageLinkByCode'], ['needs_environment' => true, 'is_safe' => ['html'],]),
54
        ];
55
    }
56
57
    /**
58
     * @param \Twig_Environment $twigEnvironment
59
     * @param string $code
60
     *
61
     * @return null|string
62
     */
63
    public function renderPageLinkByCode(\Twig_Environment $twigEnvironment, $code)
64
    {
65
        $page = $this->pageRepository->findEnabledByCode($code);
66
67
        if (false === $page instanceof PageInterface) {
68
69
            $this->logger->warning(sprintf(
70
                'Page with "%s" code was not found in the database.',
71
                $code
72
            ));
73
74
            return null;
75
        }
76
77
        return $twigEnvironment->render(self::PAGE_LINK_TEMPLATE, ['page' => $page]);
78
    }
79
}
80