Completed
Pull Request — master (#342)
by Piotr
62:49
created

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