-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEncoder.php
More file actions
52 lines (43 loc) · 1.19 KB
/
Encoder.php
File metadata and controls
52 lines (43 loc) · 1.19 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
<?php
declare(strict_types=1);
namespace Chubbyphp\DecodeEncode\Encoder;
use Chubbyphp\DecodeEncode\LogicException;
final class Encoder implements EncoderInterface
{
/**
* @var array<string, TypeEncoderInterface>
*/
private array $encoderTypes = [];
/**
* @param list<TypeEncoderInterface> $encoderTypes
*/
public function __construct(array $encoderTypes)
{
foreach ($encoderTypes as $encoderType) {
$this->addTypeEncoder($encoderType);
}
}
/**
* @return list<string>
*/
public function getContentTypes(): array
{
return array_keys($this->encoderTypes);
}
/**
* @param array<string, mixed> $data
*
* @throws LogicException
*/
public function encode(array $data, string $contentType): string
{
if (isset($this->encoderTypes[$contentType])) {
return $this->encoderTypes[$contentType]->encode($data);
}
throw LogicException::createMissingContentType($contentType);
}
private function addTypeEncoder(TypeEncoderInterface $encoderType): void
{
$this->encoderTypes[$encoderType->getContentType()] = $encoderType;
}
}