Completed
Pull Request — master (#277)
by Eric
63:02 queued 27s
created

CKEditorRenderer::fixRoutePath()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 5
cts 5
cp 1
rs 9.2
c 0
b 0
f 0
cc 4
eloc 8
nc 4
nop 1
crap 4

1 Method

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