Passed
Push — main ( 378c88...96b792 )
by Oscar
04:54
created

OcubomTwigExtraExtension::loadSvgFinders()   B

Complexity

Conditions 6
Paths 16

Size

Total Lines 52
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 29
CRAP Score 6.0012

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 27
c 1
b 0
f 0
nc 16
nop 2
dl 0
loc 52
ccs 29
cts 30
cp 0.9667
crap 6.0012
rs 8.8657

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\Twig\Extension\HtmlAttributesRuntime;
15
use Ocubom\Twig\Extension\HtmlCompressRuntime;
16
use Ocubom\Twig\Extension\HtmlExtension;
17
use Ocubom\Twig\Extension\Svg\Finder;
1 ignored issue
show
Bug introduced by
The type Ocubom\Twig\Extension\Svg\Finder was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
18
use Ocubom\Twig\Extension\Svg\FinderInterface;
1 ignored issue
show
Bug introduced by
The type Ocubom\Twig\Extension\Svg\FinderInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
19
use Ocubom\Twig\Extension\Svg\Library\FontAwesome\Finder as FontAwesomeFinder;
1 ignored issue
show
Bug introduced by
The type Ocubom\Twig\Extension\Sv...rary\FontAwesome\Finder was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
20
use Ocubom\Twig\Extension\Svg\Library\FontAwesomeRuntime;
1 ignored issue
show
Bug introduced by
The type Ocubom\Twig\Extension\Sv...rary\FontAwesomeRuntime was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
21
use Ocubom\Twig\Extension\Svg\Loader\ChainLoader;
22
use Ocubom\Twig\Extension\Svg\Loader\LoaderInterface;
23
use Ocubom\Twig\Extension\Svg\Util\PathCollection;
24
use Ocubom\Twig\Extension\SvgExtension;
25
use Ocubom\Twig\Extension\SvgRuntime;
26
use Ocubom\TwigExtraBundle\Extensions;
27
use Ocubom\TwigExtraBundle\Listener\AddHttpHeadersListener;
28
use Ocubom\TwigExtraBundle\Twig\WebpackEncoreExtension;
29
use Symfony\Component\Config\Definition\ConfigurationInterface;
30
use Symfony\Component\DependencyInjection\Argument\TaggedIteratorArgument;
31
use Symfony\Component\DependencyInjection\ContainerBuilder;
1 ignored issue
show
Bug introduced by
The type Symfony\Component\Depend...ection\ContainerBuilder was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
32
use Symfony\Component\DependencyInjection\Extension\Extension;
33
use Symfony\Component\DependencyInjection\Reference;
34
35
use function BenTools\IterableFunctions\iterable_to_array;
36
use function Ocubom\Math\base_convert;
37
38
class OcubomTwigExtraExtension extends Extension
39
{
40 12
    public function load(array $configs, ContainerBuilder $container): void
41
    {
42 12
        $configuration = $this->getConfiguration($configs, $container);
43
        assert($configuration instanceof ConfigurationInterface);
44 12
        $config = $this->processConfiguration($configuration, $configs);
45
46
        // Load enabled extensions
47 12
        foreach (array_keys(Extensions::getClasses()) as $name) {
48 12
            if ($this->isConfigEnabled($container, $config[$name])) {
49 12
                $call = str_replace(' ', '', ucwords(str_replace(['-', '_'], ' ', $name)));
50
51 12
                $this->{'load'.$call}($container, $config[$name]);
52
            }
53
        }
54
55
        // Load headers listener
56 12
        $this->loadHttpHeaders($container, $config['http_headers']);
57
    }
58
59 12
    private function loadHttpHeaders(ContainerBuilder $container, array $config): void
60
    {
61
        // Filter enabled header rules
62 12
        $headers = array_filter($config, function (array $header): bool {
63 4
            return (bool) $header['enabled'];
64 12
        });
65
66
        // Only register listener if some rule is defined
67 12
        if (count($headers) > 0) {
68 4
            $container->register('ocubom_twig_extra.http_headers_listener', AddHttpHeadersListener::class)
69 4
                ->setArguments(array_values($headers))
70 4
                ->addTag('kernel.event_subscriber');
71
        }
72
    }
73
74 10
    private function loadHtml(ContainerBuilder $container, array $config): void
75
    {
76 10
        $container->register('ocubom_twig_extra.twig_html_extension', HtmlExtension::class)
77 10
            ->addTag('twig.extension');
78
79 10
        $container->register('ocubom_twig_extra.twig_html_attributes_runtime', HtmlAttributesRuntime::class)
80 10
            ->addTag('twig.runtime');
81
82 10
        $container->register('ocubom_twig_extra.twig_html_compress_runtime', HtmlCompressRuntime::class)
83 10
            ->setArguments([
84 10
                $config['compression']['force'],
85 10
                $config['compression']['level'],
86 10
            ])
87 10
            ->addTag('twig.runtime');
88
    }
89
90
    /** @psalm-suppress UndefinedClass */
91 10
    private function loadSvg(ContainerBuilder $container, array $config): void
92
    {
93 10
        if (empty($config['providers'])) {
94
            return;
95
        }
96
97
        // Register the extension
98 10
        $container->register('ocubom_twig_extra.twig_svg_extension', SvgExtension::class)
99 10
            ->addTag('twig.extension');
100
101
        switch (true) {
102 10
            case interface_exists(LoaderInterface::class):
103 5
                $this->loadSvgLoaders($container, $config);
104 5
                break;
105
106 5
            case interface_exists(FinderInterface::class):
107 5
                $this->loadSvgFinders($container, $config);
108 5
                break;
109
        }
110
    }
111
112 5
    private function loadSvgLoaders(ContainerBuilder $container, array $config): void
113
    {
114
        // Register global loader
115 5
        $container->register('ocubom_twig_extra.svg_loader', ChainLoader::class)
116 5
            ->setArguments([
117 5
                new TaggedIteratorArgument('ocubom_twig_extra.svg_loader'),
118 5
            ]);
119
120
        // Register global runtime
121 5
        $container->register('ocubom_twig_extra.twig_svg_runtime', SvgRuntime::class)
122 5
            ->setArguments([
123 5
                new Reference('ocubom_twig_extra.svg_loader'),
124 5
            ])
125 5
            ->setAutowired(true)
126 5
            ->setAutoconfigured(true)
127 5
            ->addTag('twig.runtime');
128
129
        // Register individual providers
130 5
        foreach ($config['providers'] as $name => $provider) {
131 5
            if (!$provider['enabled']) {
132
                continue; // @codeCoverageIgnore
133
            }
134
135 5
            $case = str_replace(' ', '', ucwords(str_replace(['-', '_'], ' ', $name)));
136
137
            // Loader
138 5
            $loaderClass = "Ocubom\\Twig\\Extension\\Svg\\Provider\\{$case}\\{$case}Loader";
139 5
            $loaderIdent = "ocubom_twig_extra.svg_loader.{$name}";
140 5
            if (class_exists($loaderClass)) {
141
                // $loaderClass = (new \ReflectionClass($loaderClass))->getName();
142
143
                // Register the path collection (when necessary)
144 5
                $pathsIdent = base_convert(sha1(serialize($provider['paths'])), 16, 62);
145 5
                $pathsIdent = ".ocubom_twig_extra.svg_path_collection.{$pathsIdent}";
146 5
                if (!$container->has($pathsIdent)) {
147 5
                    $container->register($pathsIdent, PathCollection::class)
148 5
                        ->setArguments($provider['paths'])
149 5
                        ->setPublic(false);
150
                }
151
152
                // Register loader
153 5
                $container->register($loaderIdent, $loaderClass)
154 5
                    ->setArguments(iterable_to_array(call_user_func(function () use ($provider, $pathsIdent) {
155 5
                        yield new Reference($pathsIdent);
156
157
                        // Pass custom loader options
158 5
                        if (isset($provider['loader'])) {
159 5
                            yield $provider['loader'];
160
                        }
161 5
                    })))
162 5
                    ->setAutowired(true)
163 5
                    ->setAutoconfigured(true)
164 5
                    ->addTag('ocubom_twig_extra.svg_loader');
165
            }
166
167
            // Runtime
168 5
            $runtimeClass = "Ocubom\\Twig\\Extension\\Svg\\Provider\\{$case}\\{$case}Runtime";
169 5
            $runtimeIdent = "ocubom_twig_extra.twig_svg_{$name}_runtime";
170 5
            if ($container->has($loaderIdent) && class_exists($runtimeClass)) {
171
                // Register runtime
172 5
                $container
173 5
                    ->register($runtimeIdent, $runtimeClass)
174 5
                    ->setArguments(iterable_to_array(call_user_func(function () use ($provider, $loaderIdent) {
175 5
                        yield new Reference($loaderIdent);
176
177
                        // Pass custom runtime options
178 5
                        if (isset($provider['runtime'])) {
179 5
                            yield $provider['runtime'];
180
                        }
181 5
                    })))
182 5
                    ->setAutowired(true)
183 5
                    ->setAutoconfigured(true)
184 5
                    ->addTag('twig.runtime');
185
186
                // Register the extension
187 5
                if (!$container->has('ocubom_twig_extra.twig_svg_extension')) {
188
                    $container->register('ocubom_twig_extra.twig_svg_extension', SvgExtension::class)
189
                        ->addTag('twig.extension');
190
                }
191
            }
192
        }
193
    }
194
195
    /** @psalm-suppress UndefinedClass */
196 5
    private function loadSvgFinders(ContainerBuilder $container, array $config): void
197
    {
198 5
        foreach ($config['providers'] as $name => $provider) {
199 5
            if (!$provider['enabled']) {
200
                continue;
201
            }
202
203
            // Path colletion
204 5
            $pathsIdent = sha1(serialize($provider['paths']));
205 5
            $pathsIdent = ".ocubom_twig_extra.svg.finder.{$pathsIdent}";
206 5
            if (!$container->has($pathsIdent)) {
207 5
                $container->register($pathsIdent, Finder::class)
208 5
                    ->setArguments($provider['paths'])
209 5
                    ->setPublic(false)
210 5
                    ->addTag('ocubom_twig_extra.svg_finder');
211
            }
212
213
            // Create a hidden alias
214 5
            $container->setAlias(".ocubom_twig_extra.svg.{$name}_finder.inner", $pathsIdent);
215
        }
216
217
        // Register default runtime
218 5
        if ($container->has('.ocubom_twig_extra.svg.file_system_finder.inner')) {
219
            // Register runtime
220 5
            $container->register('ocubom_twig_extra.twig_svg_runtime', SvgRuntime::class)
221 5
                ->setArguments([
222 5
                    new Reference('.ocubom_twig_extra.svg.file_system_finder.inner'),
223 5
                ])
224 5
                ->setAutowired(true)
225 5
                ->setAutoconfigured(true)
226 5
                ->addTag('twig.runtime');
227
228
            // Create default finder (just an alias)
229 5
            $container->setAlias('ocubom_twig_extra.svg.default_finder', '.ocubom_twig_extra.svg.file_system_finder.inner');
230
231
            // Create class aliases
232
            // $container->setAlias(FinderInterface::class, 'ocubom_twig_extra.svg.default_finder');
233
        }
234
235
        // Register fontawesome runtime
236 5
        if ($container->has('.ocubom_twig_extra.svg.font_awesome_finder.inner')) {
237
            // Register runtime
238 5
            $container->register('ocubom_twig_extra.twig_fontawesome_runtime', FontAwesomeRuntime::class)
239 5
                ->setArguments([
240 5
                    new Reference('ocubom_twig_extra.svg.fontawesome_finder'),
241 5
                ])
242 5
                ->addTag('twig.runtime');
243
244
            // Create fontawesome finder
245 5
            $container->register('ocubom_twig_extra.svg.fontawesome_finder', FontAwesomeFinder::class)
246 5
                ->setArguments([
247 5
                    new Reference('.ocubom_twig_extra.svg.font_awesome_finder.inner'),
248 5
                ]);
249
250
            // Create class aliases
251
            // $container->setAlias(FontAwesomeFinder::class, 'ocubom_twig_extra.svg.fontawesome_finder');
252
        }
253
    }
254
255 10
    private function loadWebpackEncore(ContainerBuilder $container, array $config): void
256
    {
257 10
        $container->register('ocubom_twig_extra.twig_webpack_encore_extension', WebpackEncoreExtension::class)
258 10
            ->setArguments([
259 10
                new Reference('webpack_encore.entrypoint_lookup_collection'),
260 10
                $config['output_paths'],
261 10
            ])
262 10
            ->addTag('twig.extension');
263
    }
264
}
265