Proyectos de Subversion Moodle

Rev

| 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
22
    ) {
23
    }
24
 
25
    /**
26
     * Create a format string and argument list for pack(), then call
27
     * pack() and return the result.
28
     */
29
    public static function pack(self ...$fields): string
30
    {
31
        $fmt = array_reduce($fields, function (string $acc, self $field) {
32
            return $acc . $field->format;
33
        }, '');
34
 
35
        $args = array_map(function (self $field) {
36
            switch($field->format) {
37
                case 'V':
38
                    if ($field->value > self::MAX_V) {
39
                        throw new RuntimeException(print_r($field->value, true) . ' is larger than 32 bits');
40
                    }
41
                    break;
42
                case 'v':
43
                    if ($field->value > self::MAX_v) {
44
                        throw new RuntimeException(print_r($field->value, true) . ' is larger than 16 bits');
45
                    }
46
                    break;
47
                case 'P': break;
48
                default:
49
                    break;
50
            }
51
 
52
            return $field->value;
53
        }, $fields);
54
 
55
        return pack($fmt, ...$args);
56
    }
57
}