EncryptionServiceProvider::key()   A
last analyzed

Complexity

Conditions 2
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 1
nop 1
dl 0
loc 6
ccs 0
cts 5
cp 0
crap 6
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Stidges\LaravelSodiumEncryption;
4
5
use RuntimeException;
6
use Illuminate\Support\Str;
7
use Illuminate\Support\ServiceProvider;
8
9
class EncryptionServiceProvider extends ServiceProvider
10
{
11
    /**
12
     * Register the service provider.
13
     *
14
     * @return void
15
     */
16
    public function register()
17
    {
18
        $this->app->singleton('encrypter.sodium', function ($app) {
19
            $config = $app->make('config')->get('app');
20
21
            if (Str::startsWith($key = $this->key($config), 'base64:')) {
22
                $key = base64_decode(substr($key, 7));
23
            }
24
25
            return new Encrypter($key);
26
        });
27
28
        $this->app->alias('encrypter.sodium', Encrypter::class);
29
    }
30
31
    /**
32
     * Extract the encryption key from the given configuration.
33
     *
34
     * @param  array  $config
35
     * @return string
36
     *
37
     * @throws \RuntimeException
38
     */
39
    protected function key(array $config)
40
    {
41
        return tap($config['key'], function ($key) {
42
            if (empty($key)) {
43
                throw new RuntimeException(
44
                    'No application encryption key has been specified.'
45
                );
46
            }
47
        });
48
    }
49
}
50