Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
90.00% covered (success)
90.00%
9 / 10
50.00% covered (danger)
50.00%
1 / 2
CRAP
0.00% covered (danger)
0.00%
0 / 1
ContentCompressionService
90.00% covered (success)
90.00%
9 / 10
50.00% covered (danger)
50.00%
1 / 2
5.03
0.00% covered (danger)
0.00%
0 / 1
 compress
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
2.06
 decompress
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
3
1<?php
2declare( strict_types = 1 );
3
4namespace ContentTranslation\Service;
5
6use Deflate;
7use RuntimeException;
8
9/**
10 * This service provides methods to compress and decompress content
11 * It uses gzdeflate for compression and use Deflate::inflate for decompression
12 *
13 * @author Huei Tan
14 * @since 2025.06
15 */
16class ContentCompressionService {
17
18    /**
19     * Prefix for the compressed content
20     */
21    public const COMPRESSION_PREFIX = 'rawdeflate,';
22
23    /**
24     * Compress content using gzdeflate.
25     * Returns the compressed content, otherwise original content.
26     *
27     * @param string $content Content to compress (typically HTML)
28     * @return string Compressed content prefixed with COMPRESSION_PREFIX and base64-encoded,
29     *                or original content if compression fails
30     */
31    public function compress( string $content ): string {
32        $compressed = gzdeflate( $content );
33        if ( $compressed === false ) {
34            // If compression fails, return the original content
35            return $content;
36        }
37
38        return self::COMPRESSION_PREFIX . base64_encode( $compressed );
39    }
40
41    /**
42     * Decompress content using Deflate::inflate
43     *
44     * @param string $content Potentially compressed content
45     * @return string Decompressed content
46     * @throws RuntimeException If decompression fails
47     */
48    public function decompress( string $content ): string {
49        if ( Deflate::isDeflated( $content ) ) {
50            $status = Deflate::inflate( $content );
51            if ( !$status->isGood() ) {
52                throw new RuntimeException( (string)$status );
53            }
54            return $status->getValue();
55        }
56
57        return $content;
58    }
59}