-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryEncoder.php
More file actions
44 lines (35 loc) · 1.01 KB
/
BinaryEncoder.php
File metadata and controls
44 lines (35 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<?php
namespace SyncEngine\Service\Serializer;
use SyncEngine\Service\Interface\CodecInterface;
class BinaryEncoder implements CodecInterface
{
const FORMAT = 'binary';
private const ALTERNATIVE_FORMAT = 'base64';
public function encode( mixed $data, string $format, array $context = [] ): string
{
if ( 'base64' === $format ) {
return base64_encode( $data );
}
return base_convert( unpack( 'H*', $data ), 16, 2 );
}
public function decode( string $data, string $format, array $context = [] ): false|string
{
if ( 'base64' === $format ) {
$decoded = base64_decode( $data );
} else {
$decoded = pack( 'H*', base_convert( $data, 2, 16 ) );
}
if ( false === $decoded ) {
$decoded = '';
}
return $decoded;
}
public function supportsEncoding( string $format ): bool
{
return self::FORMAT === $format || self::ALTERNATIVE_FORMAT === $format;
}
public function supportsDecoding( string $format ): bool
{
return self::FORMAT === $format || self::ALTERNATIVE_FORMAT === $format;
}
}