Passed
Push — main ( 3acca2...274d1b )
by Oscar
03:30
created

Configuration::addWebpackEncoreSection()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 15
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 11
nc 1
nop 1
dl 0
loc 15
ccs 14
cts 14
cp 1
crap 1
rs 9.9
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * This file is part of ocubom/twig-extra-bundle
5
 *
6
 * © Oscar Cubo Medina <https://ocubom.github.io>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Ocubom\TwigExtraBundle\DependencyInjection;
13
14
use Ocubom\TwigExtraBundle\Extensions;
15
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
16
use Symfony\Component\Config\Definition\Builder\BooleanNodeDefinition;
17
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
18
use Symfony\Component\Config\Definition\ConfigurationInterface;
19
20
class Configuration implements ConfigurationInterface
21
{
22 5
    public function getConfigTreeBuilder(): TreeBuilder
23
    {
24 5
        $builder = new TreeBuilder('ocubom_twig_extra');
25 5
        $root = $builder->getRootNode();
26
27
        // Register available extensions
28 5
        foreach (Extensions::getClasses() as $name => $class) {
29 5
            $call = str_replace(' ', '', ucwords(str_replace(['-', '_'], ' ', $name)));
30 5
            $this->{'add'.$call.'Section'}(
31 5
                $this->createSectionNode($root, $name, class_exists($class))
32 5
            );
33
        }
34
35
        // Headers listener included on this bundle
36 5
        $this->addHttpHeaderSection($root);
37
38 5
        return $builder;
39
    }
40
41 5
    private function createSectionNode(
42
        ArrayNodeDefinition $root,
43
        string $name,
44
        bool $canBeDisabled = true
45
    ): ArrayNodeDefinition {
46 5
        $node = $root
47 5
            ->children()
48 5
                ->arrayNode($name)
49 5
                    ->{$canBeDisabled ? 'canBeDisabled' : 'canBeEnabled'}()
50 5
                    ->info(sprintf(
51 5
                        'Twig %s Extension',
52 5
                        ucfirst($name)
53 5
                    ));
54
        assert($node instanceof ArrayNodeDefinition);
55
56 5
        $enabled = $node->find('enabled');
57
        assert($enabled instanceof BooleanNodeDefinition);
58 5
        $enabled->info('Enable or disable this extension');
59
60 5
        return $node;
61
    }
62
63 5
    private function addHttpHeaderSection(ArrayNodeDefinition $root): void
64
    {
65 5
        $root
66 5
            ->fixXmlConfig('http_header')
67 5
            ->children()
68 5
                ->arrayNode('http_headers')
69 5
                    ->info(implode("\n", [
70 5
                        'HTTP headers that must be set.',
71 5
                        'The listener will only be registered if at least one rule is enabled.',
72 5
                    ]))
73 5
                    ->prototype('array')
74 5
                        ->treatFalseLike(['enabled' => false])
75 5
                        ->treatTrueLike(['enabled' => true])
76 5
                        ->treatNullLike(['enabled' => true])
77 5
                        ->children()
78 5
                            ->booleanNode('enabled')
79 5
                                ->info('Enable or disable this rule')
80 5
                                ->defaultTrue()
81 5
                            ->end()
82 5
                            ->scalarNode('name')
83 5
                                ->info('The header name to be added.')
84 5
                                ->example('X-UA-Compatible')
85 5
                                ->isRequired()
86 5
                                ->cannotBeEmpty()
87 5
                            ->end()
88 5
                            ->scalarNode('pattern')
89 5
                                ->info('A regular expression to extract the header value.')
90 5
                                ->example('@@[\p{Zs}]*<meta\s+(?:http-equiv="X-UA-Compatible"\s+content="([^"]+)"|content="([^"]+)"\s+http-equiv="X-UA-Compatible")\s*>\p{Zs}*\n?@i')
91 5
                                ->isRequired()
92 5
                                ->cannotBeEmpty()
93 5
                            ->end()
94 5
                            ->scalarNode('value')
95 5
                                ->info('The format of the value (printf processed using the matched value).')
96 5
                                ->example('%2$s')
97 5
                                ->isRequired()
98 5
                                ->cannotBeEmpty()
99 5
                            ->end()
100 5
                            ->scalarNode('replace')
101 5
                                ->info('The text that replaces the match in the original (printf processed using the matched value).')
102 5
                                // ->example('')
103 5
                                ->defaultValue('%s')
104 5
                            ->end()
105 5
                            ->arrayNode('formats')
106 5
                                ->info('The response formats when this replacement must be done.')
107 5
                                ->example('["text/html"]')
108 5
                                // ->addDefaultChildrenIfNoneSet()
109 5
                                ->prototype('scalar')
110 5
                                    // ->defaultValue('text/html')
111 5
                                ->end()
112 5
                            ->end()
113 5
                        ->end()
114 5
                    ->end()
115 5
                ->end()
116 5
            ->end();
117
    }
118
119 5
    private function addHtmlSection(ArrayNodeDefinition $root): void
120
    {
121 5
        $root
122 5
            ->children()
123 5
                ->arrayNode('compression')
124 5
                    ->info('Compress HTML output')
125 5
                    ->addDefaultsIfNotSet()
126 5
                    ->children()
127 5
                        ->booleanNode('force')
128 5
                            ->info('Force compression')
129 5
                            ->defaultFalse()
130 5
                        ->end()
131 5
                        ->enumNode('level')
0 ignored issues
show
Bug introduced by
The method enumNode() does not exist on Symfony\Component\Config...der\NodeParentInterface. It seems like you code against a sub-type of Symfony\Component\Config...der\NodeParentInterface such as Symfony\Component\Config...ion\Builder\NodeBuilder. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

131
                        ->/** @scrutinizer ignore-call */ enumNode('level')
Loading history...
132 5
                            ->info('The level of compression to use')
133 5
                            ->defaultValue('smallest')
134 5
                            ->values([
135 5
                                'none',
136 5
                                'fastest',
137 5
                                'normal',
138 5
                                'smallest',
139 5
                            ])
140 5
                        ->end()
141 5
                    ->end()
142 5
                ->end()
143 5
            ->end();
144
    }
145
146 5
    private function addSvgSection(ArrayNodeDefinition $root): void
147
    {
148 5
        $examples = [
149 5
            'default' => [
150 5
                '%kernel.project_dir%/assets',
151 5
                '%kernel.project_dir%/node_modules',
152 5
            ],
153 5
            'fontawesome' => [
154 5
                '%kernel.project_dir%/node_modules/@fortawesome/fontawesome-pro/svgs',
155 5
                '%kernel.project_dir%/node_modules/@fortawesome/fontawesome-free/svgs',
156 5
                '%kernel.project_dir%/vendor/fortawesome/font-awesome/svgs/',
157 5
            ],
158 5
        ];
159
160 5
        $finderKeys = array_keys($examples);
161
162 5
        $root
163 5
            ->beforeNormalization()
164 5
                ->always(static function ($v) use ($finderKeys) {
165
                    // Convert deprecated configuration
166 5
                    $v['finders'] = $v['finders'] ?? [];
167 5
                    foreach ($finderKeys as $key) {
168
                        switch ($key) {
169 5
                            case 'default':
170 5
                                $v['finders'][$key] = $v['finders'][$key] ?? $v['search_path'] ?? [];
171 5
                                unset($v['search_path']);
172 5
                                break;
173
174 5
                            case 'fontawesome':
175 5
                                $v['finders'][$key] = $v['finders'][$key] ?? $v['fontawesome']['search_path'] ?? [];
176 5
                                unset($v['fontawesome']);
177 5
                                break;
178
                        }
179
                    }
180
181 5
                    return $v;
182 5
                })
183 5
            ->end()
184 5
            ->validate()
185 5
                ->always(function ($v) {
186
                    // Clean deprecated configuration
187 5
                    unset($v['search_path']);
188
189
                    // Disable if no finder are registered
190 5
                    $v['finders'] = array_filter($v['finders'] ?? []);
191 5
                    $v['enabled'] = (0 !== count($v['finders']));
192
193 5
                    return $v;
194 5
                })
195 5
            ->end()
196 5
            ->fixXmlConfig('finder')
197 5
            ->children()
198 5
                ->arrayNode('finders')
199 5
                    ->info('The paths where SVG files will be searched for.')
200 5
                    ->children()
201 5
                        ->arrayNode('default')
202 5
                            ->info('The default paths where the SVG files will be searched for.')
203 5
                            ->example(sprintf('["%s"]', implode('", "', $examples['default'])))
204 5
                            ->defaultValue($examples['default'])
205 5
                            ->prototype('scalar')
206 5
                            ->end()
207 5
                        ->end()
208 5
                        ->arrayNode('fontawesome')
209 5
                            ->info('The paths where the FontAwesome files will be searched for.')
210 5
                            ->example(sprintf('["%s"]', implode('", "', $examples['fontawesome'])))
211 5
                            ->defaultValue($examples['fontawesome'])
212 5
                            ->prototype('scalar')
213 5
                            ->end()
214 5
                        ->end()
215 5
                    ->end()
216 5
                ->end()
217 5
                ->arrayNode('search_path')
218 5
                    ->setDeprecated(
219 5
                        'ocubom/twig-extra-bundle',
220 5
                        '1.2',
221 5
                        'The "%node%" option is deprecated. Use "finder.svg" instead.'
222 5
                    )
223 5
                    ->info('The paths where the SVG files will be searched for.')
224 5
                    ->example(sprintf('["%s"]', implode('", "', $examples['default'])))
225 5
                    ->prototype('scalar')->end()
226 5
                ->end()
227 5
                ->arrayNode('fontawesome')
228 5
                    ->setDeprecated(
229 5
                        'ocubom/twig-extra-bundle',
230 5
                        '1.2',
231 5
                        'The "%node%" option is deprecated. Use "finder.fontawesome" instead.'
232 5
                    )
233 5
                    ->info('Configuration for FontAwesome.')
234 5
                    ->children()
235 5
                        ->arrayNode('search_path')
236 5
                            ->info('The paths where the FontAwesome files will be searched for.')
237 5
                            ->example(sprintf('["%s"]', implode('", "', [
238 5
                                '%kernel.project_dir%/node_modules/@fortawesome/fontawesome-pro/svgs',
239 5
                                '%kernel.project_dir%/node_modules/@fortawesome/fontawesome-free/svgs',
240 5
                            ])))
241 5
                            ->defaultValue([
242 5
                                '%kernel.project_dir%/node_modules/@fortawesome/fontawesome-pro/svgs',
243 5
                                '%kernel.project_dir%/node_modules/@fortawesome/fontawesome-free/svgs',
244 5
                            ])
245 5
                            ->prototype('scalar')->end()
246 5
                        ->end()
247 5
                    ->end()
248 5
                ->end()
249 5
            ->end();
250
    }
251
252 5
    private function addWebpackEncoreSection(ArrayNodeDefinition $root): void
253
    {
254 5
        $root
255 5
            ->children()
256 5
                ->arrayNode('output_paths')
257 5
                    ->info('Paths where Symfony Encore will generate its output.')
258 5
                    ->example(sprintf('["%s"]', implode('", "', [
259 5
                        '%kernel.project_dir%/public/build',
260 5
                    ])))
261 5
                    ->defaultValue([
262 5
                        '%kernel.project_dir%/public/build',
263 5
                    ])
264 5
                    ->prototype('scalar')
265 5
                ->end()
266 5
            ->end();
1 ignored issue
show
Bug introduced by
The method end() does not exist on Symfony\Component\Config...der\NodeParentInterface. It seems like you code against a sub-type of said class. However, the method does not exist in Symfony\Component\Config...ion\Builder\TreeBuilder. Are you sure you never get one of those? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

266
            ->/** @scrutinizer ignore-call */ end();
Loading history...
267
    }
268
}
269