1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace RealPage\JsonApi; |
5
|
|
|
|
6
|
|
|
use Neomerx\JsonApi\Encoder\Encoder; |
7
|
|
|
use Neomerx\JsonApi\Encoder\EncoderOptions; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Class EncoderService |
11
|
|
|
*/ |
12
|
|
|
class EncoderService |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* @var array |
16
|
|
|
*/ |
17
|
|
|
protected $config; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @var array |
21
|
|
|
*/ |
22
|
|
|
protected $encoders = []; |
23
|
|
|
|
24
|
|
|
public function __construct(array $config = []) |
25
|
|
|
{ |
26
|
|
|
$this->config = $config; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
public function getEncoder(string $name = 'default') |
30
|
|
|
{ |
31
|
|
|
if (!isset($this->encoders[$name])) { |
32
|
|
|
if ($name === 'default') { |
33
|
|
|
$config = $this->config; |
34
|
|
|
} elseif(isset($this->config['encoders'][$name])) { |
35
|
|
|
$config = $this->config['encoders'][$name]; |
36
|
|
|
} else { |
37
|
|
|
throw new \Exception(sprintf('No configuration found for %s "%s"', Encoder::class, $name)); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
$encoder_options = isset($config['encoder-options']) && is_array($config['encoder-options']) ? |
41
|
|
|
$config['encoder-options'] : |
42
|
|
|
[]; |
43
|
|
|
$options = $this->getEncoderOptions($encoder_options); |
44
|
|
|
|
45
|
|
|
$encoder = Encoder::instance( |
46
|
|
|
$this->config['schemas'], |
47
|
|
|
$options |
48
|
|
|
); |
49
|
|
|
|
50
|
|
|
if (isset($config['jsonapi'])) { |
51
|
|
|
if (is_array($config['jsonapi'])) { |
52
|
|
|
$encoder->withJsonApiVersion($config['jsonapi']); |
53
|
|
|
} elseif ($config['jsonapi'] === true) { |
54
|
|
|
$encoder->withJsonApiVersion(); |
55
|
|
|
} |
56
|
|
|
} |
57
|
|
|
if (isset($config['meta']) && is_array($config['meta'])) { |
58
|
|
|
$encoder->withMeta($config['meta']); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
$this->encoders[$name] = $encoder; |
62
|
|
|
} |
63
|
|
|
return $this->encoders[$name]; |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
protected function getEncoderOptions(array $config) |
67
|
|
|
{ |
68
|
|
|
$options = isset($config['options']) && is_int($config['options']) ? |
69
|
|
|
$config['options'] : |
70
|
|
|
0; |
71
|
|
|
$urlPrefix = isset($config['urlPrefix']) && is_string($config['urlPrefix']) ? |
72
|
|
|
$config['urlPrefix'] : |
73
|
|
|
null; |
74
|
|
|
$depth = isset($config['depth']) && is_int($config['depth']) ? |
75
|
|
|
$config['depth'] : |
76
|
|
|
512; |
77
|
|
|
return new EncoderOptions($options, $urlPrefix, $depth); |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|