Base64Trait   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
wmc 6
eloc 14
c 3
b 0
f 0
dl 0
loc 40
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
A validBase64() 0 19 6
1
<?php
2
3
declare(strict_types=1);
4
5
namespace SimpleSAML\Assert;
6
7
use InvalidArgumentException;
8
9
use function base64_decode;
10
use function base64_encode;
11
use function filter_var;
12
use function sprintf;
13
14
/**
15
 * @package simplesamlphp/assert
16
 */
17
trait Base64Trait
18
{
19
    private static string $base64_regex = '/^(?:[a-z0-9+\/]{4})*(?:[a-z0-9+\/]{2}==|[a-z0-9+\/]{3}=)?$/i';
20
21
22
    /***********************************************************************************
23
     *  NOTE:  Custom assertions may be added below this line.                         *
24
     *         They SHOULD be marked as `protected` to ensure the call is forced       *
25
     *          through __callStatic().                                                *
26
     *         Assertions marked `public` are called directly and will                 *
27
     *          not handle any custom exception passed to it.                          *
28
     ***********************************************************************************/
29
30
31
    /**
32
     * Note: This test is not bullet-proof but prevents a string containing illegal characters
33
     * from being passed and ensures the string roughly follows the correct format for a Base64 encoded string
34
     *
35
     * @param string $value
36
     * @param string $message
37
     */
38
    protected static function validBase64(string $value, string $message = ''): void
39
    {
40
        $result = true;
41
42
        if (filter_var($value, FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => self::$base64_regex]]) === false) {
43
            $result = false;
44
        } else {
45
            $decoded = base64_decode($value, true);
46
            if (empty($decoded)) { // Invalid _or_ empty string
47
                $result = false;
48
            } elseif (base64_encode($decoded) !== $value) {
49
                $result = false;
50
            }
51
        }
52
53
        if ($result === false) {
54
            throw new InvalidArgumentException(sprintf(
55
                $message ?: '\'%s\' is not a valid Base64 encoded string',
56
                $value,
57
            ));
58
        }
59
    }
60
}
61