Passed
Push — master ( 43d3ba...783bbe )
by Dev
12:33
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
c 0
b 0
f 0
nc 1
nop 2
dl 0
loc 6
ccs 0
cts 6
cp 0
crap 2
rs 10
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\Extension\AbstractExtension;
13
use Twig\TwigFilter;
14
use Twig\TwigFunction;
15
use Twig_Environment;
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(
43
                'punctuation_beautifer',
44
                [AppExtension::class, 'punctuationBeautifer'],
45
                ['is_safe' => ['html']]
46
            ),
47
        ];
48
    }
49
50
    public static function convertMarkdownImage(string $body)
51
    {
52
        return preg_replace(
53
            '/(?:!\[(.*?)\]\((.*?)\))/',
54
            '{%'
55
            .PHP_EOL.'    include "@PiedWebCMS/component/_inline_image.html.twig" with {'
56
            .PHP_EOL.'        "image_src" : "$2",'
57
            .PHP_EOL.'        "image_alt" : "$1"'
58
            .PHP_EOL.'    } only'
59
            .PHP_EOL.'%}'.PHP_EOL,
60
            $body
61
        );
62
    }
63
64
    public function getFunctions()
65
    {
66
        return [
67
            new TwigFunction('homepage', [$this->pageCanonical, 'generatePathForHomepage']),
68
            new TwigFunction('page', [$this->pageCanonical, 'generatePathForPage']),
69
            new TwigFunction('jslink', [AppExtension::class, 'renderJavascriptLink'], [
70
                'is_safe' => ['html'],
71
                'needs_environment' => true,
72
            ]),
73
            new TwigFunction('link', [AppExtension::class, 'renderJavascriptLink'], [
74
                'is_safe' => ['html'],
75
                'needs_environment' => true,
76
            ]),
77
            new TwigFunction('mail', [AppExtension::class, 'renderEncodedMail'], [
78
                'is_safe' => ['html'],
79
                'needs_environment' => true,
80
            ]),
81
            new TwigFunction(
82
                'bookmark', // = anchor
83
                [AppExtension::class, 'renderTxtAnchor'],
84
                ['is_safe' => ['html'], 'needs_environment' => true]
85
            ),
86
            new TwigFunction(
87
                'anchor', // = bookmark
88
                [AppExtension::class, 'renderTxtAnchor'],
89
                ['is_safe' => ['html'], 'needs_environment' => true]
90
            ),
91
            new TwigFunction(
92
                'mail',
93
                [AppExtension::class, 'renderMail'],
94
                ['is_safe' => ['html'], 'needs_environment' => true]
95
            ),
96
            new TwigFunction(
97
                'isCurrentPage',
98
                [$this, 'isCurrentPage'],
99
                ['is_safe' => ['html'], 'needs_environment' => false]
100
            ),
101
            new TwigFunction(
102
                'gallery',
103
                [$this, 'renderGallery'],
104
                ['is_safe' => ['html'], 'needs_environment' => true]
105
            ),
106
            new TwigFunction(
107
                'list',
108
                [$this, 'renderPagesList'],
109
                ['is_safe' => ['html'], 'needs_environment' => true]
110
            ),
111
            new TwigFunction('isInternalImage', [AppExtension::class, 'isInternalImage']),
112
            new TwigFunction('getImageFrom', [AppExtension::class, 'transformInlineImageToMedia']),
113
        ];
114
    }
115
116
    public function renderPagesList(
117
        Twig_Environment $env,
118
        string $containing = '',
119
        int $number = 3,
120
        string $orderBy = 'createdAt',
121
        string $template = '@PiedWebCMS/page/_pages_list.html.twig'
122
    ) {
123
        $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

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