-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblemSerializer.php
More file actions
97 lines (82 loc) · 2.65 KB
/
Copy pathProblemSerializer.php
File metadata and controls
97 lines (82 loc) · 2.65 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
<?php
namespace TaskChecker\ProblemParser;
use TaskChecker\Problem;
class ProblemSerializer
{
/**
* Serializes problem list to a JSON string
*
* @return string
*/
public function serialize(array $problems)
{
$array = $this->serializeToArray($problems);
return json_encode($array, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
}
private function serializeToArray(array $problems)
{
$json = [];
foreach ($problems as $problem) {
$json[] = $this->serializeProblem($problem);
}
return $json;
}
private function serializeProblem(Problem $problem)
{
return [
'id' => $problem->getId(),
'name' => $problem->getName(),
'description' => $problem->getDescription(),
'relativeUrl' => $problem->getRelativeUrl(),
'codeSample' => $problem->getCodeSample(),
'codeSampleUrl' => $problem->getCodeSampleUrl(),
'hints' => $problem->getHints(),
'examples' => $problem->getExamples()
];
}
/**
* @return Problem[]
*/
public function deserialize($jsonString)
{
$array = json_decode($jsonString, true);
if (null === $array) {
throw new DeserializeException(json_last_error_msg());
}
$problems = [];
foreach ($array as $item) {
$problems[] = $this->deserializeProblem($item);
}
return $problems;
}
private function deserializeProblem(array $item)
{
$id = $this->readOne($item, 'id');
$name = $this->readOne($item, 'name');
$description = $this->readOne($item, 'description');
$problem = new Problem($id, $name, $description);
$problem->relativeUrl = $this->readOne($item, 'relativeUrl');
$problem->codeSample = $this->readOne($item, 'codeSample');
$problem->codeSampleUrl = $this->readOne($item, 'codeSampleUrl');
$problem->hints = $this->readMany($item, 'hints');
$problem->examples = $this->readMany($item, 'examples');
return $problem;
}
private function readOne(array $data, $key)
{
assert(array_key_exists($key, $data));
$value = $data[$key];
assert(is_scalar($value) || is_null($value));
return $value;
}
private function readMany(array $data, $key)
{
assert(array_key_exists($key, $data));
$value = $data[$key];
assert(is_array($value));
foreach ($value as $item) {
assert(is_string($item));
}
return $value;
}
}