Passed
Push — master ( f35e26...a6c4d9 )
by Tim
01:51
created

Base64Trait   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Importance

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