Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
87.50% covered (warning)
87.50%
7 / 8
50.00% covered (danger)
50.00%
1 / 2
CRAP
0.00% covered (danger)
0.00%
0 / 1
Archiver
87.50% covered (warning)
87.50%
7 / 8
50.00% covered (danger)
50.00%
1 / 2
4.03
0.00% covered (danger)
0.00%
0 / 1
 compressGzip
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
2.06
 extractGzip
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
1<?php
2
3declare(strict_types=1);
4
5namespace PeServer\Core;
6
7use PeServer\Core\Binary;
8use PeServer\Core\Errors\ErrorHandler;
9use PeServer\Core\Throws\ArchiveException;
10use PeServer\Core\Throws\Throws;
11use ValueError;
12
13/**
14 * アーカイブ処理。
15 */
16abstract class Archiver
17{
18    #region define
19
20    /**
21     * GZIP: デフォルト。
22     *
23     * `FORCE_GZIP` ラッパー。
24     */
25    public const GZIP_DEFAULT = FORCE_GZIP;
26    /**
27     * GZIP: RFC 1950 準拠。
28     *
29     * `FORCE_DEFLATE` ラッパー。
30     */
31    public const GZIP_DEFLATE = FORCE_DEFLATE;
32
33    #endregion
34
35    #region function
36
37    /**
38     * GZIP圧縮処理。
39     *
40     * `gzencode` ラッパー。
41     *
42     * @param Binary $data 圧縮するデータ。
43     * @param -1|0|1|2|3|4|5|6|7|8|9 $level 圧縮レベル。
44     * @param int $encoding `self::GZIP_DEFAULT` か `self::FORCE_DEFLATE` を指定。
45     * @phpstan-param self::GZIP_* $encoding
46     * @return Binary 圧縮データ。
47     * @throws ArchiveException 失敗。
48     * @see https://www.php.net/manual/function.gzencode.php
49     */
50    public static function compressGzip(Binary $data, int $level = -1, int $encoding = self::GZIP_DEFAULT): Binary
51    {
52        $result = Throws::wrap(ValueError::class, ArchiveException::class, fn () => gzencode($data->raw, $level, $encoding));
53        if ($result === false) {
54            throw new ArchiveException();
55        }
56
57        return new Binary($result);
58    }
59
60    /**
61     * GZIP展開処理。
62     *
63     * `gzdecode` ラッパー。
64     *
65     * @param Binary $data 圧縮データ。
66     * @return Binary 展開データ。
67     * @throws ArchiveException 失敗。
68     * @see https://www.php.net/manual/function.gzdecode.php
69     */
70    public static function extractGzip(Binary $data): Binary
71    {
72        $result = ErrorHandler::trap(fn () => gzdecode($data->raw));
73        if (!$result->success) {
74            throw new ArchiveException();
75        }
76
77        return new Binary($result->value);
78    }
79
80    #endregion
81}