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
<?php
/**
* File SwaggerParser.php
*
* @author Edward Pfremmer <epfremme@nerdery.com>
*/
namespace Epfremme\Swagger\Parser;
use Epfremme\Swagger\Exception\InvalidVersionException;
use Symfony\Component\Yaml\Yaml;
/**
* Class SwaggerParser
*
* @package Epfremme\Swagger
* @subpackage Parser
*/
class SwaggerParser
{
// default swagger version
const MINIMUM_VERSION = '2.0';
const VERSION_KEY = 'swagger';
/**
* Swagger Data
* @var array
*/
protected $data;
/**
* Constructor
*/
public function __construct($file)
{
if (!file_exists($file)) {
throw new \InvalidArgumentException(
sprintf("file '%s' doesn't exist", $file)
);
}
$this->data = $this->parse($file);
}
/**
* Parse the swagger file
*
* @param string $file - fully qualified file path
* @return array
*/
protected function parse($file)
{
$data = json_decode(file_get_contents($file), true) ?: Yaml::parse(file_get_contents($file));
return $data;
}
/**
* Return swagger version
*
* @return string
*/
public function getVersion()
{
if (!array_key_exists(self::VERSION_KEY, $this->data)) {
$this->data[self::VERSION_KEY] = self::MINIMUM_VERSION;
}
if (!version_compare($this->data[self::VERSION_KEY], SwaggerParser::MINIMUM_VERSION, '>=')) {
throw new InvalidVersionException($this->data[self::VERSION_KEY]);
}
return $this->data[self::VERSION_KEY];
}
/**
* Return swagger data
*
* @return array
*/
public function getData()
{
return $this->data;
}
/**
* Return data as json
*
* {@inheritdoc
*/
function __toString()
{
return json_encode($this->data);
}
}