1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Encryption; |
6
|
|
|
|
7
|
|
|
|
8
|
|
|
use Encryption\Cipher\ACipher; |
9
|
|
|
use Encryption\Exceptions\CipherNotImplementedException; |
10
|
|
|
use Encryption\Exceptions\InvalidCipherException; |
11
|
|
|
|
12
|
|
|
class Encryption |
|
|
|
|
13
|
|
|
{ |
14
|
|
|
public const DEFAULT_CIPHER = 'AES-256-CBC'; |
15
|
|
|
|
16
|
4 |
|
public static function getEncryptionObject(?string $cipher = null): ACipher |
17
|
|
|
{ |
18
|
4 |
|
$cipher = strtolower($cipher ?: static::DEFAULT_CIPHER); |
|
|
|
|
19
|
4 |
|
$availableCiphers = static::getCipherMethods(); |
20
|
4 |
|
if (!in_array($cipher, $availableCiphers, true)) { |
21
|
2 |
|
$message = sprintf('Invalid cipher selected [%s]', $cipher); |
22
|
2 |
|
throw new InvalidCipherException($message); |
23
|
|
|
} |
24
|
2 |
|
return static::createEncryptionObject($cipher); |
25
|
|
|
} |
26
|
|
|
|
27
|
2 |
|
protected static function createEncryptionObject(string $cipher): ACipher |
28
|
|
|
{ |
29
|
2 |
|
$className = static::createClassName($cipher); |
30
|
2 |
|
if (!class_exists($className)) { |
31
|
|
|
$message = sprintf('Cipher [%s] has not been implemented yet', $cipher); |
32
|
|
|
throw new CipherNotImplementedException($message); |
33
|
|
|
} |
34
|
2 |
|
return new $className(); |
35
|
|
|
} |
36
|
|
|
|
37
|
4 |
|
protected static function createClassName(string $cipher): string { |
38
|
4 |
|
$crypto = strtoupper(explode('-', $cipher)[0]); |
39
|
4 |
|
return sprintf('%s\%s\%s', |
40
|
4 |
|
'Encryption\Cipher', |
41
|
4 |
|
$crypto, |
42
|
4 |
|
str_replace('-', '', ucwords($cipher)) |
43
|
|
|
); |
44
|
|
|
} |
45
|
|
|
|
46
|
5 |
|
public static function getCipherMethods(): array |
47
|
|
|
{ |
48
|
5 |
|
return array_unique(array_map('strtolower', openssl_get_cipher_methods())); |
49
|
|
|
} |
50
|
|
|
|
51
|
1 |
|
public static function listAvailableCiphers(): array |
52
|
|
|
{ |
53
|
1 |
|
$availableCiphers = []; |
54
|
1 |
|
foreach (static::getCipherMethods() as $cipher) { |
55
|
1 |
|
$className = static::createClassName($cipher); |
56
|
1 |
|
if (class_exists($className)) { |
57
|
1 |
|
$availableCiphers[] = $cipher; |
58
|
|
|
} |
59
|
|
|
} |
60
|
1 |
|
return $availableCiphers; |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|
This check examines a number of code elements and verifies that they conform to the given naming conventions.
You can set conventions for local variables, abstract classes, utility classes, constant, properties, methods, parameters, interfaces, classes, exceptions and special methods.