Passed
Push — master ( 05fb81...6853de )
by Dev
07:47
created

AppExtension::renderTxtAnchor()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 2
dl 0
loc 6
ccs 0
cts 5
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace PiedWeb\CMSBundle\Twig;
4
5
use Cocur\Slugify\Slugify;
6
use Doctrine\ORM\EntityManager;
7
use Doctrine\ORM\EntityManagerInterface;
8
use PiedWeb\CMSBundle\Entity\Media;
9
use PiedWeb\CMSBundle\Entity\PageInterface as Page;
10
use PiedWeb\CMSBundle\Service\PageCanonicalService;
11
use PiedWeb\RenderAttributes\AttributesTrait;
12
use Twig\Environment as Twig;
13
use Twig\Extension\AbstractExtension;
14
use Twig\TwigFilter;
15
use Twig\TwigFunction;
16
17
class AppExtension extends AbstractExtension
18
{
19
    use AttributesTrait;
20
21
    /** @var PageCanonicalService */
22
    protected $pageCanonical;
23
24
    /** @var EntityManagerInterface */
25
    private $em;
26
27
    /** @var string */
28
    private $page_class;
29
30
    public function __construct(EntityManager $em, string $page_class, PageCanonicalService $pageCanonical)
31
    {
32
        $this->em = $em;
33
        $this->pageCanonical = $pageCanonical;
34
        $this->page_class = $page_class;
35
    }
36
37
    public function getFilters()
38
    {
39
        return [
40
            //new TwigFilter('markdown', [AppExtension::class, 'markdownToHtml'], ['is_safe' => ['all']]),
41
            new TwigFilter('html_entity_decode', 'html_entity_decode'),
42
            new TwigFilter('preg_replace', [AppExtension::class, 'pregReplace']),
43
            new TwigFilter(
44
                'punctuation_beautifer',
45
                [AppExtension::class, 'punctuationBeautifer'],
46
                ['is_safe' => ['html']]
47
            ),
48
        ];
49
    }
50
51
    public static function pregReplace($subject, $pattern, $replacement)
52
    {
53
        return preg_replace($pattern, $replacement, $subject);
54
    }
55
56
    public static function convertMarkdownImage(string $body)
57
    {
58
        return preg_replace(
59
            '/(?:!\[(.*?)\]\((.*?)\))/',
60
            '{%'
61
            .PHP_EOL.'    include "@PiedWebCMS/component/_inline_image.html.twig" with {'
62
            .PHP_EOL.'        "image_wrapper_class" : "mimg",'
63
            .PHP_EOL.'        "image_src" : "$2",'
64
            .PHP_EOL.'        "image_alt" : "$1"'
65
            .PHP_EOL.'    } only'
66
            .PHP_EOL.'%}'.PHP_EOL,
67
            $body
68
        );
69
    }
70
71
    public function getFunctions()
72
    {
73
        return [
74
            new TwigFunction('homepage', [$this->pageCanonical, 'generatePathForHomepage']),
75
            new TwigFunction('page', [$this->pageCanonical, 'generatePathForPage']),
76
            new TwigFunction('jslink', [AppExtension::class, 'renderJavascriptLink'], [
77
                'is_safe' => ['html'],
78
                'needs_environment' => true,
79
            ]),
80
            new TwigFunction('link', [AppExtension::class, 'renderJavascriptLink'], [
81
                'is_safe' => ['html'],
82
                'needs_environment' => true,
83
            ]),
84
            new TwigFunction('mail', [AppExtension::class, 'renderEncodedMail'], [
85
                'is_safe' => ['html'],
86
                'needs_environment' => true,
87
            ]),
88
            new TwigFunction(
89
                'bookmark', // = anchor
90
                [AppExtension::class, 'renderTxtAnchor'],
91
                ['is_safe' => ['html'], 'needs_environment' => true]
92
            ),
93
            new TwigFunction(
94
                'anchor', // = bookmark
95
                [AppExtension::class, 'renderTxtAnchor'],
96
                ['is_safe' => ['html'], 'needs_environment' => true]
97
            ),
98
            new TwigFunction(
99
                'isCurrentPage',
100
                [$this, 'isCurrentPage'],
101
                ['is_safe' => ['html'], 'needs_environment' => false]
102
            ),
103
            new TwigFunction(
104
                'gallery',
105
                [$this, 'renderGallery'],
106
                ['is_safe' => ['html'], 'needs_environment' => true]
107
            ),
108
            new TwigFunction(
109
                'encode',
110
                [AppExtension::class, 'encode'],
111
                ['is_safe' => ['html']]
112
            ),
113
            new TwigFunction(
114
                'list',
115
                [$this, 'renderPagesList'],
116
                ['is_safe' => ['html'], 'needs_environment' => true]
117
            ),
118
            new TwigFunction('isInternalImage', [AppExtension::class, 'isInternalImage']),
119
            new TwigFunction('getImageFrom', [AppExtension::class, 'transformInlineImageToMedia']),
120
        ];
121
    }
122
123
    public function renderPagesList(
124
        Twig $env,
125
        string $containing = '',
126
        int $number = 3,
127
        string $orderBy = 'createdAt',
128
        string $template = '@PiedWebCMS/page/_pages_list.html.twig'
129
    ) {
130
        $qb = $this->em->getRepository($this->page_class)->getQueryToFindPublished('p');
0 ignored issues
show
Bug introduced by
The method getQueryToFindPublished() does not exist on Doctrine\Persistence\ObjectRepository. It seems like you code against a sub-type of Doctrine\Persistence\ObjectRepository such as Doctrine\ORM\EntityRepository. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

130
        $qb = $this->em->getRepository($this->page_class)->/** @scrutinizer ignore-call */ getQueryToFindPublished('p');
Loading history...
131
        $qb->andWhere('p.mainContent LIKE :containing')->setParameter('containing', '%'.$containing.'%');
132
        $qb->orderBy('p.'.$orderBy, 'DESC');
133
        $qb->setMaxResults($number);
134
135
        $pages = $qb->getQuery()->getResult();
136
137
        return $env->render($template, ['pages' => $pages]);
138
    }
139
140
    public static function isInternalImage(string $media): bool
141
    {
142
        return 0 === strpos($media, '/media/default/');
143
    }
144
145
    public static function transformInlineImageToMedia(string $src)
146
    {
147
        if (self::isInternalImage($src)) {
148
            $src = substr($src, strlen('/media/default/'));
149
150
            $media = new Media();
151
            $media->setRelativeDir('/media');
152
            $media->setMedia($src);
153
            $media->setSlug(preg_replace('@(\.jpg|\.jpeg|\.png|\.gif)$@', '', $src), true);
154
155
            return $media;
156
        }
157
158
        $media = new Media();
159
        $media->setRelativeDir($src);
160
        $media->setMedia('');
161
        $media->setSlug('', true);
162
163
        return $media;
164
    }
165
166
    public function renderGallery(Twig $env, Page $currentPage, $filterImageFrom = 1, $length = 1001)
167
    {
168
        return $env->render('@PiedWebCMS/page/_gallery.html.twig', [
169
            'page' => $currentPage,
170
            'galleryFilterFrom' => $filterImageFrom - 1,
171
            'length' => $length,
172
        ]);
173
    }
174
175
    public function isCurrentPage(string $uri, ?Page $currentPage)
176
    {
177
        return
178
            null === $currentPage || $uri != $this->pageCanonical->generatePathForPage($currentPage->getRealSlug())
179
            ? false
180
            : true;
181
    }
182
183
    public static function renderTxtAnchor(Twig $env, $name)
184
    {
185
        $slugify = new Slugify();
186
        $name = $slugify->slugify($name);
187
188
        return $env->render('@PiedWebCMS/component/_txt_anchor.html.twig', ['name' => $name]);
189
    }
190
191
    public static function renderEncodedMail(Twig $env, $mail, $class = '')
192
    {
193
        return $env->render('@PiedWebCMS/component/_encoded_mail.html.twig', [
194
            'mail' => str_rot13($mail),
195
            'class' => $class,
196
        ]);
197
    }
198
199
    public static function punctuationBeautifer($text)
200
    {
201
        return str_replace(
202
            [' ;', ' :', ' ?', ' !', '« ', ' »', '&laquo; ', ' &raquo;'],
203
            ['&nbsp;;', '&nbsp;:', '&nbsp;?', '&nbsp;!', '«&nbsp;', '&nbsp;»', '&laquo;&nbsp;', '&nbsp;&raquo;'],
204
            $text
205
        );
206
    }
207
208
    public static function renderJavascriptLink(Twig $env, $anchor, $path, $attr = [])
209
    {
210
        if (0 === strpos($path, 'http://')) {
211
            $path = '-'.substr($path, 7);
212
        } elseif (0 === strpos($path, 'https://')) {
213
            $path = '_'.substr($path, 8);
214
        } elseif (0 === strpos($path, 'mailto:')) {
215
            $path = '@'.substr($path, 7);
216
        }
217
218
        return $env->render(
219
            '@PiedWebCMS/component/_javascript_link.html.twig',
220
            [
221
            'attr' => self::mergeAndMapAttributes($attr, ['class' => 'a', 'data-rot' => str_rot13($path)]),
222
            'anchor' => $anchor,
223
            ]
224
        );
225
    }
226
227
    public static function encode($string)
228
    {
229
        return str_rot13($string);
230
    }
231
}
232