Base64Trait::validBase64()   A
last analyzed

Complexity

Conditions 6
Paths 8

Size

Total Lines 19
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 13
c 2
b 0
f 0
dl 0
loc 19
rs 9.2222
cc 6
nc 8
nop 2
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
    /** @var string */
20
    private static string $base64_regex = '/^(?:[a-z0-9+\/]{4})*(?:[a-z0-9+\/]{2}==|[a-z0-9+\/]{3}=)?$/i';
21
22
23
    /***********************************************************************************
24
     *  NOTE:  Custom assertions may be added below this line.                         *
25
     *         They SHOULD be marked as `protected` to ensure the call is forced       *
26
     *          through __callStatic().                                                *
27
     *         Assertions marked `public` are called directly and will                 *
28
     *          not handle any custom exception passed to it.                          *
29
     ***********************************************************************************/
30
31
32
    /**
33
     * Note: This test is not bullet-proof but prevents a string containing illegal characters
34
     * from being passed and ensures the string roughly follows the correct format for a Base64 encoded string
35
     *
36
     * @param string $value
37
     * @param string $message
38
     */
39
    protected static function validBase64(string $value, string $message = ''): void
40
    {
41
        $result = true;
42
43
        if (filter_var($value, FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => self::$base64_regex]]) === false) {
44
            $result = false;
45
        } else {
46
            $decoded = base64_decode($value, true);
47
            if (empty($decoded)) { // Invalid _or_ empty string
48
                $result = false;
49
            } elseif (base64_encode($decoded) !== $value) {
50
                $result = false;
51
            }
52
        }
53
54
        if ($result === false) {
55
            throw new InvalidArgumentException(sprintf(
56
                $message ?: '\'%s\' is not a valid Base64 encoded string',
57
                $value,
58
            ));
59
        }
60
    }
61
}
62