axy/codecs-base64vlq
PHP codec for Base64 VLQ (variable-length quantity) encoding/decoding of integer sequences, suitable for compact text representations (e.g., JavaScript/CSS source maps). Converts signed ints to VLQ digits and maps them into Base64 characters.
Installation:
composer require axy/codecs-base64vlq
Ensure your composer.json has "php": "^8.1" or higher.
First Use Case: Encode/decode a simple array of integers:
use axy\codecs\base64vlq\Encoder;
$encoder = Encoder::getStandardInstance();
$encoded = $encoder->encode([12345, -12345, 0]); // Output: "yjYzjYA"
$decoded = $encoder->decode($encoded); // Output: [12345, -12345, 0]
Where to Look First:
Encoder class: Core functionality (methods: encode(), decode()).axy\codecs\base64vlq\Encoder\Errors for error handling.Standard Encoding/Decoding:
Use the singleton Encoder::getStandardInstance() for default Base64VLQ (6-bit, signed, standard alphabet).
$encoder = Encoder::getStandardInstance();
$data = [1, -2, 3];
$encoded = $encoder->encode($data);
$decoded = $encoder->decode($encoded);
Custom Alphabets/Bit Lengths: Override defaults for niche use cases (e.g., compact storage, non-standard alphabets):
$customEncoder = new Encoder('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef', 4, false);
$encoded = $customEncoder->encode([1, 2, 3]); // Uses custom 4-bit VLQ
Batch Processing: Loop through arrays of data (e.g., database records) and encode/decode in bulk:
$records = [[1, -2], [3, -4]];
$encodedRecords = array_map([$encoder, 'encode'], $records);
Integration with JSON/XML: Useful for storing compact integer sequences in text formats:
$jsonData = json_encode(['coordinates' => $encoder->encode([10, -20, 30])]);
Cache::put('vlq_data', $encoder->encode($data), $ttl);
TEXT columns (e.g., for serialized data).return response()->json(['data' => $encoder->encode($array)]);
Bit Length Mismatch:
$bits too large for the alphabet will throw InvalidBase64Input.$bits <= log2(count($alphabet)).Sign Handling:
$signed (3rd constructor arg) drops negative number support.Continuation Bit Errors:
1 in continuation bit) throw InvalidVLQSequence.Alphabet Case Sensitivity:
A-Z, a-z).strtolower()) for consistency.\Log::debug('Encoded:', ['data' => $encodedString]);
assert($decoded === $originalData, 'Decoding failed!');
$urlSafeEncoder = new Encoder('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_', 6);
try {
$decoded = $encoder->decode($input);
} catch (\axy\codecs\base64vlq\Encoder\Errors\InvalidVLQSequence $e) {
\Log::error('VLQ error:', ['input' => $input]);
return null;
}
$this->app->singleton(Encoder::class, function () {
return Encoder::getStandardInstance();
});
$this->info('Encoded data: ' . $encoder->encode($data));
How can I help you explore Laravel packages today?