Skip to content

Commit

Permalink
Initial commit.
Browse files Browse the repository at this point in the history
  • Loading branch information
lavros committed Dec 5, 2016
0 parents commit bc254f3
Show file tree
Hide file tree
Showing 7 changed files with 391 additions and 0 deletions.
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2016 lichunqiang, YarCode

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
46 changes: 46 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# yii2-swagger

## Installation

The preferred way to install this extension is through [composer](http://getcomposer.org/download/).

Either run

```
php composer.phar require --prefer-dist yarcode/yii2-swagger
```

or add

```json
"yarcode/yii2-swagger": "*"
```

## Usage

TODO: It should be described in detail.

```php
public function init()
{
$this->controllerMap = [
'swagger' => [
'class' => 'YarCode\Yii2\Swagger\SwaggerController',
'host' => 'http://some.host',
'basePath' => '/base/path/to/swagger/doc',,
'templateFile' => '/@api/path/to/swagger/template.yaml',
'includePaths' => [
'/include/path/first',
'/include/path/second',
],
]
];
parent::init();
}
```

## License

![MIT](https://img.shields.io/badge/license-MIT-blue.svg?style=flat-square)

Copyright (c) 2016 lichunqiang, YarCode
17 changes: 17 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"name": "yarcode/yii2-swagger",
"description": "Swagger intergation with Yii2",
"type": "yii2-extension",
"keywords": ["yii2","extension","swagger","Restful","document"],
"license": "MIT",
"require": {
"yiisoft/yii2": "~2.0",
"symfony/yaml": "~3.0",
"bower-asset/swagger-ui": "~2.1"
},
"autoload": {
"psr-4": {
"YarCode\\Yii2\\Swagger\\": "src"
}
}
}
39 changes: 39 additions & 0 deletions src/SwaggerAction.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php

namespace YarCode\Yii2\Swagger;

use yii\base\Action;

/**
* The document display action.
*
* ~~~
* public function actions()
* {
* return [
* 'doc' => [
* 'class' => 'YarCode\Yii2\Swagger\SwaggerAction',
* 'restUrl' => Url::to(['site/api'], true)
* ]
* ];
* }
* ~~~
*/
class SwaggerAction extends Action
{
/**
* @var string The rest url configuration.
*/
public $restUrl;

public function run()
{
$this->controller->layout = false;

$view = $this->controller->getView();

return $view->renderFile(__DIR__ . '/index.php', [
'rest_url' => $this->restUrl,
], $this->controller);
}
}
131 changes: 131 additions & 0 deletions src/SwaggerController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
<?php

namespace YarCode\Yii2\Swagger;

use Yii;
use yii\base\InvalidConfigException;
use yii\web\Controller;
use yii\web\Response;
use yii\helpers\Url;
use Symfony\Component\Yaml\Yaml;

class SwaggerController extends Controller
{
public $defaultAction = 'doc';
public $host;
public $basePath;
public $templateFile;
public $includePaths = [];

public function beforeAction($action)
{
Yii::$app->response->off(Response::EVENT_BEFORE_SEND);
return parent::beforeAction($action);
}

public function init()
{
parent::init();

$this->templateFile = Yii::getAlias($this->templateFile);

if (!is_file($this->templateFile)) {
throw new InvalidConfigException('Invalid swagger template file: ' . $this->templateFile);
}

if (empty($this->includePaths)) {
throw new InvalidConfigException('Include paths must be set');
}
}

public function actions()
{
return [
'doc' => [
'class' => 'YarCode\Yii2\Swagger\SwaggerAction',
'restUrl' => Url::to(['api'], true),
],
];
}

public function actionApi()
{
array_walk($this->includePaths, function (&$item) {
$item = Yii::getAlias($item);
});

$includePaths = array_filter($this->includePaths, function ($item) {
return is_dir($item);
});

$content = [];

foreach ($includePaths as $path) {

$newContent = $this->loadDirectory($path);

foreach ($newContent as $key=>$value) {
if (isset($content[$key])) {
$content[$key] = $content[$key] . "\n" . $newContent[$key];
} else {
$content[$key] = $value;
}
}
}

/** Load config */
$yaml = Yaml::parse(file_get_contents($this->templateFile));
$yaml['host'] = $this->host;
$yaml['basePath'] = $this->basePath;

foreach ($content as $key=>$value) {
$yaml[$key] = Yaml::parse($value);
}

return Yaml::dump($yaml);
}

/**
* @param $path
* @return array
*/
protected function loadDirectory($path)
{
if (!is_dir($path)) {
throw new \InvalidArgumentException("$path is not a directory");
}

$result = [];
$dir = new \DirectoryIterator($path);

foreach ($dir as $info) {
if ($info->isDir() && !$info->isDot()) {
$result[$info->getFilename()] = $this->mergeDirectoryFiles($info->getPathname());
}
}

return $result;
}

/**
* @param $path
* @return string
*/
protected function mergeDirectoryFiles($path)
{
if (!is_dir($path)) {
throw new \InvalidArgumentException("$path is not a directory");
}

$dir = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path));
$content = '';

foreach ($dir as $info) {
if ($info->isFile()) {
$content = implode("\n", [$content, file_get_contents($info->getPathname())]);
}
}

return $content;
}
};
38 changes: 38 additions & 0 deletions src/SwaggerUIAsset.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

namespace YarCode\Yii2\Swagger;

use yii\web\AssetBundle;
use yii\web\View;

class SwaggerUIAsset extends AssetBundle
{
public $sourcePath = '@bower/swagger-ui/dist';

public $js = [
'lib/object-assign-pollyfill.js',
'lib/jquery-1.8.0.min.js',
'lib/jquery.slideto.min.js',
'lib/jquery.wiggle.min.js',
'lib/jquery.ba-bbq.min.js',
'lib/handlebars-4.0.5.js',
'lib/lodash.min.js',
'lib/backbone-min.js',
'swagger-ui.min.js',
'lib/highlight.9.1.0.pack.js',
'lib/highlight.9.1.0.pack_extended.js',
'lib/jsoneditor.min.js',
'lib/marked.js',
'lib/swagger-oauth.js'
];

public $jsOptions = [
'position' => View::POS_HEAD,
];

public $css = [
'css/typography.css',
'css/reset.css',
'css/screen.css',
];
}
99 changes: 99 additions & 0 deletions src/index.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
<?php

use YarCode\Yii2\Swagger\SwaggerUIAsset;

SwaggerUIAsset::register($this);
?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Swagger UI</title>
<?php $this->head() ?>

<script type="text/javascript">
$(function () {
var url = window.location.search.match(/url=([^&]+)/);
if (url && url.length > 1) {
url = decodeURIComponent(url[1]);
} else {
url = "<?= $rest_url ?>";
}
// Pre load translate...
if(window.SwaggerTranslator) {
window.SwaggerTranslator.translate();
}
window.swaggerUi = new SwaggerUi({
url: url,
dom_id: "swagger-ui-container",
supportedSubmitMethods: ['get', 'post', 'put', 'delete', 'patch'],
onComplete: function(swaggerApi, swaggerUi){
if(typeof initOAuth == "function") {
initOAuth({
clientId: "your-client-id",
clientSecret: "your-client-secret-if-required",
realm: "your-realms",
appName: "your-app-name",
scopeSeparator: ","
});
}
if(window.SwaggerTranslator) {
window.SwaggerTranslator.translate();
}
$('pre code').each(function(i, e) {
hljs.highlightBlock(e)
});
addApiKeyAuthorization();
},
onFailure: function(data) {
log("Unable to Load SwaggerUI");
},
docExpansion: "none",
apisSorter: "alpha",
defaultModelRendering: 'schema',
showRequestHeaders: false
});
function addApiKeyAuthorization(){
var key = encodeURIComponent($('#input_apiKey')[0].value);
if(key && key.trim() != "") {
var apiKeyAuth = new SwaggerClient.ApiKeyAuthorization("api_key", key, "query");
window.swaggerUi.api.clientAuthorizations.add("api_key", apiKeyAuth);
log("added key " + key);
}
}
$('#input_apiKey').change(addApiKeyAuthorization);
// if you have an apiKey you would like to pre-populate on the page for demonstration purposes...
/*
var apiKey = "myApiKeyXXXX123456789";
$('#input_apiKey').val(apiKey);
*/
window.swaggerUi.load();
function log() {
if ('console' in window) {
console.log.apply(console, arguments);
}
}
});
</script>
</head>

<body class="swagger-section">
<?php $this->beginBody() ?>
<div id='header'>
<div class="swagger-ui-wrap">
<a id="logo" href="http://swagger.io">swagger</a>
<form id='api_selector'>
<div class='input'><input placeholder="http://example.com/api" id="input_baseUrl" name="baseUrl" type="text"/></div>
<div class='input'><input placeholder="api_key" id="input_apiKey" name="apiKey" type="password"/></div>
<div class='input'><a id="explore" href="#" data-sw-translate>Explore</a></div>
</form>
</div>
</div>

<div id="message-bar" class="swagger-ui-wrap" data-sw-translate>&nbsp;</div>
<div id="swagger-ui-container" class="swagger-ui-wrap"></div>
<?php $this->endBody() ?>
</body>
</html>
<?php $this->endPage() ?>

0 comments on commit bc254f3

Please sign in to comment.