-
Notifications
You must be signed in to change notification settings - Fork 3
/
MapCollectionParser.php
106 lines (92 loc) · 2.79 KB
/
MapCollectionParser.php
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
98
99
100
101
102
103
104
105
106
<?php
/**
* @copyright 2014 Integ S.A.
* @license http://opensource.org/licenses/MIT The MIT License (MIT)
* @author Javier Lorenzana <[email protected]>
*/
namespace GoIntegro\Raml;
// YAML.
use Symfony\Component\Yaml\Yaml;
// JSON.
use GoIntegro\Json\JsonCoder;
class MapCollectionParser
{
use DereferencesIncludes;
const ERROR_ROOT_SCHEMA_VALUE = "The root section \"schemas\" have an unsupported item.",
ERROR_UNEXPECTED_VALUE = "An unexpected value was found when parsing the RAML.";
/**
* @var JsonCoder
* @see DereferencesIncludes::dereferenceInclude
*/
private $jsonCoder;
/**
* @var RamlSnippetParser
*/
private $snippetParser;
/**
* @var string
*/
private $fileDir;
/**
* @param JsonCoder $jsonCoder
*/
public function __construct(JsonCoder $jsonCoder)
{
$this->jsonCoder = $jsonCoder;
}
/**
* @param mixed $rawRaml
* @param RamlDoc $ramlDoc
* @return self
* @throws \ErrorException
*/
public function parse($raw, RamlDoc $ramlDoc)
{
$collection = new Root\MapCollection;
if (is_string($raw)) {
if (RamlDoc::isInclude($raw)) {
$raw = $this->dereferenceInclude($raw, $ramlDoc->fileDir);
} else {
throw new \ErrorException(self::ERROR_ROOT_SCHEMA_VALUE);
}
}
foreach ($raw as $map) {
if (is_array($map)) {
$map = $this->dereferenceIncludes($map, $ramlDoc->fileDir);
} elseif (is_string($map) && RamlDoc::isInclude($map)) {
$map = $this->dereferenceInclude($map, $ramlDoc->fileDir);
} else {
throw new \ErrorException(self::ERROR_ROOT_SCHEMA_VALUE);
}
foreach ($map as $name => &$snippet) {
// @todo Real typing (JSON schemata are \stdClass instances).
if (is_array($snippet)) {
// Resource types and traits (RAML snippets) are arrays.
$snippet = new Root\ResourceType($name, $snippet);
}
}
$collection->add($map);
}
return $collection;
}
/**
* @param array &$map
* @param string $fileDir
* @return array
*/
protected function dereferenceIncludes(array &$map, $fileDir = __DIR__)
{
foreach ($map as &$value) {
if (is_string($value)) {
if (RamlDoc::isInclude($value)) {
$value = $this->dereferenceInclude($value, $fileDir);
} else {
throw new \ErrorException(
self::ERROR_UNEXPECTED_VALUE
);
}
}
}
return $map;
}
}