Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
 
3
declare(strict_types=1);
4
 
5
namespace ZipStream;
6
 
7
use RuntimeException;
8
 
9
/**
10
 * @internal
11
 * TODO: Make class readonly when requiring PHP 8.2 exclusively
12
 */
13
class PackField
14
{
15
    public const MAX_V = 0xFFFFFFFF;
16
 
17
    public const MAX_v = 0xFFFF;
18
 
19
    public function __construct(
20
        public readonly string $format,
21
        public readonly int|string $value
1441 ariadna 22
    ) {}
1 efrain 23
 
24
    /**
25
     * Create a format string and argument list for pack(), then call
26
     * pack() and return the result.
27
     */
28
    public static function pack(self ...$fields): string
29
    {
30
        $fmt = array_reduce($fields, function (string $acc, self $field) {
31
            return $acc . $field->format;
32
        }, '');
33
 
34
        $args = array_map(function (self $field) {
1441 ariadna 35
            switch ($field->format) {
1 efrain 36
                case 'V':
37
                    if ($field->value > self::MAX_V) {
38
                        throw new RuntimeException(print_r($field->value, true) . ' is larger than 32 bits');
39
                    }
40
                    break;
41
                case 'v':
42
                    if ($field->value > self::MAX_v) {
43
                        throw new RuntimeException(print_r($field->value, true) . ' is larger than 16 bits');
44
                    }
45
                    break;
46
                case 'P': break;
47
                default:
48
                    break;
49
            }
50
 
51
            return $field->value;
52
        }, $fields);
53
 
54
        return pack($fmt, ...$args);
55
    }
56
}