Completed
Pull Request — master (#324)
by Javier
62:25
created

CKEditorRenderer::fixUrl()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

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