Completed
Push — master ( 2bc6ba...1ab902 )
by Francesco
09:17
created

MesCryptoExtension::createKeyDefinition()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 14
ccs 9
cts 9
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 9
nc 1
nop 2
crap 1
1
<?php
2
3
/*
4
 * This file is part of the MesCryptoBundle package.
5
 *
6
 * (c) Francesco Cartenì <http://www.multimediaexperiencestudio.it/>
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 Mes\Security\CryptoBundle\DependencyInjection;
13
14
use Symfony\Component\Config\FileLocator;
15
use Symfony\Component\DependencyInjection\Alias;
16
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
17
use Symfony\Component\DependencyInjection\ContainerBuilder;
18
use Symfony\Component\DependencyInjection\Definition;
19
use Symfony\Component\DependencyInjection\Loader;
20
use Symfony\Component\DependencyInjection\Reference;
21
use Symfony\Component\ExpressionLanguage\Expression;
22
use Symfony\Component\HttpKernel\DependencyInjection\ConfigurableExtension;
23
24
/**
25
 * Class MesCryptoExtension.
26
 */
27
class MesCryptoExtension extends ConfigurableExtension implements CompilerPassInterface
28
{
29
    /**
30
     * @var bool
31
     */
32
    private $loaderEnabled = false;
33
34
    /**
35
     * @var Expression
36
     */
37
    private $loadKey;
38
39
    /**
40
     * @var Expression
41
     */
42
    private $loadSecret;
43
44
    /**
45
     * @param array            $config
46
     * @param ContainerBuilder $container
47
     *
48
     * @return Configuration
49
     */
50 5
    public function getConfiguration(array $config, ContainerBuilder $container)
51
    {
52 5
        return new Configuration();
53
    }
54
55
    /**
56
     * @codeCoverageIgnore
57
     *
58
     * @return string
59
     */
60
    public function getNamespace()
61
    {
62
        return 'http://multimediaexperiencestudio.it/schema/dic/crypto';
63
    }
64
65
    /**
66
     * @codeCoverageIgnore
67
     *
68
     * @return string|bool
69
     */
70
    public function getXsdValidationBasePath()
71
    {
72
        return __DIR__.'/../Resources/config/schema';
0 ignored issues
show
Bug Best Practice introduced by
The return type of return __DIR__ . '/../Resources/config/schema'; (string) is incompatible with the return type of the parent method Symfony\Component\Depend...etXsdValidationBasePath of type boolean.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
73
    }
74
75
    /**
76
     * @param ContainerBuilder $container
77
     */
78
    public function process(ContainerBuilder $container)
79
    {
80
        if (!$this->loaderEnabled) {
81
            return;
82
        }
83
84
        foreach ($container->findTaggedServiceIds('mes_crypto.loader') as $id => $attributes) {
85
            foreach ($attributes as $attribute) {
86
87
                // Sets the loader resource.
88
                $container->findDefinition($id)
89
                          ->addMethodCall('setResource', array($attribute['resource']));
90
91
                // Load secret from loader.
92
                $container->getDefinition('mes_crypto.key_manager_wrapper')
93
                          ->setMethodCalls(array())
94
                          ->addMethodCall('setSecret', array($this->loadSecret));
95
96
                // Sets Defuse KeyProtectedByPassword.
97
                $container->findDefinition('mes_crypto.raw_key')
98
                          ->setClass('Defuse\Crypto\KeyProtectedByPassword')
99
                          ->setArguments(array($this->loadKey))
100
                          ->setFactory(array(
101
                              'Defuse\Crypto\KeyProtectedByPassword',
102
                              'loadFromAsciiSafeString',
103
                          ));
104
105
                // Sets the key
106
                $this->createKeyDefinition($container, $this->loadSecret);
107
            }
108
109
            $container->setAlias('mes_crypto.loader', $id);
110
111
            return;
112
        }
113
    }
114
115
    /**
116
     * Configures the passed container according to the merged configuration.
117
     *
118
     * @param array            $mergedConfig
119
     * @param ContainerBuilder $container
120
     */
121 5
    protected function loadInternal(array $mergedConfig, ContainerBuilder $container)
122
    {
123 5
        $loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
124 5
        $loader->load('services.xml');
125
126 5
        if ($this->isConfigEnabled($container, $mergedConfig['loader'])) {
127
            $this->loaderEnabled = true;
128
        }
129
130 5
        $this->createKeyStorage($mergedConfig, $container);
131 5
        $this->createKeyGenerator($mergedConfig, $container);
132 5
        $this->generateKey($mergedConfig, $container);
133 5
        $this->createEncryption($mergedConfig, $container);
134 5
    }
135
136
    /**
137
     * @param $config
138
     * @param ContainerBuilder $container
139
     */
140 5
    private function createKeyStorage($config, ContainerBuilder $container)
141
    {
142
        // Key Storage
143 5
        if (null !== $config['key_storage']) {
144 1
            $container->setAlias(new Alias('mes_crypto.key_storage', false), $config['key_storage']);
145
        }
146 5
    }
147
148
    /**
149
     * @param $config
150
     * @param ContainerBuilder $container
151
     */
152 5
    private function createKeyGenerator($config, ContainerBuilder $container)
153
    {
154
        // Key Generator
155 5
        if (null !== $config['key_generator']) {
156 1
            $container->setAlias(new Alias('mes_crypto.key_generator', false), $config['key_generator']);
157
        }
158 5
    }
159
160
    /**
161
     * @param $config
162
     * @param ContainerBuilder $container
163
     */
164 5
    private function generateKey($config, ContainerBuilder $container)
165
    {
166 5
        $secret = $config['secret'];
167 5
        $ext_secret = $config['external_secret'];
168 5
        $key = $config['key']['key'];
169 5
        $path = $config['key']['path'];
170
171
        // Secret Expression.
172 5
        $this->loadSecret = new Expression('service("mes_crypto.loader").loadSecret()');
173
174
        // Key Expression.
175 5
        $this->loadKey = new Expression('service("mes_crypto.loader").loadKey()');
176
177
        // Conditions.
178 5
        $createRandomKey = (null === $key) && (null === $path);
179
180 5
        $keyIsExternal = (true === !$createRandomKey) && (null !== $path) && (null === $key);
181
182 5
        $secretExists = (null !== $secret) || (true === $ext_secret);
183 5
        $secretIsExternal = (true === $secretExists) && (true === $ext_secret) && (null === $secret);
184
185 5
        $rawKeyDefinition = new Definition();
186 5
        $defuseKey = $secretExists ? 'Defuse\Crypto\KeyProtectedByPassword' : 'Defuse\Crypto\Key';
187
188
        // Creates a Key from an encoded version.
189 5
        if (!$createRandomKey) {
190 3
            if ($keyIsExternal) {
191
                // Sets the .crypto file path to CryptoLoader.
192 2
                $this->setCryptoLoaderResource($container, $path);
193
            }
194
195
            // Reads encoded key from configuration file if key is not external.
196 3
            $rawKeyDefinition->setClass($defuseKey)
197 3
                             ->setFactory(array(
198 3
                                 $defuseKey,
199 3
                                 'loadFromAsciiSafeString',
200
                             ));
201 3
            $rawKeyDefinition->setArguments(array(
202 3
                $keyIsExternal ? $this->loadKey : $key,
203
            ));
204
        } else {
205 2
            $rawKeyDefinition->setClass($defuseKey)
206 2
                             ->setArguments($secretExists ? array($secretIsExternal ? $this->loadSecret : $secret) : array())
207 2
                             ->setFactory($secretExists ? array(
208 1
                                 'Defuse\Crypto\KeyProtectedByPassword',
209
                                 'createRandomPasswordProtectedKey',
210
                             ) : array(
211 2
                                 'Defuse\Crypto\Key',
212
                                 'createNewRandomKey',
213
                             ));
214
        }
215
216 5
        if (($createRandomKey || (!$createRandomKey && !$keyIsExternal)) && !$this->loaderEnabled) {
217 3
            $container->removeAlias('mes_crypto.loader');
218
        }
219
220 5
        $container->setDefinition('mes_crypto.raw_key', $rawKeyDefinition)
221 5
                  ->setPublic(false);
222
223
        // Key
224 5
        $this->createKeyDefinition($container, $secretExists ? ($secretIsExternal ? $this->loadSecret : $secret) : null);
225
226 5
        $keyManagerDefinition = $container->findDefinition('mes_crypto.key_manager_wrapper');
227
228
        // Save the generated key.
229 5
        $keyManagerDefinition->addMethodCall('setKey', array(new Reference('mes_crypto.key')));
230
231
        // Save the secret.
232 5
        if ($secretExists) {
233 4
            $keyManagerDefinition->addMethodCall('setSecret', array(
234 4
                $secretExists ? ($secretIsExternal ? $this->loadSecret : $secret) : null,
235
            ));
236
        }
237 5
    }
238
239 5
    private function createKeyDefinition(ContainerBuilder $container, $secret)
240
    {
241 5
        $keyDefinition = new Definition('Mes\Security\CryptoBundle\Model\Key', array(
242 5
            new Reference('mes_crypto.raw_key'),
243 5
            $secret,
244
        ));
245 5
        $keyDefinition->setFactory(array(
246 5
            'Mes\Security\CryptoBundle\Model\Key',
247
            'create',
248
        ))
249 5
                      ->setPublic(false);
250
251 5
        $container->setDefinition('mes_crypto.key', $keyDefinition);
252 5
    }
253
254
    /**
255
     * @param $config
256
     * @param ContainerBuilder $container
257
     */
258 5
    private function createEncryption($config, ContainerBuilder $container)
259
    {
260 5
        if (null !== $config['encryption']) {
261 1
            $container->setAlias(new Alias('mes_crypto.encryption'), $config['encryption']);
262
        }
263 5
    }
264
265
    /**
266
     * @param ContainerBuilder $container
267
     * @param $resource
268
     *
269
     * @return Definition
270
     */
271 2
    private function setCryptoLoaderResource(ContainerBuilder $container, $resource)
272
    {
273 2
        $container->findDefinition('mes_crypto.loader')
274 2
                  ->addMethodCall('setResource', array($resource));
275 2
    }
276
}
277