Passed
Push — master ( 8e81b3...7b641e )
by Dev
11:08
created

AppExtension::getFilters()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 3
Bugs 1 Features 0
Metric Value
cc 1
eloc 6
c 3
b 1
f 0
nc 1
nop 0
dl 0
loc 9
ccs 0
cts 8
cp 0
crap 2
rs 10
1
<?php
2
3
namespace PiedWeb\CMSBundle\Twig;
4
5
use Cocur\Slugify\Slugify;
6
use PiedWeb\CMSBundle\Entity\PageInterface as Page;
7
use PiedWeb\CMSBundle\Service\PageCanonicalService;
8
use PiedWeb\CMSBundle\Entity\Media;
9
use PiedWeb\RenderAttributes\AttributesTrait;
10
use Twig\Extension\AbstractExtension;
11
use Twig\TwigFilter;
12
use Twig\TwigFunction;
13
use Twig_Environment;
14
15
class AppExtension extends AbstractExtension
16
{
17
    use AttributesTrait;
18
19
    /** @var PageCanonicalService */
20
    protected $pageCanonical;
21
22
    public function __construct(PageCanonicalService $pageCanonical)
23
    {
24
        $this->pageCanonical = $pageCanonical;
25
    }
26
27
    public function getFilters()
28
    {
29
        return [
30
            //new TwigFilter('markdown', [AppExtension::class, 'markdownToHtml'], ['is_safe' => ['all']]),
31
            new TwigFilter('html_entity_decode', 'html_entity_decode'),
32
            new TwigFilter(
33
                'punctuation_beautifer',
34
                [AppExtension::class, 'punctuationBeautifer'],
35
                ['is_safe' => ['html']]
36
            ),
37
        ];
38
    }
39
40
    public static function convertMarkdownImage(string $body)
41
    {
42
        return preg_replace(
43
            '/(?:!\[(.*?)\]\((.*?)\))/',
44
            '{%'
45
            .PHP_EOL.'    include "@PiedWebCMS/component/_inline_image.html.twig" with {'
46
            .PHP_EOL.'        "image_src" : "$2",'
47
            .PHP_EOL.'        "image_alt" : "$1"'
48
            .PHP_EOL.'    } only'
49
            .PHP_EOL.'%}'.PHP_EOL,
50
            $body
51
        );
52
    }
53
54
    public function getFunctions()
55
    {
56
        return [
57
            new TwigFunction('homepage', [$this->pageCanonical, 'generatePathForHomepage']),
58
            new TwigFunction('page', [$this->pageCanonical, 'generatePathForPage']),
59
            new TwigFunction('jslink', [AppExtension::class, 'renderJavascriptLink'], [
60
                'is_safe' => ['html'],
61
                'needs_environment' => true,
62
            ]),
63
            new TwigFunction('link', [AppExtension::class, 'renderJavascriptLink'], [
64
                'is_safe' => ['html'],
65
                'needs_environment' => true,
66
            ]),
67
            new TwigFunction('mail', [AppExtension::class, 'renderEncodedMail'], [
68
                'is_safe' => ['html'],
69
                'needs_environment' => true,
70
            ]),
71
            new TwigFunction(
72
                'bookmark', // = anchor
73
                [AppExtension::class, 'renderTxtAnchor'],
74
                ['is_safe' => ['html'], 'needs_environment' => true]
75
            ),
76
            new TwigFunction(
77
                'anchor', // = bookmark
78
                [AppExtension::class, 'renderTxtAnchor'],
79
                ['is_safe' => ['html'], 'needs_environment' => true]
80
            ),
81
            new TwigFunction(
82
                'mail', // = bookmark
83
                [AppExtension::class, 'renderMail'],
84
                ['is_safe' => ['html'], 'needs_environment' => true]
85
            ),
86
            new TwigFunction(
87
                'isCurrentPage', // = bookmark
88
                [$this, 'isCurrentPage'],
89
                ['is_safe' => ['html'], 'needs_environment' => false]
90
            ),
91
            new TwigFunction(
92
                'gallery',
93
                [$this, 'renderGallery'],
94
                ['is_safe' => ['html'], 'needs_environment' => true]
95
            ),
96
            new TwigFunction('isInternalImage', [AppExtension::class, 'isInternalImage']),
97
            new TwigFunction('getImageFrom', [AppExtension::class, 'transformInlineImageToMedia']),
98
99
        ];
100
    }
101
102
    public static function isInternalImage(string $media): bool
103
    {
104
        return strpos($media, '/media/default/') === 0;
105
    }
106
107
    public static function transformInlineImageToMedia(string $src)
108
    {
109
        $src = substr($src, strlen('/media/default/'));
110
111
        $media = new Media();
112
        $media->setRelativeDir('/media');
113
        $media->setMedia($src);
114
        $media->setSlug(preg_replace('@(\.jpg|\.jpeg|\.png|\.gif)$@', '', $src), true);
115
116
        return $media;
117
    }
118
119
    public function renderGallery(Twig_Environment $env, Page $currentPage, $filterImageFrom = 1, $filterImageTo = 1001)
120
    {
121
        return $env->render('@PiedWebCMS/page/_gallery.html.twig', [
122
            'page' => $currentPage,
123
            'galleryFilterFrom' => $filterImageFrom - 1,
124
            'galleryFilterTo' => $filterImageTo - 1,
125
        ]);
126
    }
127
128
    public function isCurrentPage(string $uri, ?Page $currentPage)
129
    {
130
        return
131
            null === $currentPage || $uri != $this->pageCanonical->generatePathForPage($currentPage->getRealSlug())
132
            ? false
133
            : true;
134
    }
135
136
    public static function renderTxtAnchor(Twig_Environment $env, $name)
137
    {
138
        $slugify = new Slugify();
139
        $name = $slugify->slugify($name);
140
141
        return $env->render('@PiedWebCMS/component/_txt_anchor.html.twig', ['name' => $name]);
142
    }
143
144
    public static function renderMail(Twig_Environment $env, $mail, $class = '')
145
    {
146
        $mail = str_rot13($mail);
147
148
        return $env->render('@PiedWebCMS/component/_mail.html.twig', ['mail' => $mail, 'class' => $class]);
149
    }
150
151
    public static function renderEncodedMail(Twig_Environment $env, $mail)
152
    {
153
        return $env->render('@PiedWebCMS/component/_encoded_mail.html.twig', ['mail' => str_rot13($mail)]);
154
    }
155
156
    public static function punctuationBeautifer($text)
157
    {
158
        return str_replace(
159
            [' ;', ' :', ' ?', ' !', '« ', ' »', '&laquo; ', ' &raquo;'],
160
            ['&nbsp;;', '&nbsp;:', '&nbsp;?', '&nbsp;!', '«&nbsp;', '&nbsp;»', '&laquo;&nbsp;', '&nbsp;&raquo;'],
161
            $text
162
        );
163
    }
164
165
    public static function renderJavascriptLink(Twig_Environment $env, $anchor, $path, $attr = [])
166
    {
167
        if (0 === strpos($path, 'http://')) {
168
            $path = '-'.substr($path, 7);
169
        } elseif (0 === strpos($path, 'https://')) {
170
            $path = '_'.substr($path, 8);
171
        } elseif (0 === strpos($path, 'mailto:')) {
172
            $path = '@'.substr($path, 7);
173
        }
174
175
        return $env->render(
176
            '@PiedWebCMS/component/_javascript_link.html.twig',
177
            [
178
            'attr' => self::mergeAndMapAttributes($attr, ['class' => 'a', 'data-rot' => str_rot13($path)]),
179
            'anchor' => $anchor,
180
            ]
181
        );
182
    }
183
}
184