Completed
Pull Request — master (#340)
by Maximilian
14:30
created

CKEditorRenderer::getJsonBuilder()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
3
/*
4
 * This file is part of the Ivory CKEditor package.
5
 *
6
 * (c) Eric GELOEN <[email protected]>
7
 *
8
 * For the full copyright and license information, please read the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Ivory\CKEditorBundle\Renderer;
13
14
use Ivory\JsonBuilder\JsonBuilder;
15
use Symfony\Component\Asset\Packages;
16
use Symfony\Component\HttpFoundation\RequestStack;
17
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
18
use Symfony\Component\Routing\RouterInterface;
19
use Symfony\Component\Templating\EngineInterface;
20
21
/**
22
 * @author GeLo <[email protected]>
23
 */
24
class CKEditorRenderer implements CKEditorRendererInterface
25
{
26
    /**
27
     * @var JsonBuilder
28
     */
29
    private $jsonBuilder;
30
31
    /**
32
     * @var RouterInterface
33
     */
34
    private $router;
35
36
    /**
37
     * @var Packages
38
     */
39
    private $assetsPackages;
40
41
    /**
42
     * @var EngineInterface
43
     */
44
    private $templating;
45
46
    /**
47
     * @var RequestStack
48
     */
49
    private $requestStack;
50
51
    /**
52
     * @param JsonBuilder $jsonBuilder
53
     * @param RouterInterface $router
54
     * @param Packages $packages
55
     * @param RequestStack $requestStack
56
     * @param EngineInterface $templating
57
     */
58 770
    public function __construct(JsonBuilder $jsonBuilder, RouterInterface $router, Packages $packages, RequestStack $requestStack, EngineInterface $templating)
59
    {
60 770
        $this->jsonBuilder = $jsonBuilder;
61 770
        $this->router = $router;
62 770
        $this->assetsPackages = $packages;
63 770
        $this->templating = $templating;
64 770
        $this->requestStack = $requestStack;
65 770
    }
66
67
    /**
68
     * {@inheritdoc}
69
     */
70 100
    public function renderBasePath($basePath)
71
    {
72 100
        return $this->fixPath($basePath);
73
    }
74
75
    /**
76
     * {@inheritdoc}
77
     */
78 90
    public function renderJsPath($jsPath)
79
    {
80 90
        return $this->fixPath($jsPath);
81
    }
82
83
    /**
84
     * {@inheritdoc}
85
     */
86 610
    public function renderWidget($id, array $config, array $options = [])
87
    {
88 610
        $config = $this->fixConfigLanguage($config);
89 610
        $config = $this->fixConfigContentsCss($config);
90 610
        $config = $this->fixConfigFilebrowsers(
91 610
            $config,
92 610
            isset($options['filebrowsers']) ? $options['filebrowsers'] : []
93 427
        );
94
95 610
        $autoInline = isset($options['auto_inline']) && !$options['auto_inline']
96 436
            ? 'CKEDITOR.disableAutoInline = true;'."\n"
97 610
            : null;
98
99 610
        $builder = $this->jsonBuilder->reset()->setValues($config);
100 610
        $this->fixConfigEscapedValues($builder, $config);
101
102 610
        $widget = sprintf(
103 610
            'CKEDITOR.%s("%s", %s);',
104 610
            isset($options['inline']) && $options['inline'] ? 'inline' : 'replace',
105 610
            $id,
106 610
            $this->fixConfigConstants($builder->build())
107 427
        );
108
109 610
        if (isset($options['input_sync']) && $options['input_sync']) {
110 30
            $variable = 'ivory_ckeditor_'.$id;
111 30
            $widget = 'var '.$variable.' = '.$widget."\n";
112
113 30
            return $autoInline.$widget.$variable.'.on(\'change\', function() { '.$variable.'.updateElement(); });';
114
        }
115
116 580
        return $autoInline.$widget;
117
    }
118
119
    /**
120
     * {@inheritdoc}
121
     */
122 110
    public function renderDestroy($id)
123
    {
124 110
        return sprintf(
125
            'if (CKEDITOR.instances["%1$s"]) { '.
126 77
            'CKEDITOR.instances["%1$s"].destroy(true); '.
127 77
            'delete CKEDITOR.instances["%1$s"]; '.
128 110
            '}',
129 33
            $id
130 77
        );
131
    }
132
133
    /**
134
     * {@inheritdoc}
135
     */
136 40
    public function renderPlugin($name, array $plugin)
137
    {
138 40
        return sprintf(
139 40
            'CKEDITOR.plugins.addExternal("%s", "%s", "%s");',
140 40
            $name,
141 40
            $this->fixPath($plugin['path']),
142 40
            $plugin['filename']
143 28
        );
144
    }
145
146
    /**
147
     * {@inheritdoc}
148
     */
149 30
    public function renderStylesSet($name, array $stylesSet)
150
    {
151 30
        return sprintf(
152
            'if (CKEDITOR.stylesSet.get("%1$s") === null) { '.
153 21
            'CKEDITOR.stylesSet.add("%1$s", %2$s); '.
154 30
            '}',
155 30
            $name,
156 30
            $this->jsonBuilder->reset()->setValues($stylesSet)->build()
157 21
        );
158
    }
159
160
    /**
161
     * {@inheritdoc}
162
     */
163 60
    public function renderTemplate($name, array $template)
164
    {
165 60
        if (isset($template['imagesPath'])) {
166 60
            $template['imagesPath'] = $this->fixPath($template['imagesPath']);
167 42
        }
168
169 60
        if (isset($template['templates'])) {
170 60
            foreach ($template['templates'] as &$rawTemplate) {
0 ignored issues
show
Bug introduced by
The expression $template['templates'] of type string is not traversable.
Loading history...
171 60
                if (isset($rawTemplate['template'])) {
172 20
                    $rawTemplate['html'] = $this->templating->render(
173 20
                        $rawTemplate['template'],
174 20
                        isset($rawTemplate['template_parameters']) ? $rawTemplate['template_parameters'] : []
175 14
                    );
176 14
                }
177
178 60
                unset($rawTemplate['template']);
179 60
                unset($rawTemplate['template_parameters']);
180 42
            }
181 42
        }
182
183 60
        return sprintf(
184 60
            'CKEDITOR.addTemplates("%s", %s);',
185 60
            $name,
186 60
            $this->jsonBuilder->reset()->setValues($template)->build()
187 42
        );
188
    }
189
190
    /**
191
     * @param array $config
192
     *
193
     * @return array
194
     */
195 610
    private function fixConfigLanguage(array $config)
196
    {
197 610
        if (!isset($config['language']) && ($language = $this->requestStack->getCurrentRequest()->getLocale()) !== null) {
198 40
            $config['language'] = $language;
199 28
        }
200
201 610
        if (isset($config['language'])) {
202 60
            $config['language'] = strtolower(str_replace('_', '-', $config['language']));
203 42
        }
204
205 610
        return $config;
206
    }
207
208
    /**
209
     * @param array $config
210
     *
211
     * @return array
212
     */
213 610
    private function fixConfigContentsCss(array $config)
214
    {
215 610
        if (isset($config['contentsCss'])) {
216 80
            $cssContents = (array) $config['contentsCss'];
217
218 80
            $config['contentsCss'] = [];
219 80
            foreach ($cssContents as $cssContent) {
220 80
                $config['contentsCss'][] = $this->fixPath($cssContent);
221 56
            }
222 56
        }
223
224 610
        return $config;
225
    }
226
227
    /**
228
     * @param array $config
229
     * @param array $filebrowsers
230
     *
231
     * @return array
232
     */
233 610
    private function fixConfigFilebrowsers(array $config, array $filebrowsers)
234
    {
235 610
        $filebrowsers = array_unique(array_merge([
236 610
            'Browse',
237 427
            'FlashBrowse',
238 427
            'ImageBrowse',
239 427
            'ImageBrowseLink',
240 427
            'Upload',
241 427
            'FlashUpload',
242 427
            'ImageUpload',
243 610
        ], $filebrowsers));
244
245 610
        foreach ($filebrowsers as $filebrowser) {
246 610
            $fileBrowserKey = 'filebrowser'.$filebrowser;
247 610
            $handler = $fileBrowserKey.'Handler';
248 610
            $url = $fileBrowserKey.'Url';
249 610
            $route = $fileBrowserKey.'Route';
250 610
            $routeParameters = $fileBrowserKey.'RouteParameters';
251 610
            $routeType = $fileBrowserKey.'RouteType';
252
253 610
            if (isset($config[$handler])) {
254 70
                $config[$url] = $config[$handler]($this->router);
255 610
            } elseif (isset($config[$route])) {
256 140
                $config[$url] = $this->router->generate(
257 140
                    $config[$route],
258 140
                    isset($config[$routeParameters]) ? $config[$routeParameters] : [],
259 140
                    isset($config[$routeType]) ? $config[$routeType] : UrlGeneratorInterface::ABSOLUTE_PATH
260 98
                );
261 98
            }
262
263 610
            unset($config[$handler]);
264 610
            unset($config[$route]);
265 610
            unset($config[$routeParameters]);
266 610
            unset($config[$routeType]);
267 427
        }
268
269 610
        return $config;
270
    }
271
272
    /**
273
     * @param JsonBuilder $builder
274
     * @param array       $config
275
     */
276 610
    private function fixConfigEscapedValues(JsonBuilder $builder, array $config)
277
    {
278 610
        if (isset($config['protectedSource'])) {
279 10
            foreach ($config['protectedSource'] as $key => $value) {
280 10
                $builder->setValue(sprintf('[protectedSource][%s]', $key), $value, false);
281 7
            }
282 7
        }
283
284
        $escapedValueKeys = [
285 610
            'stylesheetParser_skipSelectors',
286 427
            'stylesheetParser_validSelectors',
287 427
        ];
288
289 610
        foreach ($escapedValueKeys as $escapedValueKey) {
290 610
            if (isset($config[$escapedValueKey])) {
291 197
                $builder->setValue(sprintf('[%s]', $escapedValueKey), $config[$escapedValueKey], false);
292 14
            }
293 427
        }
294 610
    }
295
296
    /**
297
     * @param string $json
298
     *
299
     * @return string
300
     */
301 610
    private function fixConfigConstants($json)
302
    {
303 610
        return preg_replace('/"(CKEDITOR\.[A-Z_]+)"/', '$1', $json);
304
    }
305
306
    /**
307
     * @param string $path
308
     *
309
     * @return string
310
     */
311 250
    private function fixPath($path)
312
    {
313 250
        if ($this->assetsPackages === null) {
314
            return $path;
315
        }
316
317 250
        $url = $this->assetsPackages->getUrl($path);
318
319 250
        if (substr($path, -1) === '/' && ($position = strpos($url, '?')) !== false) {
320 40
            $url = substr($url, 0, $position);
321 28
        }
322
323 250
        return $url;
324
    }
325
}
326