Permalink
Browse files

Switched to yaml as default output

This matches the openapi v3 documentation

#315
  • Loading branch information...
bfanger committed Aug 11, 2018
1 parent 531d7cb commit be3f04c7514d404d98941a996201f11781995005
View
@@ -3,4 +3,5 @@
/bin/*
!/bin/openapi
/openapi.json
/openapi.yaml
/docs/.vuepress/dist
View
@@ -53,8 +53,8 @@ Generate always-up-to-date documentation.
<?php
require("vendor/autoload.php");
$openapi = \OpenApi\scan('/path/to/project');
header('Content-Type: application/json');
echo $openapi;
header('Content-Type: application/x-yaml');
echo $openapi->toYaml();
```
### Usage from the Command Line Interface
@@ -76,7 +76,7 @@ use OpenApi\Serializer;
$serializer = new Serializer();
$openapi = $serializer->deserialize($jsonString, 'OpenApi\Annotations\OpenApi');
echo $openapi;
echo $openapi->toJson();
```
### Usage from [docker](https://docker.com)
View
@@ -1,10 +1,15 @@
#!/usr/bin/env php
<?php
use OpenApi\Logger;
use OpenApi\Analysis;
use const OpenApi\UNDEFINED;
error_reporting(E_ALL);
// Possible options and their default values.
$options = [
'output' => 'openapi.json',
'output' => 'openapi.yaml',
'format' => 'auto',
'stdout' => false,
'exclude' => [],
'bootstrap' => false,
@@ -20,10 +25,12 @@ $aliases = [
'v' => 'version',
'h' => 'help',
'd' => 'debug',
'p' => 'processor'
'p' => 'processor',
'f' => 'format'
];
$needsArgument = [
'output',
'format',
'exclude',
'bootstrap',
'processor',
@@ -94,6 +101,7 @@ Usage: openapi [--option value] [/path/to/project ...]
Options:
--output (-o) Path to store the generated documentation.
--stdout Write to the standard output.
--format Force yaml or json.
--exclude (-e) Exclude path(s).
ex: --exclude vendor,library/Zend
--bootstrap (-b) Bootstrap a php file for defining constants, etc.
@@ -111,7 +119,7 @@ if (count($paths) === 0) {
$paths[] = getcwd();
echo "Scanning files in '".$paths[0]."' ...\n";
}
if (class_exists('OpenApi\Logger') === false) {
if (class_exists(Logger::class) === false) {
if (file_exists(__DIR__.'/../vendor/autoload.php')) { // cloned / dev environment?
require_once(__DIR__.'/../vendor/autoload.php');
} else {
@@ -154,7 +162,7 @@ set_exception_handler(function ($exception) use ($options) {
exit($exception->getCode() ?: 1);
});
$exit = 0;
\OpenApi\Logger::getInstance()->log = function ($entry, $type) use ($options, &$exit) {
Logger::getInstance()->log = function ($entry, $type) use ($options, &$exit) {
$exit = 1;
$type = $type === E_USER_NOTICE ? 'INFO' : 'WARN';
if ($entry instanceof Exception) {
@@ -200,7 +208,7 @@ foreach ($options["processor"] as $processor) {
} elseif (class_exists($processor)) {
$processor = new $processor();
}
\OpenApi\Analysis::registerProcessor($processor);
Analysis::registerProcessor($processor);
}
$openapi = OpenApi\scan($paths, ['exclude' => $exclude]);
@@ -211,7 +219,7 @@ $counter = 0;
// Output report
foreach ($openapi->paths as $pathItem) {
foreach ($pathItem as $method => $operation) {
if ($operation !== null && in_array($method, $methods)) {
if ($operation !== UNDEFINED && in_array($method, $methods)) {
error_log(str_pad($method, 7, ' ', STR_PAD_LEFT) . ' ' . $pathItem->path);
$counter++;
}
@@ -221,12 +229,16 @@ error_log('----------------------'. str_repeat('-', strlen($counter)));
error_log($counter.' operations documented');
error_log('----------------------'. str_repeat('-', strlen($counter)));
if ($options['stdout']) {
echo $openapi;
if (strtolower($options['format']) === 'json') {
echo $openapi->toJson();
} else {
echo $openapi->toYaml();
}
} else {
if (is_dir($options['output'])) {
$options['output'] .= '/openapi.json';
$options['output'] .= '/openapi.yaml';
}
$openapi->saveAs($options['output']);
$openapi->saveAs($options['output'], $options['format']);
error_log('Written to '.realpath($options['output']));
}
error_log('');
View
@@ -31,7 +31,8 @@
"require": {
"php": ">=7.0",
"doctrine/annotations": "*",
"symfony/finder": ">=2.2"
"symfony/finder": ">=2.2",
"symfony/yaml": ">=2.8"
},
"autoload": {
"psr-4": {
View
@@ -16,8 +16,8 @@ Generate always-up-to-date documentation.
<?php
require("vendor/autoload.php");
$openapi = \OpenApi\scan('/path/to/project');
header('Content-Type: application/json');
echo $openapi;
header('Content-Type: application/x-yaml');
echo $openapi->toYaml();
```
This will scan the php-files in the given folder(s), look for OpenApi annotations and output a json file.
@@ -260,7 +260,7 @@ The `@OA\MediaType` is used to describe the content:
* mediaType="application/json",
* @OA\Schema(ref="#/components/schemas/User"),
* )
* ),
* ),
*/
```
View
@@ -3,14 +3,13 @@ home: true
actionText: Get Started →
actionLink: /Getting-started
features:
- title: OpenAPI specification
details:
Compatible with the OpenAPI Specification version 3.
formerly known as Swagger.
- title: Use @Annotations
details: Write the documentation inside the php source files which helps to keep the documentation in sync.
- title: Useful error messages
details: Enhanced errors messages with hints and context.
- title: OpenAPI specification
details: Compatible with the OpenAPI Specification version 3.
formerly known as Swagger.
- title: Use @Annotations
details: Write the documentation inside the php source files which helps to keep the documentation in sync.
- title: Useful error messages
details: Enhanced errors messages with hints and context.
---
Install with composer:
@@ -25,8 +24,8 @@ Create a php file:
<?php
require("vendor/autoload.php");
$openapi = \OpenApi\scan('/path/to/project');
header('Content-Type: application/json');
echo $openapi;
header('Content-Type: application/x-yaml');
echo $openapi->toYaml();
```
Add annotations to your php files.
View
@@ -401,9 +401,4 @@ public function validate()
return false;
}
public function __toString()
{
return json_encode($this->openapi, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
}
}
@@ -12,6 +12,7 @@
use OpenApi\Analyser;
use OpenApi\Context;
use OpenApi\Logger;
use Symfony\Component\Yaml\Yaml;
/**
* The openapi annotation base class.
@@ -226,9 +227,27 @@ public function mergeProperties($object)
}
}
public function __toString()
/**
* Generate the documentation in YAML format.
*
* @return string
*/
public function toYaml()
{
return json_encode($this, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
return Yaml::dump(json_decode($this->toJson(0)), 10, 2, Yaml::DUMP_OBJECT_AS_MAP);
}
/**
* Generate the documentation in YAML format.
*
* @return string
*/
public function toJson($flags = null)
{
if ($flags === null) {
$flags = JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE;
}
return json_encode($this, $flags);
}
public function __debugInfo()
@@ -371,7 +390,7 @@ public function validate($parents = [], $skip = [], $ref = '')
}
}
}
if (isset($this->ref)) {
if (property_exists($this, 'ref') && $this->ref !== UNDEFINED) {
if (substr($this->ref, 0, 2) === '#/' && count($parents) > 0 && $parents[0] instanceof OpenApi) { // Internal reference
try {
$parents[0]->ref($this->ref);
@@ -140,10 +140,19 @@ public function validate($parents = null, $skip = null, $ref = null)
* @param string $filename
* @throws Exception
*/
public function saveAs($filename)
public function saveAs($filename, $format = 'auto')
{
if (file_put_contents($filename, $this) === false) {
throw new Exception('Failed to saveAs("' . $filename . '")');
if ($format === 'auto') {
$format = strtolower(substr($filename, -5)) === '.json' ? 'json' : 'yaml';
}
if (strtolower($format) === 'json') {
$content = $this->toJson();
} else {
$content = $this->toYaml();
}
if (file_put_contents($filename, $content) === false) {
throw new Exception('Failed to saveAs("' . $filename . '", "'.$format.'")');
}
}
@@ -184,7 +193,7 @@ private static function resolveRef($ref, $resolved, $container, $mapping)
if (is_object($container)) {
if (property_exists($container, $property) === false) {
throw new Exception('$ref "' . $unresolved . '" ');
throw new Exception('$ref "' . $ref . '" not found');
}
if ($slash === false) {
return $container->$property;
@@ -15,7 +15,7 @@ protected function setUp()
public function testStdout()
{
exec(__DIR__.'/../bin/openapi --stdout '.escapeshellarg(__DIR__.'/../Examples/swagger-spec/petstore-simple').' 2> /dev/null', $output, $retval);
exec(__DIR__.'/../bin/openapi --stdout --format json '.escapeshellarg(__DIR__.'/../Examples/swagger-spec/petstore-simple').' 2> /dev/null', $output, $retval);
$this->assertSame(0, $retval);
$json = json_decode(implode("\n", $output));
$this->assertSame(JSON_ERROR_NONE, json_last_error());
@@ -25,7 +25,7 @@ public function testStdout()
public function testOutputTofile()
{
$filename = sys_get_temp_dir().'/swagger-php-clitest.json';
exec(__DIR__.'/../bin/openapi -o '.escapeshellarg($filename).' '.escapeshellarg(__DIR__.'/../Examples/swagger-spec/petstore-simple').' 2> /dev/null', $output, $retval);
exec(__DIR__.'/../bin/openapi --format json -o '.escapeshellarg($filename).' '.escapeshellarg(__DIR__.'/../Examples/swagger-spec/petstore-simple').' 2> /dev/null', $output, $retval);
$this->assertSame(0, $retval);
$this->assertCount(0, $output, 'No output to stdout');
$contents = file_get_contents($filename);
View
@@ -117,13 +117,12 @@ public function testDeserializeAnnotation()
}
JSON;
// $this->markTestSkipped('@todo');
$annotation = $serializer->deserialize($json, 'OpenApi\Annotations\OpenApi');
$this->assertInstanceOf('OpenApi\Annotations\OpenApi', $annotation);
$this->assertJsonStringEqualsJsonString(
$annotation->__toString(),
$this->getExpected()->__toString()
$annotation->toJson(),
$this->getExpected()->toJson()
);
}

0 comments on commit be3f04c

Please sign in to comment.