|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Swaggest\JsonSchema\Constraint; |
|
4
|
|
|
|
|
5
|
|
|
use Swaggest\JsonSchema\Context; |
|
6
|
|
|
use Swaggest\JsonSchema\Exception\ContentException; |
|
7
|
|
|
|
|
8
|
|
|
class Content |
|
9
|
|
|
{ |
|
10
|
|
|
const MEDIA_TYPE_APPLICATION_JSON = 'application/json'; |
|
11
|
|
|
const ENCODING_BASE64 = 'base64'; |
|
12
|
|
|
|
|
13
|
|
|
const BASE64_INVALID_REGEX = '_[^A-Za-z0-9+/=]+_'; |
|
14
|
|
|
|
|
15
|
|
|
|
|
16
|
|
|
/** |
|
17
|
|
|
* @param Context $options |
|
18
|
|
|
* @param string|null $encoding |
|
19
|
|
|
* @param string|null $mediaType |
|
20
|
|
|
* @param string $data |
|
21
|
|
|
* @param bool $import |
|
22
|
|
|
* @return bool|mixed|string |
|
23
|
|
|
* @throws ContentException |
|
24
|
|
|
*/ |
|
25
|
|
|
public static function process(Context $options, $encoding, $mediaType, $data, $import = true) |
|
26
|
|
|
{ |
|
27
|
|
|
if ($import) { |
|
28
|
|
|
if ($encoding !== null) { |
|
29
|
|
|
switch ($encoding) { |
|
30
|
|
|
case self::ENCODING_BASE64: |
|
31
|
|
|
if ($options->strictBase64Validation && preg_match(self::BASE64_INVALID_REGEX, $data)) { |
|
32
|
|
|
throw new ContentException('Invalid base64 string'); |
|
33
|
|
|
} |
|
34
|
|
|
$data = base64_decode($data); |
|
35
|
|
|
if ($data === false) { |
|
36
|
|
|
throw new ContentException('Unable to decode base64'); |
|
37
|
|
|
} |
|
38
|
|
|
break; |
|
39
|
|
|
} |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
if ($mediaType !== null) { |
|
43
|
|
|
switch ($mediaType) { |
|
44
|
|
|
case self::MEDIA_TYPE_APPLICATION_JSON: |
|
45
|
|
|
$data = json_decode($data); |
|
46
|
|
|
$lastErrorCode = json_last_error(); |
|
47
|
|
|
if ($lastErrorCode !== JSON_ERROR_NONE) { |
|
48
|
|
|
// TODO add readable error message |
|
49
|
|
|
throw new ContentException('Unable to decode json, err code: ' . $lastErrorCode); |
|
50
|
|
|
} |
|
51
|
|
|
break; |
|
52
|
|
|
|
|
53
|
|
|
} |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
return $data; |
|
57
|
|
|
} else { |
|
58
|
|
|
// export |
|
59
|
|
|
|
|
60
|
|
|
if ($mediaType !== null) { |
|
61
|
|
|
switch ($mediaType) { |
|
62
|
|
|
case self::MEDIA_TYPE_APPLICATION_JSON: |
|
63
|
|
|
$data = json_encode($data); |
|
64
|
|
|
$lastErrorCode = json_last_error(); |
|
65
|
|
|
if ($lastErrorCode !== JSON_ERROR_NONE) { |
|
66
|
|
|
// TODO add readable error message |
|
67
|
|
|
throw new ContentException('Unable to encode json, err code: ' . $lastErrorCode); |
|
68
|
|
|
} |
|
69
|
|
|
break; |
|
70
|
|
|
} |
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
|
|
if ($encoding !== null) { |
|
74
|
|
|
switch ($encoding) { |
|
75
|
|
|
case self::ENCODING_BASE64: |
|
76
|
|
|
$data = base64_encode($data); |
|
77
|
|
|
break; |
|
78
|
|
|
|
|
79
|
|
|
} |
|
80
|
|
|
} |
|
81
|
|
|
|
|
82
|
|
|
return $data; |
|
83
|
|
|
} |
|
84
|
|
|
|
|
85
|
|
|
} |
|
86
|
|
|
} |