Passed
Pull Request — feature/unit-tests (#37)
by Daniel
06:16
created

prependDoctrineConfig()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 2
c 2
b 0
f 0
dl 0
loc 5
ccs 3
cts 3
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
/*
4
 * This file is part of the Silverback API Component Bundle Project
5
 *
6
 * (c) Daniel West <[email protected]>
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
declare(strict_types=1);
13
14
namespace Silverback\ApiComponentBundle\DependencyInjection;
15
16
use Exception;
17
use RuntimeException;
18
use Silverback\ApiComponentBundle\Doctrine\Extension\TablePrefixExtension;
19
use Silverback\ApiComponentBundle\Entity\Core\ComponentInterface;
20
use Silverback\ApiComponentBundle\EventListener\Doctrine\UserListener;
21
use Silverback\ApiComponentBundle\Factory\Mailer\User\ChangeEmailVerificationEmailFactory;
22
use Silverback\ApiComponentBundle\Factory\Mailer\User\PasswordChangedEmailFactory;
23
use Silverback\ApiComponentBundle\Factory\Mailer\User\PasswordResetEmailFactory;
24
use Silverback\ApiComponentBundle\Factory\Mailer\User\UserEnabledEmailFactory;
25
use Silverback\ApiComponentBundle\Factory\Mailer\User\UsernameChangedEmailFactory;
26
use Silverback\ApiComponentBundle\Factory\Mailer\User\WelcomeEmailFactory;
27
use Silverback\ApiComponentBundle\Factory\User\UserFactory;
28
use Silverback\ApiComponentBundle\Form\FormTypeInterface;
29
use Silverback\ApiComponentBundle\Form\Type\User\ChangePasswordType;
30
use Silverback\ApiComponentBundle\Form\Type\User\NewEmailAddressType;
31
use Silverback\ApiComponentBundle\Form\Type\User\UserRegisterType;
32
use Silverback\ApiComponentBundle\Mailer\UserMailer;
33
use Silverback\ApiComponentBundle\Manager\User\PasswordManager;
34
use Silverback\ApiComponentBundle\Repository\User\UserRepository;
35
use Silverback\ApiComponentBundle\Security\TokenAuthenticator;
36
use Silverback\ApiComponentBundle\Security\UserChecker;
37
use Symfony\Component\Config\FileLocator;
38
use Symfony\Component\DependencyInjection\ContainerBuilder;
39
use Symfony\Component\DependencyInjection\Extension\Extension;
40
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
41
use Symfony\Component\DependencyInjection\Loader\PhpFileLoader;
42
43
/**
44
 * @author Daniel West <[email protected]>
45
 */
46
class SilverbackApiComponentExtension extends Extension implements PrependExtensionInterface
47
{
48
    /**
49
     * @throws Exception
50
     */
51 1
    public function load(array $configs, ContainerBuilder $container): void
52
    {
53 1
        $configuration = new Configuration();
54 1
        $config = $this->processConfiguration($configuration, $configs);
55
56 1
        $this->loadServiceConfig($container);
57
58 1
        $definition = $container->getDefinition(TablePrefixExtension::class);
59 1
        $definition->setArgument('$prefix', $config['table_prefix']);
60
61 1
        $definition = $container->getDefinition(TokenAuthenticator::class);
62 1
        $definition->setArgument('$tokens', $config['security']['tokens']);
63
64 1
        $definition = $container->getDefinition(PasswordManager::class);
65 1
        $definition->setArgument('$tokenTtl', $config['user']['password_reset']['repeat_ttl_seconds']);
66
67 1
        $definition = $container->getDefinition(UserRepository::class);
68 1
        $definition->setArgument('$passwordRequestTimeout', $config['user']['password_reset']['request_timeout_seconds']);
69 1
        $definition->setArgument('$entityClass', $config['user']['class_name']);
70
71 1
        $this->setEmailVerificationArguments($container, $config['user']['email_verification']);
72 1
        $this->setUserClassArguments($container, $config['user']['class_name']);
73 1
        $this->setMailerServiceArguments($container, $config);
74 1
    }
75
76 1
    private function setEmailVerificationArguments(ContainerBuilder $container, array $emailVerificationConfig): void
77
    {
78 1
        $definition = $container->getDefinition(UserChecker::class);
79 1
        $definition->setArgument('$denyUnverifiedLogin', $emailVerificationConfig['deny_unverified_login']);
80
81 1
        $definition = $container->getDefinition(UserListener::class);
82 1
        $definition->setArgument('$initialEmailVerifiedState', $emailVerificationConfig['default_value']);
83 1
        $definition->setArgument('$verifyEmailOnRegister', $emailVerificationConfig['verify_on_register']);
84 1
        $definition->setArgument('$verifyEmailOnChange', $emailVerificationConfig['verify_on_change']);
85 1
    }
86
87 1
    private function setUserClassArguments(ContainerBuilder $container, string $userClass): void
88
    {
89 1
        $definition = $container->getDefinition(UserFactory::class);
90 1
        $definition->setArgument('$userClass', $userClass);
91
92 1
        $definition = $container->getDefinition(ChangePasswordType::class);
93 1
        $definition->setArgument('$userClass', $userClass);
94
95 1
        $definition = $container->getDefinition(NewEmailAddressType::class);
96 1
        $definition->setArgument('$userClass', $userClass);
97
98 1
        $definition = $container->getDefinition(UserRegisterType::class);
99 1
        $definition->setArgument('$userClass', $userClass);
100 1
    }
101
102 1
    private function setMailerServiceArguments(ContainerBuilder $container, array $config): void
103
    {
104 1
        $definition = $container->getDefinition(UserMailer::class);
105 1
        $definition->setArgument('$context', [
106 1
            'website_name' => $config['website_name'],
107
        ]);
108
109
        $mapping = [
110 1
            PasswordChangedEmailFactory::class => 'password_changed',
111
            UserEnabledEmailFactory::class => 'user_enabled',
112
            UsernameChangedEmailFactory::class => 'username_changed',
113
            WelcomeEmailFactory::class => 'welcome',
114
        ];
115 1
        foreach ($mapping as $class => $key) {
116 1
            $definition = $container->getDefinition($class);
117 1
            $definition->setArgument('$subject', $config['user']['emails'][$key]['subject']);
118 1
            $definition->setArgument('$enabled', $config['user']['emails'][$key]['enabled']);
119 1
            if (WelcomeEmailFactory::class === $class) {
120 1
                $definition->setArgument('$defaultRedirectPath', $config['user']['email_verification']['email']['default_redirect_path']);
121 1
                $definition->setArgument('$redirectPathQueryKey', $config['user']['email_verification']['email']['redirect_path_query']);
122
            }
123
        }
124
125
        $mapping = [
126 1
            ChangeEmailVerificationEmailFactory::class => 'email_verification',
127
            PasswordResetEmailFactory::class => 'password_reset',
128
        ];
129 1
        foreach ($mapping as $class => $key) {
130 1
            $definition = $container->getDefinition($class);
131 1
            $definition->setArgument('$subject', $config['user'][$key]['email']['subject']);
132 1
            $definition->setArgument('$enabled', true);
133 1
            $definition->setArgument('$defaultRedirectPath', $config['user'][$key]['email']['default_redirect_path']);
134 1
            $definition->setArgument('$redirectPathQueryKey', $config['user'][$key]['email']['redirect_path_query']);
135
        }
136 1
    }
137
138
    /**
139
     * @throws Exception
140
     */
141 1
    private function loadServiceConfig(ContainerBuilder $container): void
142
    {
143 1
        $container->registerForAutoconfiguration(FormTypeInterface::class)
144 1
            ->addTag('silverback_api_component.form_type');
145
146 1
        $container->registerForAutoconfiguration(ComponentInterface::class)
147 1
            ->addTag('silverback_api_component.entity.component');
148
149 1
        $loader = new PhpFileLoader(
150 1
            $container,
151 1
            new FileLocator(__DIR__ . '/../Resources/config')
152
        );
153 1
        $loader->load('services.php');
154 1
    }
155
156 1
    public function prepend(ContainerBuilder $container): void
157
    {
158 1
        $configs = $container->getExtensionConfig($this->getAlias());
159 1
        $configuration = new Configuration();
160 1
        $config = $this->processConfiguration($configuration, $configs);
161 1
        $srcBase = __DIR__ . '/..';
162 1
        $configBasePath = $srcBase . '/Resources/config/api_platform';
163 1
        $mappingPaths = [$srcBase . '/Entity/Core'];
164 1
        foreach ($config['enabled_components'] as $key => $enabled_component) {
165 1
            if (true === $enabled_component) {
166 1
                $mappingPaths[] = sprintf('%s/%s.yaml', $configBasePath, $key);
167
            }
168
        }
169 1
        $websiteName = $config['website_name'];
170 1
        $container->prependExtensionConfig(
171 1
            'api_platform',
172
            [
173 1
                'title' => $websiteName,
174 1
                'description' => sprintf('API for %s', $websiteName),
175
                'collection' => [
176
                    'pagination' => [
177
                        'client_items_per_page' => true,
178
                        'items_per_page_parameter_name' => 'perPage',
179
                        'maximum_items_per_page' => 100,
180
                    ],
181
                ],
182
                'mapping' => [
183 1
                    'paths' => $mappingPaths,
184
                ],
185
                'swagger' => [
186
                    'api_keys' => [
187
                        'API Token' => [
188
                            'name' => 'X-AUTH-TOKEN',
189
                            'type' => 'header',
190
                        ],
191
                        'JWT (use prefix `Bearer`)' => [
192
                            'name' => 'Authorization',
193
                            'type' => 'header',
194
                        ],
195
                    ],
196
                ],
197
            ]
198
        );
199
200 1
        $bundles = $container->getParameter('kernel.bundles');
201 1
        if (isset($bundles['DoctrineBundle'])) {
202 1
            $this->prependDoctrineConfig($container);
203
        }
204 1
        if (isset($bundles['LiipImagineBundle'])) {
205 1
            $this->prependLiipConfig($container);
206
        }
207 1
    }
208
209 1
    private function prependDoctrineConfig(ContainerBuilder $container)
210
    {
211 1
        $container->prependExtensionConfig(
212 1
            'doctrine',
213
            [
214
                //                'orm' => [
215
                //                    'filters' => [
216
                //                        'publishable' => [
217
                //                            'class' => PublishableFilter::class,
218
                //                            'enabled' => false
219
                //                        ]
220
                //                    ]
221
                //                ]
222 1
            ]
223
        );
224 1
    }
225
226 1
    private function prependLiipConfig(ContainerBuilder $container)
227
    {
228 1
        $projectDir = $container->getParameter('kernel.project_dir');
229 1
        $uploadsDir = $projectDir . '/var/uploads';
230 1
        if (!@mkdir($uploadsDir) && !is_dir($uploadsDir)) {
231
            throw new RuntimeException(sprintf('Directory "%s" was not created', $uploadsDir));
232
        }
233 1
        $container->prependExtensionConfig(
234 1
            'liip_imagine',
235
            [
236
                'loaders' => [
237
                    'default' => [
238
                        'filesystem' => [
239
                            'data_root' => [
240 1
                                'uploads' => $uploadsDir,
241 1
                                'default' => $projectDir . '/public',
242
                            ],
243
                        ],
244
                    ],
245
                ],
246
                'filter_sets' => [
247
                    'placeholder_square' => [
248
                        'jpeg_quality' => 10,
249
                        'png_compression_level' => 9,
250
                        'filters' => [
251
                            'thumbnail' => [
252
                                'size' => [80, 80],
253
                                'mode' => 'outbound',
254
                            ],
255
                        ],
256
                    ],
257
                    'placeholder' => [
258
                        'jpeg_quality' => 10,
259
                        'png_compression_level' => 9,
260
                        'filters' => [
261
                            'thumbnail' => [
262
                                'size' => [100, 100],
263
                                'mode' => 'inset',
264
                            ],
265
                        ],
266
                    ],
267
                    'thumbnail' => [
268
                        'jpeg_quality' => 100,
269
                        'png_compression_level' => 0,
270
                        'filters' => [
271
                            'upscale' => [
272
                                'min' => [636, 636],
273
                            ],
274
                            'thumbnail' => [
275
                                'size' => [636, 636],
276
                                'mode' => 'inset',
277
                                'allow_upscale' => true,
278
                            ],
279
                        ],
280
                    ],
281
                ],
282
            ]
283
        );
284 1
    }
285
}
286