/** * Filter resource list by api version */ public function testResourceFilter() { $swagger = new Swagger($this->examplesDir('Petstore')); $swagger->registry['/pet']->apiVersion = 4; // Set "/pet" to a version below 1 $before = $swagger->getResourceList(); $this->assertCount(3, $before['apis'], 'The /pet, /user and /store resources'); // Filter out all unstable versions $swagger->registry = array_filter($swagger->registry, function ($resource) { return version_compare($resource->apiVersion, 4, '=='); }); $after = $swagger->getResourceList(); $this->assertCount(1, $after['apis']); $this->assertEquals('/pet', $after['apis'][0]['path'], 'Resources /user and /store didn\'t match the filter and only /pet remains'); }
public function testBasicUsage() { $swagger = new Swagger($this->examplesDir('Petstore')); $tmpDir = sys_get_temp_dir(); $command = dirname(dirname(__DIR__)) . '/bin/swagger'; // `swagger Examples/Petstore --output /tmp` shell_exec(escapeshellcmd($command) . ' ' . escapeshellarg($this->examplesDir('Petstore')) . ' --output ' . escapeshellarg($tmpDir)); foreach (array('user', 'pet', 'store') as $record) { $json = $swagger->getResource('/' . $record, array('output' => 'json')); $filename = $tmpDir . DIRECTORY_SEPARATOR . $record . '.json'; $this->assertOutputEqualsJson($filename, $json); unlink($filename); } unlink($tmpDir . DIRECTORY_SEPARATOR . 'api-docs.json'); }
public function jsonSerialize() { $data = parent::jsonSerialize(); unset($data['name']); unset($data['required']); if ($this->type !== 'array' && Swagger::isPrimitive($this->type) === false) { $data['$ref'] = $this->type; unset($data['type']); } return $data; }
/** * emulate swagger. save analyzed data to object * * @param string $basePath */ public static function analyze($basePath) { if (isset(self::$analyzedData)) { return; } if (isset($_ENV['swagger-assert-cache']) && $_ENV['swagger-assert-cache'] && file_exists(self::CACHE_FILE)) { self::$analyzedData = json_decode(file_get_contents(self::CACHE_FILE), true); return; } $swagger = new Swagger([$basePath], []); $resourceOptions = ['output' => 'json', 'defaultBasePath' => 'dummy string', 'defaultApiVersion' => null, 'defaultSwaggerVersion' => '1.2']; $analyzedData = []; foreach ($swagger->getResourceNames() as $resourceName) { $annotatedData = json_decode($swagger->getResource($resourceName, $resourceOptions), true); $resourceName = str_replace('/', '-', ltrim($resourceName, '/')); $analyzedData[$resourceName] = $annotatedData; } if (isset($_ENV['swagger-assert-cache']) && $_ENV['swagger-assert-cache']) { file_put_contents(self::CACHE_FILE, json_encode($analyzedData)); } self::$analyzedData = $analyzedData; }
/** * Test the examples against the json files in ExamplesOutput. * * @group examples * @dataProvider getExampleDirs * @param string $exampleDir */ public function testExample($exampleDir) { $swagger = new Swagger($this->examplesDir($exampleDir)); $dir = new \DirectoryIterator($this->outputDir($exampleDir)); $options = array('output' => 'json'); foreach ($dir as $entry) { if ($entry->getExtension() === 'json') { $name = $entry->getBasename('.json'); if (isset($swagger->registry['/' . $name])) { // Resource? $this->assertOutputEqualsJson($entry->getPathname(), $swagger->getResource('/' . $name, $options), 'Resource "/' . $name . '" doesn\'t match expected output in "' . $entry->getPathname() . '"'); } elseif ($name === 'api-docs') { // Listing? $this->assertOutputEqualsJson($entry->getPathname(), $swagger->getResourceList($options), 'Resource listing doesn\'t match expected output in "' . $entry->getPathname() . '"'); } elseif (isset($swagger->models[$name])) { // Model $this->assertOutputEqualsJson($entry->getPathname(), Swagger::jsonEncode($swagger->models[$name]), 'Model "' . $name . '" doesn\'t match expected output in "' . $entry->getPathname() . '"'); } else { $this->fail('Resource or model "' . $name . '" not detected in "' . $this->examplesDir($exampleDir) . '"'); } } } }
/** * Show an specific Resource */ public function showResource($name) { $options = Config::get('laravel-swagger::getResourceOptions'); $resourceName = "/" . str_replace("-", "/", $name); $excludedPath = Config::get('laravel-swagger::excludedPath'); $swagger = new Swagger($this->getPaths(), $excludedPath); if (Config::get('laravel-swagger::cache') && Cache::has('resource_' . $resourceName)) { $resource = Cache::get('resource_' . $resourceName); } else { if (!in_array($resourceName, $swagger->getResourceNames())) { App::abort(404, 'Resource not found'); } // Pet demo uses the main laravel-swagger route. if ($resourceName == '/petdemo') { $options['defaultBasePath'] = route('swagger-index'); } $resource = $swagger->getResource($resourceName, $options); } if (Config::get('laravel-swagger::cache') && !Cache::has('resource_' . $resourceName)) { Cache::put('resource_' . $resourceName, $resource, $this->getExpireAt()); } return $resource; }
/** * * @param Property|Parameter|Operation $annotation * @return bool */ public static function validateContainer($annotation) { // Interpret `items="$ref:Model"` as `@SWG\Items(type="Model")` if (is_string($annotation->items) && preg_match('/\\$ref:[\\s]*(.+)[\\s]*$/', $annotation->items, $matches)) { $annotation->items = new Items(); $annotation->items->type = array_pop($matches); } // Validate if items are inside a container type. if ($annotation->items !== null) { if ($annotation->type !== 'array') { Logger::warning('Unexcepted items for type "' . $annotation->type . '" in ' . $annotation->identity() . ', expecting "array"'); $annotation->items = null; } else { Swagger::checkDataType($annotation->items->type, $annotation->items->_context); } } return true; }
public function fire() { $projectPaths = $this->realpaths($this->paths); $excludePaths = $this->realpaths($this->exclude); $outputPath = head((array) $this->output) . DIRECTORY_SEPARATOR; $swagger = new \Swagger\Swagger($projectPaths, $excludePaths); $resourceList = $swagger->getResourceList(['output' => 'array', 'suffix' => $this->suffix, 'apiVersion' => $this->default_api_version, 'swaggerVersion' => $this->default_swagger_version, 'template' => $this->api_doc_template]); $resourceOptions = ['output' => 'json', 'defaultSwaggerVersion' => $resourceList['swaggerVersion'], 'defaultBasePath' => $this->default_base_path]; if (isset($resourceList['apiVersion'])) { $resourceOptions['defaultApiVersion'] = $resourceList['apiVersion']; } $resourceName = false; $output = []; foreach ($swagger->getResourceNames() as $resourceName) { $json = $swagger->getResource($resourceName, $resourceOptions); $resourceName = str_replace(DIRECTORY_SEPARATOR, '-', ltrim($resourceName, DIRECTORY_SEPARATOR)); $output[$resourceName] = $json; } if (!$output) { throw new SwaggerException('no valid resources found'); } if (file_exists($outputPath) && !is_dir($outputPath)) { throw new SwaggerException(sprintf('[%s] is not a directory', $outputPath)); } elseif (!file_exists($outputPath) && !mkdir($outputPath, 0755, true)) { throw new SwaggerException(sprintf('[%s] is not writeable', $outputPath)); } if (!file_exists($outputPath . '/.gitignore')) { file_put_contents($outputPath . '/.gitignore', "*\n!.gitignore"); } $filename = $outputPath . 'api-docs.json'; if (file_put_contents($filename, \Swagger\Swagger::jsonEncode($resourceList, true))) { $this->logger('Created ' . $filename); } foreach ($output as $name => $json) { $name = str_replace(DIRECTORY_SEPARATOR, '-', ltrim($name, DIRECTORY_SEPARATOR)); $filename = $outputPath . $name . '.json'; $this->logger('Created ' . $filename); file_put_contents($filename, $json); } $this->logger(''); }
/** * * @param string $php * @return Swagger */ protected function examineCode($php) { $swagger = new Swagger(); $swagger->examine("<?php\n" . $php); return $swagger; }
public function validate() { if (count($this->_partials) !== 0) { return true; } if (empty($this->nickname)) { Logger::notice('Required field "nickname" is missing for "' . $this->identity() . '" in ' . $this->_context); } Swagger::checkDataType($this->type, $this->_context); foreach ($this->parameters as $parameter) { if ($parameter->validate() == false) { return false; } } Items::validateContainer($this); Produces::validateContainer($this); Consumes::validateContainer($this); return true; }
<?php /** * Generate Swagger configuration * * @author Anton Shevchuk * @created 22.08.12 17:14 */ namespace Application; use Bluz\Proxy\Router; use Swagger\Swagger; return function ($resource = null) { /** * @var Bootstrap $this */ $this->useJson(); $paths = array(PATH_APPLICATION . '/models', PATH_APPLICATION . '/modules'); $exclude = array(); $swagger = new Swagger($paths, $exclude); if ($resource) { return $swagger->getResource('/' . $resource, ['defaultBasePath' => rtrim(Router::getFullUrl(), '/')]); } else { return $swagger->getResourceList(['basePath' => '/system/api/resource']); } };
<?php require_once 'swagger-php/library/Swagger/Swagger.php'; require_once 'swagger-php/library/Swagger/Logger.php'; require_once 'swagger-php/library/Swagger/Parser.php'; use Swagger\Swagger; $swagger = new Swagger('/Users/jcornado/Documents/devel/rutas-backend/'); header("Content-Type: application/json"); echo $swagger->getResource('/pet', array('output' => 'json'));
<?php require "vendor/autoload.php"; use Swagger\Swagger; $swagger = new Swagger('/mmt_lun/data/SHC/www/html/shc/projects/ssc/dev/api', '/mmt_lun/data/SHC/www/html/shc/projects/ssc/dev/api/vendor'); header('Content-Type: application/json'); var_dump($swagger->getResourceList());
$capsule->setAsGlobal(); $capsule->bootEloquent(); try { if (strpos($capsule->getConnection()->getPdo()->getAttribute(PDO::ATTR_CLIENT_VERSION), 'mysqlnd') === false) { die('PHP PDO is using non-native MySQL extension, php-mysqlnd native extension is required. You most likely have to execute: apt-get install php5-mysqlnd'); } } catch (PDOException $e) { http_response_code(503); die(json_encode(array('code' => 503, 'message' => 'Server is temporarily unavailable due to a MySQL connection problem.'), JSON_PRETTY_PRINT)); } ////////////////////// SERVE API DOCS WITH Swagger /////////////////////////////// // http://zircote.com/swagger-php/using_swagger.html // https://github.com/zircote/swagger-php/blob/master/library/Swagger/Swagger.php use Swagger\Swagger; $DevAAC->get(ROUTES_API_PREFIX . '/docs(/:path)', function ($path = '/') use($DevAAC) { $swagger = new Swagger('../', '../vendor'); $DevAAC->response->headers->set('Access-Control-Allow-Origin', '*'); $DevAAC->response->headers->set('Content-Type', 'application/json'); if ($path != '/') { $DevAAC->response->setBody($swagger->getResource('/' . $path, array('output' => 'json'))); } else { $DevAAC->response->setBody($swagger->getResourceList(array('output' => 'json'))); } }); //////////////////////////// DEFINE API ROUTES ////////////////////////////////// require 'routes/accounts.php'; require 'routes/guilds.php'; require 'routes/houses.php'; require 'routes/market.php'; require 'routes/players.php'; require 'routes/server.php';
/** * Publishes an API Swagger. * If publish is successful, the browser will be redirected to the 'swagger/index?url=$model->name' page. * @param integer $id * @return mixed */ public function actionPublish($id) { $api = $this->findModel($id); $api->published = 1; $api->save(); $apiName = preg_replace('/\\s+/', '', $api->name); $change = new NotifAPIHelper(); $followersNotified = $change->apiChangedPublished($id); $basePathPart = Url::canonical(); $basePathPart = explode('swagger', $basePathPart); $basePathPart = explode('hydra', $basePathPart[0]); $basePathPart = explode('raml', $basePathPart[0]); $basePathPart = explode('wadl', $basePathPart[0]); $basePath = $basePathPart[0] . $apiName . '/'; $objects = Objects::findAll(['api' => $id]); $swaggerJSON = new BuildSwaggerAnnotationsOnly(); $swaggerJSON->BuildJSON(); foreach ($objects as $object) { $object->methods = explode(',', $object->methods); // If this Resource has Methods if ($object->methods !== ['']) { $swaggerJSON->BuildResource($api->version, '1.2', $basePath, $object->name); foreach ($object->methods as $methodName) { // $methodParts[method_name, path] $tempMethodParts = explode(' ', $methodName); foreach ($tempMethodParts as $key => $methodPart) { if ($key === 0) { $methodParts[$key] = $methodPart; $methodParts[1] = ''; } else { $methodParts[1] .= $methodPart; } } $upper_method = strtoupper($methodParts[0]); // $pathParts = [object, ({id}, connection)] $pathParts = explode('/', $methodParts[1]); $numOfPathParts = count($pathParts); $swaggerJSON->BuildAPI($methodParts[1], NULL); $summary = ''; $nickname = ''; $returnType = ''; switch ($upper_method) { case 'GET': switch ($numOfPathParts) { case 1: $summary = 'Retrieve a list of ' . $pathParts[0]; $nickname = 'Get_all_' . $pathParts[0]; $returnType = 'list_' . $pathParts[0]; break; case 2: $summary = 'Retrieve one ' . $pathParts[0]; $nickname = 'Get_one_' . $pathParts[0]; $returnType = $pathParts[0]; break; case 3: $summary = 'Retrieve a list of ' . $pathParts[0] . ' ' . $pathParts[2]; $nickname = 'Get_all_' . $pathParts[2]; $returnType = 'list_' . $pathParts[2]; } break; case 'POST': switch ($numOfPathParts) { case 1: $summary = 'Create a new ' . $pathParts[0] . ' object'; $nickname = 'Post_one_' . $pathParts[0]; $returnType = $pathParts[0]; break; case 3: $summary = 'Create a new ' . $pathParts[2] . 'as a cconection of ' . $pathParts[0]; $nickname = 'Post_one_' . $pathParts[2]; $returnType = $pathParts[2] . '_post'; } break; case 'PUT': switch ($numOfPathParts) { case 2: $summary = 'Change a particular ' . $pathParts[0]; $nickname = 'Put_' . $pathParts[0]; $returnType = $pathParts[0]; } break; case 'DELETE': switch ($numOfPathParts) { case 1: $summary = 'Delete all ' . $pathParts[0]; $nickname = 'Delete_all_' . $pathParts[0]; $returnType = 'list_' . $pathParts[0]; break; case 2: $summary = 'Delete one ' . $pathParts[0]; $nickname = 'Delete_one_' . $pathParts[0]; $returnType = 'boolean'; break; case 3: $summary = 'Delete all ' . $pathParts[2] . ' connections of ' . $pathParts[0]; $nickname = 'Delete_all_' . $pathParts[0]; $returnType = 'boolean'; } break; } $swaggerJSON->BuildOperation($upper_method, $summary, '', $returnType, $nickname); if ($numOfPathParts > 1) { $swaggerJSON->BuildParameter('id', 'Primary key of resource', true, 'integer', 'body'); } if ($upper_method === 'POST' or $upper_method === 'PUT') { $swaggerJSON->BuildParameter($pathParts[0], 'Model of resource', true, $pathParts[0] . '_post_put', 'query'); } $swaggerJSON->CloseOperation(); $swaggerJSON->CloseAPI(); } $swaggerJSON->CloseResource(); // ALL THE DIFFERENT MODEL TYPES THAT NEED TO BE IMPLEMENTED // Meta // $pathParts[0] + Meta // $pathParts[0] . '_post_put' // $pathParts[2] . '_post' // 'list_' . $pathParts[0] // 'list_' . $pathParts[2] // THE MODELS FOR THE CONNECTIONS HAVE TO BE BUILT WHEN THAT PARTICULAR OBJECT COMES IN $swaggerJSON->BuildModel('Meta'); $swaggerJSON->BuildProperty('previous', 'Uri of the previous page relative to the current page settings.', 'string'); $swaggerJSON->BuildProperty('next', 'Uri of the next page relative to the current page settings.', 'string'); $swaggerJSON->BuildProperty('total_count', 'Total items count for all the collection.', 'integer'); $swaggerJSON->BuildProperty('offset', 'Specify the offset to start displaying element on a page.', 'integer'); $swaggerJSON->BuildProperty('limit', 'Specify the number of element to display per page.', 'integer'); $swaggerJSON->CloseModel(); $properties = Properties::findAll(['object' => $object->id]); // $pathParts[0] + Meta $swaggerJSON->BuildModel($object->name); foreach ($properties as $property) { if ($property->type === 'byte') { $swaggerJSON->BuildProperty($property->name, $property->description, 'string', '', 'byte'); } else { if ($property->type === 'date') { $swaggerJSON->BuildProperty($property->name, $property->description, 'string', '', 'date'); } else { if ($property->type === 'dateTime') { $swaggerJSON->BuildProperty($property->name, $property->description, 'string', '', 'date-format'); } else { if ($property->type === 'long') { $swaggerJSON->BuildProperty($property->name, $property->description, 'integer', '', 'int64'); } else { switch ($property->type) { case 'Integer': case 'String': $property->type = strtolower($property->type); } $swaggerJSON->BuildProperty($property->name, $property->description, $property->type); } } } } } $swaggerJSON->BuildProperty('meta', '', 'Meta'); $swaggerJSON->CloseModel(); // $pathParts[0] . '_post_put' $swaggerJSON->BuildModel($object->name . '_post_put'); foreach ($properties as $property) { if ($property->name !== 'id') { if ($property->type === 'byte') { $swaggerJSON->BuildProperty($property->name, $property->description, 'string', '', 'byte'); } else { if ($property->type === 'date') { $swaggerJSON->BuildProperty($property->name, $property->description, 'string', '', 'date'); } else { if ($property->type === 'dateTime') { $swaggerJSON->BuildProperty($property->name, $property->description, 'string', '', 'date-format'); } else { if ($property->type === 'long') { $swaggerJSON->BuildProperty($property->name, $property->description, 'integer', '', 'int64'); } else { switch ($property->type) { case 'Integer': case 'String': $property->type = strtolower($property->type); } $swaggerJSON->BuildProperty($property->name, $property->description, $property->type); } } } } } } $swaggerJSON->CloseModel(); // 'list_' . $pathParts[0] $swaggerJSON->BuildModel('Objects_' . $object->name); $swaggerJSON->BuildProperty($object->name, '', 'array', $object->name); $swaggerJSON->CloseModel(); $swaggerJSON->BuildModel('list_' . $object->name); $swaggerJSON->BuildProperty('meta', '', 'Meta'); $swaggerJSON->BuildProperty('objects', '', 'Objects_' . $object->name); $swaggerJSON->CloseModel(); } } $swaggerJSON->CloseJSON(); $file = new FileManipulation(); $file->setFilename(ucfirst($apiName) . '/' . $apiName . '.php'); $file->makeDirectory(ucfirst($apiName) . '/'); $file->write_file($swaggerJSON->getSwaggerJSON()); // Actually Publish the API $_file = Yii::getAlias('@apisDirectory') . '/' . ucfirst($apiName); $swagger = new Swagger($_file); $basePathPart = explode('/apis/', $basePathPart[0]); $writeFiles = new FileManipulation(); $writeFiles->setFilename(ucfirst($apiName) . '/api-docs.json'); $writeFiles->write_file($swagger->getResourceList(array('output' => 'json', 'basePath' => $basePathPart[0] . '/api-docs/' . ucfirst($apiName)))); foreach ($swagger->registry as $api_name => $api_resource) { $writeFiles->setFilename(ucfirst($apiName) . '/' . $api_name); $writeFiles->write_file($swagger->getResource($api_name, array('output' => 'json'))); } return $apiName; }
public function actionPublish() { //Publish it $_file = Yii::getAlias('@apisDirectory') . '/' . ucfirst($this->_core); $swagger = new Swagger($_file); $actual_link = str_replace('/rebuildschema/publish', '', Url::canonical()); $writeFiles = new FileManipulation(); $writeFiles->setFilename(ucfirst($this->_core) . '/api-docs.json'); $writeFiles->write_file($swagger->getResourceList(array('output' => 'json', 'basePath' => $actual_link . '/api-docs/Core'))); foreach ($swagger->registry as $api_name => $api) { $writeFiles->setFilename(ucfirst($this->_core) . '/' . $api_name); $writeFiles->write_file($swagger->getResource($api_name, array('output' => 'json'))); } return $this->redirect(['index']); }
public function assertOutputEqualsJson($outputFile, $json, $message = '') { if (file_exists($this->outputDir($outputFile))) { $outputFile = $this->outputDir($outputFile); } $expected = json_decode(file_get_contents($outputFile)); $error = json_last_error(); if ($error !== JSON_ERROR_NONE) { $this->fail('File: "' . $outputFile . '" doesn\'t contain valid json, error ' . $error); } if (is_string($json) === false) { $this->fail('Not a (json) string'); } $actual = json_decode($json); $error = json_last_error(); if ($error !== JSON_ERROR_NONE) { $this->fail('invalid json, error ' . $error); } $expectedJson = Swagger::jsonEncode($this->sort($expected, '"' . $outputFile . '" '), true); $actualJson = Swagger::jsonEncode($this->sort($actual, 'generated json '), true); return $this->assertEquals($expectedJson, $actualJson, $message); }
}); Route::get('api-docs', function () { if (Config::get('swagger.generateAlways')) { $appDir = base_path() . "/" . Config::get('swagger.app-dir'); $docDir = Config::get('swagger.doc-dir'); if (!File::exists($docDir) || is_writable($docDir)) { // delete all existing documentation if (File::exists($docDir)) { File::deleteDirectory($docDir); } File::makeDirectory($docDir); $defaultBasePath = Config::get('swagger.default-base-path'); $defaultApiVersion = Config::get('swagger.default-api-version'); $defaultSwaggerVersion = Config::get('swagger.default-swagger-version'); $excludeDirs = Config::get('swagger.excludes'); $swagger = new Swagger($appDir, $excludeDirs); $resourceList = $swagger->getResourceList(array('output' => 'array', 'apiVersion' => $defaultApiVersion, 'swaggerVersion' => $defaultSwaggerVersion)); $resourceOptions = array('output' => 'json', 'defaultSwaggerVersion' => $resourceList['swaggerVersion'], 'defaultBasePath' => $defaultBasePath); $output = array(); foreach ($swagger->getResourceNames() as $resourceName) { $json = $swagger->getResource($resourceName, $resourceOptions); $resourceName = str_replace(DIRECTORY_SEPARATOR, '-', ltrim($resourceName, DIRECTORY_SEPARATOR)); $output[$resourceName] = $json; } $filename = $docDir . '/api-docs.json'; file_put_contents($filename, Swagger::jsonEncode($resourceList, true)); foreach ($output as $name => $json) { $name = str_replace(DIRECTORY_SEPARATOR, '-', ltrim($name, DIRECTORY_SEPARATOR)); $filename = $docDir . '/' . $name . '.json'; file_put_contents($filename, $json); }
public function __construct(array $values = array()) { parent::__construct($values); Swagger::checkDataType($this->type, $this->_context); if (is_string($this->enum)) { $values = $this->decode($this->enum); if (is_object($values)) { $this->enum = array(); foreach ($values as $key => $value) { $this->enum[] = $key . '-' . $value; } } else { $this->enum = $values; } } }