Passed
Push — master ( 098479...e4440e )
by Tim
01:55
created

Base64Trait   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 7
eloc 16
c 1
b 0
f 0
dl 0
loc 43
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
B validBase64() 0 21 7
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;
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
        } elseif (strlen($value) % 4 !== 0) {
47
            $result = false;
48
        } else {
49
            $decoded = base64_decode($value, true);
50
            if (empty($decoded)) { // Invalid _or_ empty string
51
                $result = false;
52
            } elseif (base64_encode($decoded) !== $value) {
53
                $result = false;
54
            }
55
        }
56
57
        if ($result === false) {
58
            throw new InvalidArgumentException(sprintf(
59
                $message ?: '\'%s\' is not a valid Base64 encoded string',
60
                $value,
61
            ));
62
        }
63
    }
64
}
65