-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDataFormatter.php
More file actions
78 lines (64 loc) · 1.98 KB
/
DataFormatter.php
File metadata and controls
78 lines (64 loc) · 1.98 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<?php
namespace SyncEngine\Service;
use SyncEngine\Exception\CodecException;
use SyncEngine\Model\CodecModel;
use SyncEngine\Model\Trait\Format;
class DataFormatter
{
use Format;
public function encode( string|iterable|CodecModel $format, iterable $data, iterable $config = [] ): iterable|string
{
try {
return $this->getEncoder( $format, $config )?->encode( $data ) ?? $data;
} catch ( \Exception $e ) {
$message = $e->getMessage();
if ( 'syntax error' === strtolower( $message ) ) {
$message = $e::class . ': ' . $message;
}
throw new CodecException( $message, $e->getCode(), $e );
}
}
public function decode( string|iterable|CodecModel $format, string $data, iterable $config = [] ): iterable|string
{
try {
return $this->getEncoder( $format, $config )?->decode( $data ) ?? $data;
} catch ( \Exception $e ) {
$message = $e->getMessage();
if ( 'syntax error' === strtolower( $message ) ) {
$message = $e::class . ': ' . $message;
}
throw new CodecException( $message, $e->getCode(), $e );
}
}
public function getContentType( $format, iterable $config = [] ): string
{
return $this->getEncoder( $format, $config )?->getContentType( $config, $format ) ?? '';
}
public function getEncoder( $format, iterable $config = [] ): ?CodecModel
{
if ( $format instanceof CodecModel ) {
return $format;
}
$formatType = $format;
$formatConfig = [];
if ( is_iterable( $format ) ) {
$formatType = $format['_class'] ?? $format['format'] ?? '';
$formatConfig = $format;
}
$prefix = $formatType . '_';
foreach ( $config as $key => $value ) {
if ( str_starts_with( $key, $prefix ) ) {
if ( ! isset( $formatConfig[ $key ] ) ) {
$formatConfig[ $key ] = $value;
}
$context = substr( $key, strlen( $prefix ) );
if ( ! isset( $formatConfig[ $context ] ) ) {
$formatConfig[ $context ] = $value;
}
}
}
$codec = CodecModel::create( $formatType );
$codec?->setEncoder( $formatConfig );
return $codec;
}
}