1
0
Fork 0
mirror of https://github.com/DanielnetoDotCom/YouPHPTube synced 2025-10-03 09:49:28 +02:00

Better API documentation

This commit is contained in:
Daniel Neto 2025-04-08 12:15:58 -03:00
parent a573e1543c
commit e754679550
220 changed files with 23821 additions and 701 deletions

1
.gitignore vendored
View file

@ -119,3 +119,4 @@ plugin/YPTSocket/AVideo-Socket/
.phpunit.result.cache
phpunit.xml
plugin/API/AVideo-NodeAPIBoost/

View file

@ -80,7 +80,6 @@ Options All -Indexes
</FilesMatch>
</IfModule>
# END Caching
<IfModule mod_rewrite.c>
RewriteCond %{HTTPS} =on
@ -91,6 +90,9 @@ Options All -Indexes
RewriteEngine on
#VideoHLS for DRM
RewriteRule ^api/([^/]+)/([^/]+)$ plugin/API/router.php?APIPlugin=$1&APIName=$2 [QSA,L]
RewriteRule ^api/([^/]+)$ plugin/API/router.php?APIName=$1 [QSA,L]
RewriteRule ^buy/? plugin/YPTWallet/buy.php [NC,L,QSA]
RewriteRule ^id/? view/id.php [NC,L,QSA]
RewriteRule ^logo.png view/logo.png.php [NC,L,QSA]

View file

@ -53,7 +53,8 @@
"react/event-loop": "^1.5",
"elephantio/elephant.io": "^4.13",
"iamcal/sql-parser": "^0.6",
"ratchet/pawl": "^0.4.3"
"ratchet/pawl": "^0.4.3",
"zircote/swagger-php": "^5.0"
},
"require-dev": {
"phpunit/phpunit": "^9.6",

342
composer.lock generated
View file

@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "84e9f6a11f1bf0940cf44e61d9477687",
"content-hash": "b796d698ec634bf301a3ec925a25578d",
"packages": [
{
"name": "abraham/twitteroauth",
@ -2396,6 +2396,64 @@
],
"time": "2025-01-08T20:10:23+00:00"
},
{
"name": "nikic/php-parser",
"version": "v5.4.0",
"source": {
"type": "git",
"url": "https://github.com/nikic/PHP-Parser.git",
"reference": "447a020a1f875a434d62f2a401f53b82a396e494"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/nikic/PHP-Parser/zipball/447a020a1f875a434d62f2a401f53b82a396e494",
"reference": "447a020a1f875a434d62f2a401f53b82a396e494",
"shasum": ""
},
"require": {
"ext-ctype": "*",
"ext-json": "*",
"ext-tokenizer": "*",
"php": ">=7.4"
},
"require-dev": {
"ircmaxell/php-yacc": "^0.0.7",
"phpunit/phpunit": "^9.0"
},
"bin": [
"bin/php-parse"
],
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "5.0-dev"
}
},
"autoload": {
"psr-4": {
"PhpParser\\": "lib/PhpParser"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-3-Clause"
],
"authors": [
{
"name": "Nikita Popov"
}
],
"description": "A PHP parser written in PHP",
"keywords": [
"parser",
"php"
],
"support": {
"issues": "https://github.com/nikic/PHP-Parser/issues",
"source": "https://github.com/nikic/PHP-Parser/tree/v5.4.0"
},
"time": "2024-12-30T11:07:19+00:00"
},
{
"name": "norkunas/onesignal-php-api",
"version": "v2.15.0",
@ -4838,6 +4896,69 @@
],
"time": "2024-09-25T14:11:13+00:00"
},
{
"name": "symfony/finder",
"version": "v5.4.45",
"source": {
"type": "git",
"url": "https://github.com/symfony/finder.git",
"reference": "63741784cd7b9967975eec610b256eed3ede022b"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/finder/zipball/63741784cd7b9967975eec610b256eed3ede022b",
"reference": "63741784cd7b9967975eec610b256eed3ede022b",
"shasum": ""
},
"require": {
"php": ">=7.2.5",
"symfony/deprecation-contracts": "^2.1|^3",
"symfony/polyfill-php80": "^1.16"
},
"type": "library",
"autoload": {
"psr-4": {
"Symfony\\Component\\Finder\\": ""
},
"exclude-from-classmap": [
"/Tests/"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Fabien Potencier",
"email": "fabien@symfony.com"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
"description": "Finds files and directories via an intuitive fluent interface",
"homepage": "https://symfony.com",
"support": {
"source": "https://github.com/symfony/finder/tree/v5.4.45"
},
"funding": [
{
"url": "https://symfony.com/sponsor",
"type": "custom"
},
{
"url": "https://github.com/fabpot",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
"time": "2024-09-28T13:32:08+00:00"
},
{
"name": "symfony/http-client",
"version": "v5.4.49",
@ -6214,6 +6335,81 @@
],
"time": "2024-09-25T14:11:13+00:00"
},
{
"name": "symfony/yaml",
"version": "v5.4.45",
"source": {
"type": "git",
"url": "https://github.com/symfony/yaml.git",
"reference": "a454d47278cc16a5db371fe73ae66a78a633371e"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/yaml/zipball/a454d47278cc16a5db371fe73ae66a78a633371e",
"reference": "a454d47278cc16a5db371fe73ae66a78a633371e",
"shasum": ""
},
"require": {
"php": ">=7.2.5",
"symfony/deprecation-contracts": "^2.1|^3",
"symfony/polyfill-ctype": "^1.8"
},
"conflict": {
"symfony/console": "<5.3"
},
"require-dev": {
"symfony/console": "^5.3|^6.0"
},
"suggest": {
"symfony/console": "For validating YAML files using the lint command"
},
"bin": [
"Resources/bin/yaml-lint"
],
"type": "library",
"autoload": {
"psr-4": {
"Symfony\\Component\\Yaml\\": ""
},
"exclude-from-classmap": [
"/Tests/"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Fabien Potencier",
"email": "fabien@symfony.com"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
"description": "Loads and dumps YAML files",
"homepage": "https://symfony.com",
"support": {
"source": "https://github.com/symfony/yaml/tree/v5.4.45"
},
"funding": [
{
"url": "https://symfony.com/sponsor",
"type": "custom"
},
{
"url": "https://github.com/fabpot",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
"time": "2024-09-25T14:11:13+00:00"
},
{
"name": "thecodingmachine/safe",
"version": "v2.5.0",
@ -6405,6 +6601,92 @@
"source": "https://github.com/vimeo/vimeo.php/tree/3.0.10"
},
"time": "2022-02-18T14:05:55+00:00"
},
{
"name": "zircote/swagger-php",
"version": "5.0.7",
"source": {
"type": "git",
"url": "https://github.com/zircote/swagger-php.git",
"reference": "18457fa71f753cfd4a2b21916baf329864fdfaa6"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/zircote/swagger-php/zipball/18457fa71f753cfd4a2b21916baf329864fdfaa6",
"reference": "18457fa71f753cfd4a2b21916baf329864fdfaa6",
"shasum": ""
},
"require": {
"ext-json": "*",
"nikic/php-parser": "^4.19 || ^5.0",
"php": ">=7.4",
"psr/log": "^1.1 || ^2.0 || ^3.0",
"symfony/deprecation-contracts": "^2 || ^3",
"symfony/finder": "^5.0 || ^6.0 || ^7.0",
"symfony/yaml": "^5.0 || ^6.0 || ^7.0"
},
"conflict": {
"symfony/process": ">=6, <6.4.14"
},
"require-dev": {
"composer/package-versions-deprecated": "^1.11",
"doctrine/annotations": "^2.0",
"friendsofphp/php-cs-fixer": "^3.62.0",
"phpstan/phpstan": "^1.6 || ^2.0",
"phpunit/phpunit": "^9.0",
"rector/rector": "^1.0 || ^2.0",
"vimeo/psalm": "^4.30 || ^5.0"
},
"suggest": {
"doctrine/annotations": "^2.0"
},
"bin": [
"bin/openapi"
],
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "5.x-dev"
}
},
"autoload": {
"psr-4": {
"OpenApi\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"Apache-2.0"
],
"authors": [
{
"name": "Robert Allen",
"email": "zircote@gmail.com"
},
{
"name": "Bob Fanger",
"email": "bfanger@gmail.com",
"homepage": "https://bfanger.nl"
},
{
"name": "Martin Rademacher",
"email": "mano@radebatz.net",
"homepage": "https://radebatz.net"
}
],
"description": "swagger-php - Generate interactive documentation for your RESTful API using phpdoc annotations",
"homepage": "https://github.com/zircote/swagger-php/",
"keywords": [
"api",
"json",
"rest",
"service discovery"
],
"support": {
"issues": "https://github.com/zircote/swagger-php/issues",
"source": "https://github.com/zircote/swagger-php/tree/5.0.7"
},
"time": "2025-03-19T03:31:11+00:00"
}
],
"packages-dev": [
@ -6672,64 +6954,6 @@
],
"time": "2025-02-12T12:17:51+00:00"
},
{
"name": "nikic/php-parser",
"version": "v5.4.0",
"source": {
"type": "git",
"url": "https://github.com/nikic/PHP-Parser.git",
"reference": "447a020a1f875a434d62f2a401f53b82a396e494"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/nikic/PHP-Parser/zipball/447a020a1f875a434d62f2a401f53b82a396e494",
"reference": "447a020a1f875a434d62f2a401f53b82a396e494",
"shasum": ""
},
"require": {
"ext-ctype": "*",
"ext-json": "*",
"ext-tokenizer": "*",
"php": ">=7.4"
},
"require-dev": {
"ircmaxell/php-yacc": "^0.0.7",
"phpunit/phpunit": "^9.0"
},
"bin": [
"bin/php-parse"
],
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "5.0-dev"
}
},
"autoload": {
"psr-4": {
"PhpParser\\": "lib/PhpParser"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-3-Clause"
],
"authors": [
{
"name": "Nikita Popov"
}
],
"description": "A PHP parser written in PHP",
"keywords": [
"parser",
"php"
],
"support": {
"issues": "https://github.com/nikic/PHP-Parser/issues",
"source": "https://github.com/nikic/PHP-Parser/tree/v5.4.0"
},
"time": "2024-12-30T11:07:19+00:00"
},
{
"name": "phar-io/manifest",
"version": "2.0.4",

View file

@ -2579,8 +2579,8 @@ function allowOrigin()
header('Access-Control-Allow-Private-Network: true');
header('Access-Control-Request-Private-Network: true');
//header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: GET,HEAD,OPTIONS,POST,PUT");
header("Access-Control-Allow-Headers: Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
header("Access-Control-Allow-Methods: GET,HEAD,OPTIONS,POST,PUT,DELETE");
header("Access-Control-Allow-Headers: Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers,ua-resolution,Authorization");
}
function cleanUpAccessControlHeader()

View file

@ -3,6 +3,9 @@
function getDockerVarsFileName()
{
global $global;
if(empty($global['docker_vars'])){
return false;
}
return $global['docker_vars'];
}
@ -33,4 +36,4 @@ function getDockerInternalURL()
function getDockerStatsURL()
{
return getDockerInternalURL() . "stat";
}
}

View file

@ -92,8 +92,8 @@ function _ob_get_clean()
function _setcookie($cookieName, $value, $expires = 0)
{
if($cookieName === 'pass'){
_error_log('_setcookie pass changed '.$value);
if ($cookieName === 'pass') {
_error_log('_setcookie pass changed ' . $value);
}
global $config, $global;
if (empty($expires)) {
@ -124,7 +124,7 @@ function _setcookie($cookieName, $value, $expires = 0)
setcookie($cookieName, $value, (int) $expires, "/", $domain);
setcookie($cookieName, $value, (int) $expires, "/", 'www.' . $domain);
}
$_COOKIE[$cookieName]=$value;
$_COOKIE[$cookieName] = $value;
}
function _unsetcookie($cookieName)
@ -246,20 +246,22 @@ function _json_decode($object, $associative = false)
}
}
function _session_write_close(){
function _session_write_close()
{
if (isSessionStarted()) {
//_error_log(json_encode(debug_backtrace()));
@session_write_close();
}
}
function isSessionStarted() {
global $customSessionHandle;
function isSessionStarted()
{
global $customSessionHandle;
if(session_status() == PHP_SESSION_NONE){
if (session_status() == PHP_SESSION_NONE) {
return false;
}
if(session_status() == PHP_SESSION_ACTIVE){
if (session_status() == PHP_SESSION_ACTIVE) {
return true;
}
// Check if a session variable exists in Memcached
@ -270,22 +272,23 @@ function isSessionStarted() {
}
}
function session_start_preload(){
function session_start_preload()
{
global $_session_start_preload, $global;
if(empty($global['systemRootPath'])){
if (empty($global['systemRootPath'])) {
return false;
}
if(!class_exists('AVideoConf')){
if (!class_exists('AVideoConf')) {
require $global['systemRootPath'] . 'objects/configuration.php';
}
if(!isset($_session_start_preload)){
if (!isset($_session_start_preload)) {
$_session_start_preload = 1;
}else{
} else {
return false;
}
$config = new AVideoConf();
// server should keep session data for AT LEAST 1 hour
ini_set('session.gc_maxlifetime', $config->getSession_timeout());
@ -311,40 +314,40 @@ function _session_start(array $options = [])
{
try {
session_start_preload();
// Start session first, then check the session ID
if (isset($_GET['PHPSESSID']) && !_empty($_GET['PHPSESSID'])) {
$PHPSESSID = $_GET['PHPSESSID'];
unset($_GET['PHPSESSID']);
// Start the session with the options
$session = @session_start($options);
// Now, check if session ID matches after session start
if ($PHPSESSID === session_id()) {
// Session ID already matches, do nothing
return $session;
}
if (!User::isLogged()) {
if ($PHPSESSID !== session_id()) {
_session_write_close();
session_id($PHPSESSID);
//_error_log("captcha: session_id changed to {$PHPSESSID}");
}
// Restart session after changing the session ID
$session = @session_start($options);
if (preg_match('/objects\/getCaptcha\.php/i', $_SERVER['SCRIPT_NAME'])) {
$regenerateSessionId = false;
}
if (!blackListRegenerateSession()) {
_error_log("captcha: session_id regenerated new session_id=" . session_id());
_session_regenerate_id();
}
return $session;
} else {
//_error_log("captcha: user logged we will not change the session ID PHPSESSID={$PHPSESSID} session_id=" . session_id());
@ -419,3 +422,57 @@ function doesPHPVersioHasOBBug()
{
return (version_compare(phpversion(), '8.1.4', '==') || version_compare(phpversion(), '8.0.17', '=='));
}
function getSystemAPIs()
{
global $global;
$obj = AVideoPlugin::getObjectData("API");
$methodsList = array();
$reflector = new ReflectionClass('API');
$class_methods = get_class_methods('API');
foreach ($class_methods as $key => $met) {
if (preg_match("/(get|set)_api_(.*)/", $met, $matches)) {
$methodsList[] = array($met, $reflector, $matches[1], $matches[2], 'API');
}
}
$plugins = Plugin::getAllEnabled();
foreach ($plugins as $value) {
$p = AVideoPlugin::loadPlugin($value['dirName']);
if (class_exists($value['dirName'])) {
$class_methods = get_class_methods($value['dirName']);
$reflector = new ReflectionClass($value['dirName']);
foreach ($class_methods as $key => $met) {
if (preg_match("/API_(get|set)_(.*)/", $met, $matches)) {
$methodsList[] = array($met, $reflector, $matches[1], $matches[2], $value['dirName']);
}
}
}
}
$response = array();
$plugins = array();
foreach ($methodsList as $method) {
if (!preg_match("/(get|set)_api_(.*)/", $method[0], $matches)) {
if (!preg_match("/API_(get|set)_(.*)/", $method[0], $matches)) {
continue;
}
}
$reflector = $method[1];
$comment = $reflector->getMethod($method[0])->getDocComment();
$comment = str_replace(['{webSiteRootURL}', '{getOrSet}', '{APIPlugin}', '{APIName}', '{APISecret}'], [$global['webSiteRootURL'], $method[2], $method[4], $method[3], $obj->APISecret], $comment);
$resp = array(
'comment' => $comment,
'method' => $method[0],
'type' => $method[2],
'action' => $method[3],
'plugin' => $method[4],
);
$plugins[$method[4]][$method[0]] = $resp ;
$response[] = $resp ;
}
return array('methodsList' => $methodsList, 'response' => $response, 'plugins' => $plugins);
}

View file

@ -535,3 +535,49 @@ function escapeshellcmdURL(string $command)
function recreateCache(){
return (!empty($_REQUEST['recreate']) && !isBot());
}
function getBearerToken()
{
$headers = [];
// 1. Try apache_request_headers() if available
if (function_exists('apache_request_headers')) {
$headers = apache_request_headers();
}
// 2. If still empty, try getallheaders()
if (empty($headers) && function_exists('getallheaders')) {
$headers = getallheaders();
}
// 3. If still empty, manually build headers from $_SERVER
if (empty($headers)) {
foreach ($_SERVER as $key => $value) {
if (stripos($key, 'HTTP_') === 0) {
// Convert HTTP_HEADER_NAME to Header-Name
$headerName = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($key, 5)))));
$headers[$headerName] = $value;
}
}
}
// 4. Normalize and extract Authorization header
foreach ($headers as $name => $value) {
if (strcasecmp($name, 'Authorization') === 0 && preg_match('/Bearer\s(\S+)/', $value, $matches)) {
return $matches[1]; // Return the token
}
}
// 5. Final fallback: check $_SERVER directly
if (isset($_SERVER['HTTP_AUTHORIZATION']) && preg_match('/Bearer\s(\S+)/', $_SERVER['HTTP_AUTHORIZATION'], $matches)) {
return $matches[1];
}
if (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION']) && preg_match('/Bearer\s(\S+)/', $_SERVER['REDIRECT_HTTP_AUTHORIZATION'], $matches)) {
return $matches[1];
}
return null; // Token not found
}

View file

@ -1,11 +1,11 @@
<?php
global $global, $config;
if (!isset($global['systemRootPath'])) {
require_once '../videos/configuration.php';
require_once __DIR__.'/../videos/configuration.php';
}
require_once $global['systemRootPath'] . 'objects/Object.php';
require_once $global['systemRootPath'] . 'objects/mysql_dal.php';
require_once $global['systemRootPath'] . 'objects/user.php';
require_once __DIR__.'/Object.php';
require_once __DIR__.'/mysql_dal.php';
require_once __DIR__.'/user.php';
class Plugin extends ObjectYPT
{

4777
plugin/API/API copy.php Normal file

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

26
plugin/API/docs/README.md Normal file
View file

@ -0,0 +1,26 @@
# Swagger UI
Welcome to the Swagger UI documentation!
## Usage
- [Installation](usage/installation.md)
- [Configuration](usage/configuration.md)
- [CORS](usage/cors.md)
- [OAuth2](usage/oauth2.md)
- [Deep Linking](usage/deep-linking.md)
- [Limitations](usage/limitations.md)
- [Version detection](usage/version-detection.md)
## Customization
- [Overview](customization/overview.md)
- [Plugin API](customization/plugin-api.md)
- [Custom layout](customization/custom-layout.md)
- [Adding plugin](customization/add-plugin.md)
- [Plug-Points](customization/plug-points.md)
## Development
- [Setting up](development/setting-up.md)
- [Scripts](development/scripts.md)

View file

@ -0,0 +1,3 @@
{
"title": "Swagger UI"
}

View file

@ -0,0 +1,127 @@
# Add a plugin
### Swagger-UI relies on plugins for all the good stuff.
Plugins allow you to add
- `statePlugins`
- `selectors` - query the state
- `reducers` - modify the state
- `actions` - fire and forget, that will eventually be handled by a reducer. You *can* rely on the result of async actions. But in general it's not recommended
- `wrapActions` - replace an action with a wrapped action (useful for hooking into existing `actions`)
- `components` - React components
- `fn` - commons functions
To add a plugin we include it in the configs...
```js
SwaggerUI({
url: 'some url',
plugins: [ ... ]
})
```
Or if you're updating the core plugins.. you'll add it to the base preset: [src/core/presets/base/index.js](https://github.com/swagger-api/swagger-ui/blob/master/src/core/presets/base/index.js)
Each Plugin is a function that returns an object. That object will get merged with the `system` and later bound to the state.
Here is an example of each `type`
```js
// A contrived, but quite full example....
export function SomePlugin(toolbox) {
const UPDATE_SOMETHING = "some_namespace_update_something" // strings just need to be uniuqe... see below
// Tools
const fromJS = toolbox.Im.fromJS // needed below
const createSelector = toolbox.createSelector // same, needed below
return {
statePlugins: {
someNamespace: {
actions: {
actionName: (args)=> ({type: UPDATE_SOMETHING, payload: args}), // Synchronous action must return an object for the reducer to handle
anotherAction: (a,b,c) => (system) => system.someNamespaceActions.actionName(a || b) // Asynchronous actions must return a function. The function gets the whole system, and can call other actions (based on state if needed)
},
wrapActions: {
anotherAction: (oriAction, system) => (...args) => {
oriAction(...args) // Usually we at least call the original action
system.someNamespace.actionName(...args) // why not call this?
console.log("args", args) // Log the args
// anotherAction in the someNamespace has now been replaced with the this function
}
},
reducers: {
[UPDATE_SOMETHING]: (state, action) => { // Take a state (which is immutable) and an action (see synchronous actions) and return a new state
return state.set("something", fromJS(action.payload)) // we're updating the Immutable state object... we need to convert vanilla objects into an immutable type (fromJS)
// See immutable about how to modify the state
// PS: you're only working with the state under the namespace, in this case "someNamespace". So you can do what you want, without worrying about /other/ namespaces
}
},
selectors: {
// creatSelector takes a list of fn's and passes all the results to the last fn.
// eg: createSelector(a => a, a => a+1, (a,a2) => a + a2)(1) // = 3
something: createSelector( // see [reselect#createSelector](https://github.com/reactjs/reselect#createselectorinputselectors--inputselectors-resultfunc)
getState => getState(), // This is a requirement... because we `bind` selectors, we don't want to bind to any particular state (which is an immutable value) so we bind to a function, which returns the current state
state => state.get("something") // return the whatever "something" points to
),
foo: getState => "bar" // In the end selectors are just functions that we pass getState to
}
}
... // you can include as many namespaces as you want. They just get merged into the 'system'
},
components: {
foo: ()=> <h1> Hello </h1> // just a map of names to react components, naturally you'd want to import a fuller react component
},
fn: {
addOne: (a) => a + 1 // just any extra functions you want to include
}
}
}
```
>The plugin factory gets one argument, which I like to call `toolbox`.
This argument is the entire plugin system (at the point the plugin factory is called). It also includes a reference to the `Immutable` lib, so that plugin authors don't need to include it.
### The Plugin system
Each plugin you include will end up getting merged into the `system`, which is just an object.
Then we bind the `system` to our state. And flatten it, so that we don't need to reach into deep objects
> ie: spec.actions becomes specActions, spec.selectors becomes specSelectors
You can reach this bound system by calling `getSystem` on the store.
`getSystem` is the heart of this whole project. Each container component will receive a spread of props from `getSystem`
here is an example....
```js
class Bobby extends React.Component {
handleClick(e) {
this.props.someNamespaceActions.actionName() // fires an action... which the reducer will *eventually* see
}
render() {
let { someNamespaceSelectors, someNamespaceActions } = this.props // this.props has the whole state spread
let something = someNamespaceSelectors.something() // calls our selector, which returns some state (either an immutable object or value)
return (
<h1 onClick={this.handleClick.bind(this)}> Hello {something} </h1> // render the contents
)
}
}
```
TODO: a lot more elaboration
`

View file

@ -0,0 +1,92 @@
# Creating a custom layout
**Layouts** are a special type of component that Swagger UI uses as the root component for the entire application. You can define custom layouts in order to have high-level control over what ends up on the page.
By default, Swagger UI uses `BaseLayout`, which is built into the application. You can specify a different layout to be used by passing the layout's name as the `layout` parameter to Swagger UI. Be sure to provide your custom layout as a component to Swagger UI.
<br>
For example, if you wanted to create a custom layout that only displayed operations, you could define an `OperationsLayout`:
```js
import React from "react"
// Create the layout component
class OperationsLayout extends React.Component {
render() {
const {
getComponent
} = this.props
const Operations = getComponent("operations", true)
return (
<div className="swagger-ui">
<Operations />
</div>
)
}
}
// Create the plugin that provides our layout component
const OperationsLayoutPlugin = () => {
return {
components: {
OperationsLayout: OperationsLayout
}
}
}
// Provide the plugin to Swagger-UI, and select OperationsLayout
// as the layout for Swagger-UI
SwaggerUI({
url: "https://petstore.swagger.io/v2/swagger.json",
plugins: [ OperationsLayoutPlugin ],
layout: "OperationsLayout"
})
```
### Augmenting the default layout
If you'd like to build around the `BaseLayout` instead of replacing it, you can pull the `BaseLayout` into your custom layout and use it:
```js
import React from "react"
// Create the layout component
class AugmentingLayout extends React.Component {
render() {
const {
getComponent
} = this.props
const BaseLayout = getComponent("BaseLayout", true)
return (
<div>
<div className="myCustomHeader">
<h1>I have a custom header above Swagger-UI!</h1>
</div>
<BaseLayout />
</div>
)
}
}
// Create the plugin that provides our layout component
const AugmentingLayoutPlugin = () => {
return {
components: {
AugmentingLayout: AugmentingLayout
}
}
}
// Provide the plugin to Swagger-UI, and select AugmentingLayout
// as the layout for Swagger-UI
SwaggerUI({
url: "https://petstore.swagger.io/v2/swagger.json",
plugins: [ AugmentingLayoutPlugin ],
layout: "AugmentingLayout"
})
```

View file

@ -0,0 +1,71 @@
# Plugin system overview
### Prior art
Swagger UI leans heavily on concepts and patterns found in React and Redux.
If you aren't already familiar, here's some suggested reading:
- [React: Quick Start (reactjs.org)](https://reactjs.org/docs/hello-world.html)
- [Redux README (redux.js.org)](https://redux.js.org/)
In the following documentation, we won't take the time to define the fundamentals covered in the resources above.
> **Note**: Some of the examples in this section contain JSX, which is a syntax extension to JavaScript that is useful for writing React components.
>
> If you don't want to set up a build pipeline capable of translating JSX to JavaScript, take a look at [React without JSX (reactjs.org)](https://reactjs.org/docs/react-without-jsx.html). You can use our `system.React` reference to leverage React without needing to pull a copy into your project.
### The System
The _system_ is the heart of the Swagger UI application. At runtime, it's a JavaScript object that holds many things:
- React components
- Bound Redux actions and reducers
- Bound Reselect state selectors
- System-wide collection of available components
- Built-in helpers like `getComponent`, `makeMappedContainer`, and `getStore`
- References to the React and Immutable.js libraries (`system.React`, `system.Im`)
- User-defined helper functions
The system is built up when Swagger UI is called by iterating through ("compiling") each plugin that Swagger UI has been given, through the `presets` and `plugins` configuration options.
### Presets
Presets are arrays of plugins, which are provided to Swagger UI through the `presets` configuration option. All plugins within presets are compiled before any plugins provided via the `plugins` configuration option. Consider the following example:
```javascript
const MyPreset = [FirstPlugin, SecondPlugin, ThirdPlugin]
SwaggerUI({
presets: [
MyPreset
]
})
```
By default, Swagger UI includes the internal `ApisPreset`, which contains a set of plugins that provide baseline functionality for Swagger UI. If you specify your own `presets` option, you need to add the ApisPreset manually, like so:
```javascript
SwaggerUI({
presets: [
SwaggerUI.presets.apis,
MyAmazingCustomPreset
]
})
```
The need to provide the `apis` preset when adding other presets is an artifact of Swagger UI's original design, and will likely be removed in the next major version.
### getComponent
`getComponent` is a helper function injected into every container component, which is used to get references to components provided by the plugin system.
All components should be loaded through `getComponent`, since it allows other plugins to modify the component. It is preferred over a conventional `import` statement.
Container components in Swagger UI can be loaded by passing `true` as the second argument to `getComponent`, like so:
```javascript
getComponent("ContainerComponentName", true)
```
This will map the current system as props to the component.

View file

@ -0,0 +1,415 @@
# Plug points
Swagger UI exposes most of its internal logic through the plugin system.
Often, it is beneficial to override the core internals to achieve custom behavior.
### Note: Semantic Versioning
Swagger UI's internal APIs are _not_ part of our public contract, which means that they can change without the major version change.
If your custom plugins wrap, extend, override, or consume any internal core APIs, we recommend specifying a specific minor version of Swagger UI to use in your application, because they will _not_ change between patch versions.
If you're installing Swagger UI via NPM, for example, you can do this by using a tilde:
```js
{
"dependencies": {
"swagger-ui": "~3.11.0"
}
}
```
### `fn.opsFilter`
When using the `filter` option, tag names will be filtered by the user-provided value. If you'd like to customize this behavior, you can override the default `opsFilter` function.
For example, you can implement a multiple-phrase filter:
```js
const MultiplePhraseFilterPlugin = function() {
return {
fn: {
opsFilter: (taggedOps, phrase) => {
const phrases = phrase.split(", ")
return taggedOps.filter((val, key) => {
return phrases.some(item => key.indexOf(item) > -1)
})
}
}
}
}
```
### Logo component
While using the Standalone Preset the SwaggerUI logo is rendered in the Top Bar.
The logo can be exchanged by replacing the `Logo` component via the plugin api:
```jsx
import React from "react";
const MyLogoPlugin = {
components: {
Logo: () => (
<img alt="My Logo" height="40" src="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNTM3IiBoZWlnaHQ9IjEzNCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KCiA8Zz4KICA8dGl0bGU+TGF5ZXIgMTwvdGl0bGU+CiAgPHRleHQgdHJhbnNmb3JtPSJtYXRyaXgoMy40Nzc2OSAwIDAgMy4yNjA2NyAtNjczLjEyOCAtNjkxLjk5MykiIHN0cm9rZT0iIzAwMCIgZm9udC1zdHlsZT0ibm9ybWFsIiBmb250LXdlaWdodD0ibm9ybWFsIiB4bWw6c3BhY2U9InByZXNlcnZlIiB0ZXh0LWFuY2hvcj0ic3RhcnQiIGZvbnQtZmFtaWx5PSInT3BlbiBTYW5zIEV4dHJhQm9sZCciIGZvbnQtc2l6ZT0iMjQiIGlkPSJzdmdfMSIgeT0iMjQxLjIyMTkyIiB4PSIxOTYuOTY5MjEiIHN0cm9rZS13aWR0aD0iMCIgZmlsbD0iIzYyYTAzZiI+TXkgTG9nbzwvdGV4dD4KICA8cGF0aCBpZD0ic3ZnXzIiIGQ9Im0zOTUuNjAyNSw1MS4xODM1OWw1My44Nzc3MSwwbDE2LjY0ODYzLC01MS4xODM1OGwxNi42NDg2NCw1MS4xODM1OGw1My44Nzc3LDBsLTQzLjU4NzksMzEuNjMyODNsMTYuNjQ5NDksNTEuMTgzNThsLTQzLjU4NzkyLC0zMS42MzM2OWwtNDMuNTg3OTEsMzEuNjMzNjlsMTYuNjQ5NDksLTUxLjE4MzU4bC00My41ODc5MiwtMzEuNjMyODN6IiBzdHJva2Utd2lkdGg9IjAiIHN0cm9rZT0iIzAwMCIgZmlsbD0iIzYyYTAzZiIvPgogPC9nPgo8L3N2Zz4="/>
)
}
}
```
### JSON Schema components
In swagger there are so called JSON Schema components. These are used to render inputs for parameters and components of request bodies with `application/x-www-form-urlencoded` or `multipart/*` media-type.
Internally swagger uses following mapping to find the JSON Schema component from OpenAPI Specification schema information:
For each schemas type(eg. `string`, `array`, …) and if defined schemas format (eg. date, uuid, …) there is a corresponding component mapping:
**If format defined:**
```js
`JsonSchema_${type}_${format}`
```
**Fallback if `JsonSchema_${type}_${format}` component does not exist or format not defined:**
```js
`JsonSchema_${type}`
```
**Default:**
```js
`JsonSchema_string`
```
With this, one can define custom input components or override existing.
#### Example Date-Picker plugin
If one would like to input date values you could provide a custom plugin to integrate [react-datepicker](https://www.npmjs.com/package/react-datepicker) into swagger-ui.
All you need to do is to create a component to wrap [react-datepicker](https://www.npmjs.com/package/react-datepicker) accordingly to the format.
**There are two cases:**
- ```yaml
type: string
format: date
```
The resulting name for mapping to succeed: `JsonSchema_string_date`
- ```yaml
type: string
format: date-time
```
The resulting name for mapping to succeed: `JsonSchema_string_date-time`
This creates the need for two components and simple logic to strip any time input in case the format is date:
```js
import React from "react";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
const JsonSchema_string_date = (props) => {
const dateNumber = Date.parse(props.value);
const date = dateNumber
? new Date(dateNumber)
: new Date();
return (
<DatePicker
selected={date}
onChange={d => props.onChange(d.toISOString().substring(0, 10))}
/>
);
}
const JsonSchema_string_date_time = (props) => {
const dateNumber = Date.parse(props.value);
const date = dateNumber
? new Date(dateNumber)
: new Date();
return (
<DatePicker
selected={date}
onChange={d => props.onChange(d.toISOString())}
showTimeSelect
timeFormat="p"
dateFormat="Pp"
/>
);
}
export const DateTimeSwaggerPlugin = {
components: {
JsonSchema_string_date: JsonSchema_string_date,
"JsonSchema_string_date-time": JsonSchema_string_date_time
}
};
```
### Request Snippets
SwaggerUI can be configured with the `requestSnippetsEnabled: true` option to activate Request Snippets.
Instead of the generic curl that is generated upon doing a request. It gives you more granular options:
- curl for bash
- curl for cmd
- curl for powershell
There might be the case where you want to provide your own snipped generator. This can be done by using the plugin api.
A Request Snipped generator consists of the configuration and a `fn`,
which takes the internal request object and transforms it to the desired snippet.
```js
// Add config to Request Snippets Configuration with an unique key like "node_native"
const snippetConfig = {
requestSnippetsEnabled: true,
requestSnippets: {
generators: {
"node_native": {
title: "NodeJs Native",
syntax: "javascript"
}
}
}
}
const SnippedGeneratorNodeJsPlugin = {
fn: {
// use `requestSnippetGenerator_` + key from config (node_native) for generator fn
requestSnippetGenerator_node_native: (request) => {
const url = new Url(request.get("url"))
let isMultipartFormDataRequest = false
const headers = request.get("headers")
if(headers && headers.size) {
request.get("headers").map((val, key) => {
isMultipartFormDataRequest = isMultipartFormDataRequest || /^content-type$/i.test(key) && /^multipart\/form-data$/i.test(val)
})
}
const packageStr = url.protocol === "https:" ? "https" : "http"
let reqBody = request.get("body")
if (request.get("body")) {
if (isMultipartFormDataRequest && ["POST", "PUT", "PATCH"].includes(request.get("method"))) {
return "throw new Error(\"Currently unsupported content-type: /^multipart\\/form-data$/i\");"
} else {
if (!Map.isMap(reqBody)) {
if (typeof reqBody !== "string") {
reqBody = JSON.stringify(reqBody)
}
} else {
reqBody = getStringBodyOfMap(request)
}
}
} else if (!request.get("body") && request.get("method") === "POST") {
reqBody = ""
}
const stringBody = "`" + (reqBody || "")
.replace(/\\n/g, "\n")
.replace(/`/g, "\\`")
+ "`"
return `const http = require("${packageStr}");
const options = {
"method": "${request.get("method")}",
"hostname": "${url.host}",
"port": ${url.port || "null"},
"path": "${url.pathname}"${headers && headers.size ? `,
"headers": {
${request.get("headers").map((val, key) => `"${key}": "${val}"`).valueSeq().join(",\n ")}
}` : ""}
};
const req = http.request(options, function (res) {
const chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function () {
const body = Buffer.concat(chunks);
console.log(body.toString());
});
});
${reqBody ? `\nreq.write(${stringBody});` : ""}
req.end();`
}
}
}
const ui = SwaggerUIBundle({
"dom_id": "#swagger-ui",
deepLinking: true,
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl,
SnippedGeneratorNodeJsPlugin
],
layout: "StandaloneLayout",
validatorUrl: "https://validator.swagger.io/validator",
url: "https://petstore.swagger.io/v2/swagger.json",
...snippetConfig,
})
```
### Error handling
SwaggerUI comes with a `safe-render` plugin that handles error handling allows plugging into error handling system and modify it.
The plugin accepts a list of component names that should be protected by error boundaries.
Its public API looks like this:
```js
{
fn: {
componentDidCatch,
withErrorBoundary: withErrorBoundary(getSystem),
},
components: {
ErrorBoundary,
Fallback,
},
}
```
safe-render plugin is automatically utilized by [base](https://github.com/swagger-api/swagger-ui/blob/78f62c300a6d137e65fd027d850981b010009970/src/core/presets/base.js) and [standalone](https://github.com/swagger-api/swagger-ui/tree/78f62c300a6d137e65fd027d850981b010009970/src/standalone) SwaggerUI presets and
should always be used as the last plugin, after all the components are already known to the SwaggerUI.
The plugin defines a default list of components that should be protected by error boundaries:
```js
[
"App",
"BaseLayout",
"VersionPragmaFilter",
"InfoContainer",
"ServersContainer",
"SchemesContainer",
"AuthorizeBtnContainer",
"FilterContainer",
"Operations",
"OperationContainer",
"parameters",
"responses",
"OperationServers",
"Models",
"ModelWrapper",
"Topbar",
"StandaloneLayout",
"onlineValidatorBadge"
]
```
As demonstrated below, additional components can be protected by utilizing the safe-render plugin
with configuration options. This gets really handy if you are a SwaggerUI integrator and you maintain a number of
plugins with additional custom components.
```js
const swaggerUI = SwaggerUI({
url: "https://petstore.swagger.io/v2/swagger.json",
dom_id: '#swagger-ui',
plugins: [
() => ({
components: {
MyCustomComponent1: () => 'my custom component',
},
}),
SwaggerUI.plugins.SafeRender({
fullOverride: true, // only the component list defined here will apply (not the default list)
componentList: [
"MyCustomComponent1",
],
}),
],
});
```
##### componentDidCatch
This static function is invoked after a component has thrown an error.
It receives two parameters:
1. `error` - The error that was thrown.
2. `info` - An object with a componentStack key containing [information about which component threw the error](https://reactjs.org/docs/error-boundaries.html#component-stack-traces).
It has precisely the same signature as error boundaries [componentDidCatch lifecycle method](https://reactjs.org/docs/react-component.html#componentdidcatch),
except it's a static function and not a class method.
Default implement of componentDidCatch uses `console.error` to display the received error:
```js
export const componentDidCatch = console.error;
```
To utilize your own error handling logic (e.g. [bugsnag](https://www.bugsnag.com/)), create new SwaggerUI plugin that overrides componentDidCatch:
{% highlight js linenos %}
const BugsnagErrorHandlerPlugin = () => {
// init bugsnag
return {
fn: {
componentDidCatch = (error, info) => {
Bugsnag.notify(error);
Bugsnag.notify(info);
},
},
};
};
{% endhighlight %}
##### withErrorBoundary
This function is HOC (Higher Order Component). It wraps a particular component into the `ErrorBoundary` component.
It can be overridden via a plugin system to control how components are wrapped by the ErrorBoundary component.
In 99.9% of situations, you won't need to override this function, but if you do, please read the source code of this function first.
##### Fallback
The component is displayed when the error boundary catches an error. It can be overridden via a plugin system.
Its default implementation is trivial:
```js
import React from "react"
import PropTypes from "prop-types"
const Fallback = ({ name }) => (
<div className="fallback">
😱 <i>Could not render { name === "t" ? "this component" : name }, see the console.</i>
</div>
)
Fallback.propTypes = {
name: PropTypes.string.isRequired,
}
export default Fallback
```
Feel free to override it to match your look & feel:
```js
const CustomFallbackPlugin = () => ({
components: {
Fallback: ({ name } ) => `This is my custom fallback. ${name} failed to render`,
},
});
const swaggerUI = SwaggerUI({
url: "https://petstore.swagger.io/v2/swagger.json",
dom_id: '#swagger-ui',
plugins: [
CustomFallbackPlugin,
]
});
```
##### ErrorBoundary
This is the component that implements React error boundaries. Uses `componentDidCatch` and `Fallback`
under the hood. In 99.9% of situations, you won't need to override this component, but if you do,
please read the source code of this component first.
##### Change in behavior
In prior releases of SwaggerUI (before v4.3.0), almost all components have been protected, and when thrown error,
`Fallback` component was displayed. This changes with SwaggerUI v4.3.0. Only components defined
by the `safe-render` plugin are now protected and display fallback. If a small component somewhere within
SwaggerUI React component tree fails to render and throws an error. The error bubbles up to the closest
error boundary, and that error boundary displays the `Fallback` component and invokes `componentDidCatch`.

View file

@ -0,0 +1,455 @@
# Plugins
A plugin is a function that returns an object - more specifically, the object may contain functions and components that augment and modify Swagger UI's functionality.
### Note: Semantic Versioning
Swagger UI's internal APIs are _not_ part of our public contract, which means that they can change without the major version change.
If your custom plugins wrap, extend, override, or consume any internal core APIs, we recommend specifying a specific minor version of Swagger UI to use in your application, because they will _not_ change between patch versions.
If you're installing Swagger UI via NPM, for example, you can do this by using a tilde:
```js
{
"dependencies": {
"swagger-ui": "~3.11.0"
}
}
```
### Format
A plugin return value may contain any of these keys, where `stateKey` is a name for a piece of state:
```javascript
{
statePlugins: {
[stateKey]: {
actions,
reducers,
selectors,
wrapActions,
wrapSelectors
}
},
components: {},
wrapComponents: {},
rootInjects: {},
afterLoad: (system) => {},
fn: {},
}
```
### System is provided to plugins
Let's assume we have a plugin, `NormalPlugin`, that exposes a `doStuff` action under the `normal` state namespace.
```javascript
const ExtendingPlugin = function(system) {
return {
statePlugins: {
extending: {
actions: {
doExtendedThings: function(...args) {
// you can do other things in here if you want
return system.normalActions.doStuff(...args)
}
}
}
}
}
}
```
As you can see, each plugin is passed a reference to the `system` being built up. As long as `NormalPlugin` is compiled before `ExtendingPlugin`, this will work without any issues.
There is no dependency management built into the plugin system, so if you create a plugin that relies on another, it is your responsibility to make sure that the dependent plugin is loaded _after_ the plugin being depended on.
### Interfaces
#### Actions
```javascript
const MyActionPlugin = () => {
return {
statePlugins: {
example: {
actions: {
updateFavoriteColor: (str) => {
return {
type: "EXAMPLE_SET_FAV_COLOR",
payload: str
}
}
}
}
}
}
}
```
Once an action has been defined, you can use it anywhere that you can get a system reference:
```javascript
// elsewhere
system.exampleActions.updateFavoriteColor("blue")
```
The Action interface enables the creation of new Redux action creators within a piece of state in the Swagger UI system.
This action creator function will be exposed to container components as `exampleActions.updateFavoriteColor`. When this action creator is called, the return value (which should be a [Flux Standard Action](https://github.com/acdlite/flux-standard-action)) will be passed to the `example` reducer, which we'll define in the next section.
For more information about the concept of actions in Redux, see the [Redux Actions documentation](https://redux.js.org/tutorials/fundamentals/part-2-concepts-data-flow#actions).
#### Reducers
Reducers take a state (which is an [Immutable.js map](https://facebook.github.io/immutable-js/docs/#/Map)) and an action, then returns a new state.
Reducers must be provided to the system under the name of the action type that they handle, in this case, `EXAMPLE_SET_FAV_COLOR`.
```javascript
const MyReducerPlugin = function(system) {
return {
statePlugins: {
example: {
reducers: {
"EXAMPLE_SET_FAV_COLOR": (state, action) => {
// you're only working with the state under the namespace, in this case "example".
// So you can do what you want, without worrying about /other/ namespaces
return state.set("favColor", action.payload)
}
}
}
}
}
}
```
#### Selectors
Selectors reach into their namespace's state to retrieve or derive data from the state.
They're an easy way to keep logic in one place, and are preferred over passing state data directly into components.
```javascript
const MySelectorPlugin = function(system) {
return {
statePlugins: {
example: {
selectors: {
myFavoriteColor: (state) => state.get("favColor")
}
}
}
}
}
```
You can also use the Reselect library to memoize your selectors, which is recommended for any selectors that will see heavy use, since Reselect automatically memoizes selector calls for you:
```javascript
import { createSelector } from "reselect"
const MySelectorPlugin = function(system) {
return {
statePlugins: {
example: {
selectors: {
// this selector will be memoized after it is run once for a
// value of `state`
myFavoriteColor: createSelector((state) => state.get("favColor"))
}
}
}
}
}
```
Once a selector has been defined, you can use it anywhere that you can get a system reference:
```javascript
system.exampleSelectors.myFavoriteColor() // gets `favColor` in state for you
```
#### Components
You can provide a map of components to be integrated into the system.
Be mindful of the key names for the components you provide, as you'll need to use those names to refer to the components elsewhere.
```javascript
class HelloWorldClass extends React.Component {
render() {
return <h1>Hello World!</h1>
}
}
const MyComponentPlugin = function(system) {
return {
components: {
HelloWorldClass: HelloWorldClass
// components can just be functions, these are called "stateless components"
HelloWorldStateless: () => <h1>Hello World!</h1>,
}
}
}
```
```javascript
// elsewhere
const HelloWorldStateless = system.getComponent("HelloWorldStateless")
const HelloWorldClass = system.getComponent("HelloWorldClass")
```
You can also "cancel out" any components that you don't want by creating a stateless component that always returns `null`:
```javascript
const NeverShowInfoPlugin = function(system) {
return {
components: {
info: () => null
}
}
}
```
You can use `config.failSilently` if you don't want a warning when a component doesn't exist in the system.
Be mindful of `getComponent` arguments order. In the example below, the boolean `false` refers to presence of a container, and the 3rd argument is the config object used to suppress the missing component warning.
```javascript
const thisVariableWillBeNull = getComponent("not_real", false, { failSilently: true })
```
#### Wrap-Actions
Wrap Actions allow you to override the behavior of an action in the system.
They are function factories with the signature `(oriAction, system) => (...args) => result`.
A Wrap Action's first argument is `oriAction`, which is the action being wrapped. It is your responsibility to call the `oriAction` - if you don't, the original action will not fire!
This mechanism is useful for conditionally overriding built-in behaviors, or listening to actions.
```javascript
// FYI: in an actual Swagger UI, `updateSpec` is already defined in the core code
// it's just here for clarity on what's behind the scenes
const MySpecPlugin = function(system) {
return {
statePlugins: {
spec: {
actions: {
updateSpec: (str) => {
return {
type: "SPEC_UPDATE_SPEC",
payload: str
}
}
}
}
}
}
}
// this plugin allows you to watch changes to the spec that is in memory
const MyWrapActionPlugin = function(system) {
return {
statePlugins: {
spec: {
wrapActions: {
updateSpec: (oriAction, system) => (str) => {
// here, you can hand the value to some function that exists outside of Swagger UI
console.log("Here is my API definition", str)
return oriAction(str) // don't forget! otherwise, Swagger UI won't update
}
}
}
}
}
}
```
#### Wrap-Selectors
Wrap Selectors allow you to override the behavior of a selector in the system.
They are function factories with the signature `(oriSelector, system) => (state, ...args) => result`.
This interface is useful for controlling what data flows into components. We use this in the core code to disable selectors based on the API definition's version.
```javascript
import { createSelector } from 'reselect'
// FYI: in an actual Swagger UI, the `url` spec selector is already defined
// it's just here for clarity on what's behind the scenes
const MySpecPlugin = function(system) {
return {
statePlugins: {
spec: {
selectors: {
url: createSelector(
state => state.get("url")
)
}
}
}
}
}
const MyWrapSelectorsPlugin = function(system) {
return {
statePlugins: {
spec: {
wrapSelectors: {
url: (oriSelector, system) => (state, ...args) => {
console.log('someone asked for the spec url!!! it is', state.get('url'))
// you can return other values here...
// but let's just enable the default behavior
return oriSelector(state, ...args)
}
}
}
}
}
}
```
#### Wrap-Components
Wrap Components allow you to override a component registered within the system.
Wrap Components are function factories with the signature `(OriginalComponent, system) => props => ReactElement`. If you'd prefer to provide a React component class, `(OriginalComponent, system) => ReactClass` works as well.
```javascript
const MyWrapBuiltinComponentPlugin = function(system) {
return {
wrapComponents: {
info: (Original, system) => (props) => {
return <div>
<h3>Hello world! I am above the Info component.</h3>
<Original {...props} />
</div>
}
}
}
}
```
Here's another example that includes a code sample of a component that will be wrapped:
```javascript
///// Overriding a component from a plugin
// Here's our normal, unmodified component.
const MyNumberDisplayPlugin = function(system) {
return {
components: {
NumberDisplay: ({ number }) => <span>{number}</span>
}
}
}
// Here's a component wrapper defined as a function.
const MyWrapComponentPlugin = function(system) {
return {
wrapComponents: {
NumberDisplay: (Original, system) => (props) => {
if(props.number > 10) {
return <div>
<h3>Warning! Big number ahead.</h3>
<Original {...props} />
</div>
} else {
return <Original {...props} />
}
}
}
}
}
// Alternatively, here's the same component wrapper defined as a class.
const MyWrapComponentPlugin = function(system) {
return {
wrapComponents: {
NumberDisplay: (Original, system) => class WrappedNumberDisplay extends React.component {
render() {
if(props.number > 10) {
return <div>
<h3>Warning! Big number ahead.</h3>
<Original {...props} />
</div>
} else {
return <Original {...props} />
}
}
}
}
}
}
```
#### `rootInjects`
The `rootInjects` interface allows you to inject values at the top level of the system.
This interface takes an object, which will be merged in with the top-level system object at runtime.
```js
const MyRootInjectsPlugin = function(system) {
return {
rootInjects: {
myConstant: 123,
myMethod: (...params) => console.log(...params)
}
}
}
```
#### `afterLoad`
The `afterLoad` plugin method allows you to get a reference to the system after your plugin has been registered.
This interface is used in the core code to attach methods that are driven by bound selectors or actions. You can also use it to execute logic that requires your plugin to already be ready, for example fetching initial data from a remote endpoint and passing it to an action your plugin creates.
The plugin context, which is bound to `this`, is undocumented, but below is an example of how to attach a bound action as a top-level method:
```javascript
const MyMethodProvidingPlugin = function() {
return {
afterLoad(system) {
// at this point in time, your actions have been bound into the system
// so you can do things with them
this.rootInjects = this.rootInjects || {}
this.rootInjects.myMethod = system.exampleActions.updateFavoriteColor
},
statePlugins: {
example: {
actions: {
updateFavoriteColor: (str) => {
return {
type: "EXAMPLE_SET_FAV_COLOR",
payload: str
}
}
}
}
}
}
}
```
#### fn
The fn interface allows you to add helper functions to the system for use elsewhere.
```javascript
import leftPad from "left-pad"
const MyFnPlugin = function(system) {
return {
fn: {
leftPad: leftPad
}
}
}
```

View file

@ -0,0 +1,40 @@
# Helpful scripts
Any of the scripts below can be run by typing `npm run <script name>` in the project's root directory.
### Developing
Script name | Description
--- | ---
`dev` | Spawn a hot-reloading dev server on port 3200.
`deps-check` | Generate a size and licensing report on Swagger UI's dependencies.
`lint` | Report ESLint style errors and warnings.
`lint-errors` | Report ESLint style errors, without warnings.
`lint-fix` | Attempt to fix style errors automatically.
`lint-styles` | Report Stylelint style errors and warnings.
`lint-styles-fix` | Attempt to fix Stylelint errors and warnings automatically.
`watch` | Rebuild the core files in `/dist` when the source code changes. Useful for `npm link` with Swagger Editor.
### Building
Script name | Description
--- | ---
`build` | Build a new set of JS and CSS assets, and output them to `/dist`.
`build-bundle` | Build `swagger-ui-bundle.js` only (commonJS).
`build-core` | Build `swagger-ui.(js\|css)` only (commonJS).
`build-standalone` | Build `swagger-ui-standalone-preset.js` only (commonJS).
`build-stylesheets` | Build `swagger-ui.css` only.
`build:es:bundle` | Build `swagger-ui-es-bundle.js` only (es2015).
`build:es:bundle:core` | Build `swagger-ui-es-bundle-core.js` only (es2015).
### Testing
Script name | Description
--- | ---
`test` | Run unit tests in Node, run Cypress end-to-end tests, and run ESLint in errors-only mode.
`test:unit` | Run Jest unit tests in Node.
`e2e` | Run end-to-end tests (requires JDK and Selenium).
`e2e-cypress` | Run end-to-end browser tests with Cypress.
`dev-e2e-cypress` | Dev mode, open Cypress runner and manually select tests to run.
`lint` | Run ESLint test
`test:artifact` | Run list of bundle artifact tests in Jest
`test:artifact:umd:bundle` | Run unit test that confirms `swagger-ui-bundle` exports as a Function
`test:artifact:es:bundle` | Run unit test that confirms `swagger-ui-es-bundle` exports as a Function
`test:artifact:es:bundle:core` | Run unit test that confirms `swagger-ui-es-bundle-core` exports as a Function

View file

@ -0,0 +1,41 @@
# Setting up a dev environment
SwaggerUI includes a development server that provides hot module reloading and unminified stack traces, for easier development.
### Prerequisites
- git, any version
- **Node.js >=22.11.0** and **npm >=10.9.0** are the minimum required versions that this repo runs on, but we always recommend using the latest version of Node.js.
### Steps
1. `git clone https://github.com/swagger-api/swagger-ui.git`
2. `cd swagger-ui`
3. `npm install`
4. `npx husky init` (optional)
5. `npm run dev`
6. Wait a bit
7. Open http://localhost:3200/
### Using your own local api definition with local dev build
You can specify a local file in `dev-helpers/dev-helper-initializer.js` by changing the `url` parameter. This local file MUST be located in the `dev-helpers` directory or a subdirectory. As a convenience and best practice, we recommend that you create a subdirectory, `dev-helpers/examples`, which is already specified in `.gitignore`.
replace
```
url: "https://petstore.swagger.io/v2/swagger.json",
```
with
```
url: "./examples/your-local-api-definition.yaml",
```
Files in `dev-helpers` should NOT be committed to git. The exception is if you are fixing something in `index.html`, `oauth2-redirect.html`, `dev-helper-initializer.js`, or introducing a new support file.
## Bonus points
- Swagger UI includes an ESLint rule definition. If you use a graphical editor, consider installing an ESLint plugin, which will point out syntax and style errors for you as you code.
- The linter runs as part of the PR test sequence, so don't think you can get away with not paying attention to it!

Binary file not shown.

After

Width:  |  Height:  |  Size: 665 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 628 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 97 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 78 KiB

16
plugin/API/docs/index.css Normal file
View file

@ -0,0 +1,16 @@
html {
box-sizing: border-box;
overflow: -moz-scrollbars-vertical;
overflow-y: scroll;
}
*,
*:before,
*:after {
box-sizing: inherit;
}
body {
margin: 0;
background: #fafafa;
}

View file

@ -0,0 +1,19 @@
<!-- HTML for static distribution bundle build -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Swagger UI</title>
<link rel="stylesheet" type="text/css" href="./swagger-ui.css" />
<link rel="stylesheet" type="text/css" href="index.css" />
<link rel="icon" type="image/png" href="./favicon-32x32.png" sizes="32x32" />
<link rel="icon" type="image/png" href="./favicon-16x16.png" sizes="16x16" />
</head>
<body>
<div id="swagger-ui"></div>
<script src="./swagger-ui-bundle.js" charset="UTF-8"> </script>
<script src="./swagger-ui-standalone-preset.js" charset="UTF-8"> </script>
<script src="./swagger-initializer.js?2" charset="UTF-8"> </script>
</body>
</html>

View file

@ -0,0 +1,79 @@
<!doctype html>
<html lang="en-US">
<head>
<title>Swagger UI: OAuth2 Redirect</title>
</head>
<body>
<script>
'use strict';
function run () {
var oauth2 = window.opener.swaggerUIRedirectOauth2;
var sentState = oauth2.state;
var redirectUrl = oauth2.redirectUrl;
var isValid, qp, arr;
if (/code|token|error/.test(window.location.hash)) {
qp = window.location.hash.substring(1).replace('?', '&');
} else {
qp = location.search.substring(1);
}
arr = qp.split("&");
arr.forEach(function (v,i,_arr) { _arr[i] = '"' + v.replace('=', '":"') + '"';});
qp = qp ? JSON.parse('{' + arr.join() + '}',
function (key, value) {
return key === "" ? value : decodeURIComponent(value);
}
) : {};
isValid = qp.state === sentState;
if ((
oauth2.auth.schema.get("flow") === "accessCode" ||
oauth2.auth.schema.get("flow") === "authorizationCode" ||
oauth2.auth.schema.get("flow") === "authorization_code"
) && !oauth2.auth.code) {
if (!isValid) {
oauth2.errCb({
authId: oauth2.auth.name,
source: "auth",
level: "warning",
message: "Authorization may be unsafe, passed state was changed in server. The passed state wasn't returned from auth server."
});
}
if (qp.code) {
delete oauth2.state;
oauth2.auth.code = qp.code;
oauth2.callback({auth: oauth2.auth, redirectUrl: redirectUrl});
} else {
let oauthErrorMsg;
if (qp.error) {
oauthErrorMsg = "["+qp.error+"]: " +
(qp.error_description ? qp.error_description+ ". " : "no accessCode received from the server. ") +
(qp.error_uri ? "More info: "+qp.error_uri : "");
}
oauth2.errCb({
authId: oauth2.auth.name,
source: "auth",
level: "error",
message: oauthErrorMsg || "[Authorization failed]: no accessCode received from the server."
});
}
} else {
oauth2.callback({auth: oauth2.auth, token: qp, isValid: isValid, redirectUrl: redirectUrl});
}
window.close();
}
if (document.readyState !== 'loading') {
run();
} else {
document.addEventListener('DOMContentLoaded', function () {
run();
});
}
</script>
</body>
</html>

View file

@ -0,0 +1,14 @@
### Demo of Swagger UI with Webpack.
This `webpack-getting-started` sample is for reference only.
It includes CSS and OAuth configuration.
`_sample_package.json` is a placeholder sample. You should rename this file, per `Usage` section below, and you should also verify and update this sample's `@latest` compared to the `swagger-ui@latest`
#### Usage
rename `_sample_package.json` to `package.json`
npm install
npm start

View file

@ -0,0 +1,26 @@
{
"name": "swagger-ui-webpack-getting-started",
"version": "0.0.1",
"description": "A simple setup of Swagger UI with Webpack",
"scripts": {
"build": "webpack",
"start": "webpack-dev-server --open"
},
"author": "Shaun Luttin",
"license": "Apache-2.0",
"devDependencies": {
"clean-webpack-plugin": "^4.0.0",
"copy-webpack-plugin": "^11.0.0",
"html-webpack-plugin": "^5.5.0",
"webpack": "^5.74.0",
"webpack-cli": "^4.10.0",
"webpack-dev-server": "^4.11.0"
},
"dependencies": {
"css-loader": "^6.7.1",
"json-loader": "^0.5.7",
"style-loader": "^3.3.1",
"swagger-ui": "^4.14.0",
"yaml-loader": "^0.8.0"
}
}

View file

@ -0,0 +1,10 @@
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Getting Started</title>
</head>
<body>
<div id="swagger"></div>
</body>
</html>

View file

@ -0,0 +1,15 @@
import SwaggerUI from 'swagger-ui'
import 'swagger-ui/dist/swagger-ui.css';
const spec = require('./swagger-config.yaml');
const ui = SwaggerUI({
spec,
dom_id: '#swagger',
});
ui.initOAuth({
appName: "Swagger UI Webpack Demo",
// See https://demo.identityserver.io/ for configuration details.
clientId: 'implicit'
});

View file

@ -0,0 +1,30 @@
openapi: "3.0.4"
info:
version: "0.0.1"
title: "Swagger UI Webpack Setup"
description: "Demonstrates Swagger UI with Webpack including CSS and OAuth"
servers:
- url: "https://demo.identityserver.io/api"
description: "Identity Server test API"
components:
securitySchemes:
# See https://demo.identityserver.io/ for configuration details.
identity_server_auth:
type: oauth2
flows:
implicit:
authorizationUrl: "https://demo.identityserver.io/connect/authorize"
scopes:
api: "api"
security:
- identity_server_auth:
- api
paths:
/test:
get:
summary: "Runs a test request against the Identity Server demo API"
responses:
401:
description: "Unauthorized"
200:
description: "OK"

View file

@ -0,0 +1,52 @@
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const outputPath = path.resolve(__dirname, 'dist');
module.exports = {
mode: 'development',
entry: {
app: require.resolve('./src/index'),
},
resolve: {
extensions: ['.ts', '.js'],
},
module: {
rules: [
{
test: /\.yaml$/,
use: [
{ loader: 'json-loader' },
{ loader: 'yaml-loader', options:{ asJSON: true } }
]
},
{
test: /\.css$/,
use: [
{ loader: 'style-loader' },
{ loader: 'css-loader' },
]
}
]
},
plugins: [
new CleanWebpackPlugin(),
new CopyWebpackPlugin({patterns:[
{
// Copy the Swagger OAuth2 redirect file to the project root;
// that file handles the OAuth2 redirect after authenticating the end-user.
from: require.resolve('swagger-ui/dist/oauth2-redirect.html'),
to: './'
}
]}),
new HtmlWebpackPlugin({
template: 'index.html'
})
],
output: {
filename: '[name].bundle.js',
path: outputPath,
}
};

View file

@ -0,0 +1,21 @@
window.onload = function() {
//<editor-fold desc="Changeable Configuration Block">
// the following lines will be replaced by docker/configurator, when it runs in a docker-container
window.ui = SwaggerUIBundle({
//url: "https://petstore.swagger.io/v2/swagger.json",
url: "../swagger.json.php",
dom_id: '#swagger-ui',
deepLinking: true,
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
],
layout: "StandaloneLayout"
});
//</editor-fold>
};

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,383 @@
# Configuration
### How to configure
Swagger UI accepts configuration parameters in three locations.
From lowest to highest precedence:
- configuration object passed as an argument to Swagger UI (`SwaggerUI({ ... })`)
- configuration document fetched from a specified `configUrl`
- configuration items passed as key/value pairs in the URL query string
### Parameters
Parameters with dots in their names are single strings used to organize subordinate parameters, and are not indicative of a nested structure.
For readability, parameters are grouped by category and sorted alphabetically.
Type notations are formatted like so:
- `String=""` means a String type with a default value of `""`.
- `String=["a"*, "b", "c", "d"]` means a String type that can be `a`, `b`, `c`, or `d`, with the `*` indicating that `a` is the default value.
##### Core
Parameter name | Docker variable | Description
--- | --- | -----
<a name="configUrl"></a>`configUrl` | `CONFIG_URL` | `String`. URL to fetch external configuration document from.
<a name="dom_id"></a>`dom_id` | `DOM_ID` |`String`, **REQUIRED** if `domNode` is not provided. The ID of a DOM element inside which `SwaggerUI` will put its user interface.
<a name="domNode"></a>`domNode` | _Unavailable_ | `Element`, **REQUIRED** if `dom_id` is not provided. The HTML DOM element inside which `SwaggerUI` will put its user interface. Overrides `dom_id`.
<a name="spec"></a>`spec` | `SPEC` | `Object={}`. A JavaScript object describing the OpenAPI definition. When used, the `url` parameter will not be parsed. This is useful for testing manually-generated definitions without hosting them.
<a name="url"></a>`url` | `URL` | `String`. The URL pointing to API definition (normally `swagger.json` or `swagger.yaml`). Will be ignored if `urls` or `spec` is used.
<a name="urls"></a>`urls` | `URLS` | `Array`. An array of API definition objects (`[{url: "<url1>", name: "<name1>"},{url: "<url2>", name: "<name2>"}]`) used by Topbar plugin. When used and Topbar plugin is enabled, the `url` parameter will not be parsed. Names and URLs must be unique among all items in this array, since they're used as identifiers.
<a name="urls.primaryName"></a>`urls.primaryName` | `URLS_PRIMARY_NAME` | `String`. When using `urls`, you can use this subparameter. If the value matches the name of a spec provided in `urls`, that spec will be displayed when Swagger UI loads, instead of defaulting to the first spec in `urls`.
<a name="queryConfigEnabled"></a>`queryConfigEnabled` | `QUERY_CONFIG_ENABLED` | `Boolean=false`. Enables overriding configuration parameters via URL search params.
##### Plugin system
Read more about the plugin system in the [Customization documentation](/docs/customization/overview.md).
Parameter name | Docker variable | Description
--- | --- | -----
<a name="layout"></a>`layout` | _Unavailable_ | `String="BaseLayout"`. The name of a component available via the plugin system to use as the top-level layout for Swagger UI.
<a name="plugins"></a>`plugins` | _Unavailable_ | `Array=[]`. An array of plugin functions to use in Swagger UI.
<a name="presets"></a>`presets` | _Unavailable_ | `Array=[SwaggerUI.presets.ApisPreset]`. An array of presets to use in Swagger UI. Usually, you'll want to include `ApisPreset` if you use this option.
##### Display
<table role="table">
<thead>
<tr>
<th>Parameter name</th>
<th>Docker variable</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><a name="user-content-deeplinking"></a><code>deepLinking</code></td>
<td><code>DEEP_LINKING</code></td>
<td><code>Boolean=false</code>. If set to <code>true</code>, enables
deep linking for tags and operations. See the <a
href="/docs/usage/deep-linking.md">Deep Linking
documentation</a> for more information.
</td>
</tr>
<tr>
<td><a name="user-content-displayoperationid"></a><code>displayOperationId</code>
</td>
<td><code>DISPLAY_OPERATION_ID</code></td>
<td><code>Boolean=false</code>. Controls the display of operationId in
operations list. The default is <code>false</code>.
</td>
</tr>
<tr>
<td><a name="user-content-defaultmodelsexpanddepth"></a><code>defaultModelsExpandDepth</code>
</td>
<td><code>DEFAULT_MODELS_EXPAND_DEPTH</code></td>
<td><code>Number=1</code>. The default expansion depth for models (set
to -1 completely hide the models).
</td>
</tr>
<tr>
<td><a name="user-content-defaultmodelexpanddepth"></a><code>defaultModelExpandDepth</code>
</td>
<td><code>DEFAULT_MODEL_EXPAND_DEPTH</code></td>
<td><code>Number=1</code>. The default expansion depth for the model on
the model-example section.
</td>
</tr>
<tr>
<td><a name="user-content-defaultmodelrendering"></a><code>defaultModelRendering</code>
</td>
<td><code>DEFAULT_MODEL_RENDERING</code></td>
<td><code>String=["example"*, "model"]</code>. Controls how the model is
shown when the API is first rendered. (The user can always switch
the rendering for a given model by clicking the 'Model' and 'Example
Value' links.)
</td>
</tr>
<tr>
<td><a name="user-content-displayrequestduration"></a><code>displayRequestDuration</code>
</td>
<td><code>DISPLAY_REQUEST_DURATION</code></td>
<td><code>Boolean=false</code>. Controls the display of the request
duration (in milliseconds) for "Try it out" requests.
</td>
</tr>
<tr>
<td><a name="user-content-docexpansion"></a><code>docExpansion</code>
</td>
<td><code>DOC_EXPANSION</code></td>
<td><code>String=["list"*, "full", "none"]</code>. Controls the default
expansion setting for the operations and tags. It can be 'list'
(expands only the tags), 'full' (expands the tags and operations) or
'none' (expands nothing).
</td>
</tr>
<tr>
<td><a name="user-content-filter"></a><code>filter</code></td>
<td><code>FILTER</code></td>
<td><code>Boolean=false OR String</code>. If set, enables filtering. The
top bar will show an edit box that you can use to filter the tagged
operations that are shown. Can be Boolean to enable or disable, or a
string, in which case filtering will be enabled using that string as
the filter expression. Filtering is case sensitive matching the
filter expression anywhere inside the tag.
</td>
</tr>
<tr>
<td>
<a name="user-content-maxdisplayedtags"></a><code>maxDisplayedTags</code>
</td>
<td><code>MAX_DISPLAYED_TAGS</code></td>
<td><code>Number</code>. If set, limits the number of tagged operations
displayed to at most this many. The default is to show all
operations.
</td>
</tr>
<tr>
<td>
<a name="user-content-operationssorter"></a><code>operationsSorter</code>
</td>
<td><em>Unavailable</em></td>
<td><code>Function=(a =&gt; a)</code>. Apply a sort to the operation
list of each API. It can be 'alpha' (sort by paths
alphanumerically), 'method' (sort by HTTP method) or a function (see
Array.prototype.sort() to know how sort function works). Default is
the order returned by the server unchanged.
</td>
</tr>
<tr>
<td>
<a name="user-content-showextensions"></a><code>showExtensions</code>
</td>
<td><code>SHOW_EXTENSIONS</code></td>
<td><code>Boolean=false</code>. Controls the display of vendor extension
(<code>x-</code>) fields and values for Operations, Parameters,
Responses, and Schema.
</td>
</tr>
<tr>
<td><a name="user-content-showcommonextensions"></a><code>showCommonExtensions</code>
</td>
<td><code>SHOW_COMMON_EXTENSIONS</code></td>
<td><code>Boolean=false</code>. Controls the display of extensions
(<code>pattern</code>, <code>maxLength</code>,
<code>minLength</code>, <code>maximum</code>, <code>minimum</code>)
fields and values for Parameters.
</td>
</tr>
<tr>
<td><a name="user-content-tagsorter"></a><code>tagsSorter</code></td>
<td><em>Unavailable</em></td>
<td><code>Function=(a =&gt; a)</code>. Apply a sort to the tag list of
each API. It can be 'alpha' (sort by paths alphanumerically) or a
function (see <a
href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort"
rel="nofollow">Array.prototype.sort()</a> to learn how to
write a sort function). Two tag name strings are passed to the
sorter for each pass. Default is the order determined by Swagger UI.
</td>
</tr>
<tr>
<td>
<a name="user-content-useunsafemarkdown"></a><code>useUnsafeMarkdown</code>
</td>
<td><code>USE_UNSAFE_MARKDOWN</code></td>
<td><code>Boolean=false</code>. When enabled, sanitizer will leave
<code>style</code>, <code>class</code> and <code>data-*</code>
attributes untouched on all HTML Elements declared inside markdown
strings. This parameter is <strong>Deprecated</strong> and will be
removed in <code>4.0.0</code>.
</td>
</tr>
<tr>
<td><a name="user-content-oncomplete"></a><code>onComplete</code></td>
<td><em>Unavailable</em></td>
<td><code>Function=NOOP</code>. Provides a mechanism to be notified when
Swagger UI has finished rendering a newly provided definition.
</td>
</tr>
<tr>
<td>
<a name="user-content-syntaxhighlight"></a><code>syntaxHighlight</code>
</td>
<td><em>Unavailable</em></td>
<td>Set to <code>false</code> to deactivate syntax highlighting of
payloads and cURL command, can be otherwise an object with the
<code>activated</code> and <code>theme</code> properties.
</td>
</tr>
<tr>
<td><a name="user-content-syntaxhighlight.activated"></a><code>syntaxHighlight.activated</code>
</td>
<td><em>Unavailable</em></td>
<td><code>Boolean=true</code>. Whether syntax highlighting should be
activated or not.
</td>
</tr>
<tr>
<td><a name="user-content-syntaxhighlight.theme"></a><code>syntaxHighlight.theme</code>
</td>
<td><em>Unavailable</em></td>
<td><code>String=["agate"*, "arta", "monokai", "nord", "obsidian",
"tomorrow-night", "idea"]</code>. <a
href="https://highlightjs.org/static/demo/" rel="nofollow">Highlight.js</a>
syntax coloring theme to use. (Only these 7 styles are available.)
</td>
</tr>
<tr>
<td>
<a name="user-content-tryitoutenabled"></a><code>tryItOutEnabled</code>
</td>
<td><code>TRY_IT_OUT_ENABLED</code></td>
<td><code>Boolean=false</code>. Controls whether the "Try it out"
section should be enabled by default.
</td>
</tr>
<tr>
<td><a name="user-content-requestsnippetsenabled"></a><code>requestSnippetsEnabled</code>
</td>
<td><em>Unavailable</em></td>
<td><code>Boolean=false</code>. Enables the request snippet section.
When disabled, the legacy curl snippet will be used.
</td>
</tr>
<tr>
<td>
<a name="user-content-requestsnippets"></a><code>requestSnippets</code>
</td>
<td><em>Unavailable</em></td>
<td>
<pre lang="javascript">
<code>Object={
generators: {
curl_bash: {
title: "cURL (bash)",
syntax: "bash"
},
curl_powershell: {
title: "cURL (PowerShell)",
syntax: "powershell"
},
curl_cmd: {
title: "cURL (CMD)",
syntax: "bash"
},
},
defaultExpanded: true,
languages: null,
// e.g. only show curl bash = ["curl_bash"]
}
</code>
</pre>
This is the default configuration section for the
requestSnippets plugin.
</td>
</tr>
</tbody>
</table>
##### Network
Parameter name | Docker variable | Description
--- | --- | -----
<a name="oauth2RedirectUrl"></a>`oauth2RedirectUrl` | `OAUTH2_REDIRECT_URL` | `String`. OAuth redirect URL.
<a name="requestInterceptor"></a>`requestInterceptor` | _Unavailable_ | `Function=(a => a)`. MUST be a function. Function to intercept remote definition, "Try it out", and OAuth 2.0 requests. Accepts one argument requestInterceptor(request) and must return the modified request, or a Promise that resolves to the modified request.
<a name="request.curlOptions"></a>`request.curlOptions` | _Unavailable_ | `Array`. If set, MUST be an array of command line options available to the `curl` command. This can be set on the mutated request in the `requestInterceptor` function. For example `request.curlOptions = ["-g", "--limit-rate 20k"]`
<a name="responseInterceptor"></a>`responseInterceptor` | _Unavailable_ | `Function=(a => a)`. MUST be a function. Function to intercept remote definition, "Try it out", and OAuth 2.0 responses. Accepts one argument responseInterceptor(response) and must return the modified response, or a Promise that resolves to the modified response.
<a name="showMutatedRequest"></a>`showMutatedRequest` | `SHOW_MUTATED_REQUEST` | `Boolean=true`. If set to `true`, uses the mutated request returned from a requestInterceptor to produce the curl command in the UI, otherwise the request before the requestInterceptor was applied is used.
<a name="supportedSubmitMethods"></a>`supportedSubmitMethods` | `SUPPORTED_SUBMIT_METHODS` | `Array=["get", "put", "post", "delete", "options", "head", "patch", "trace"]`. List of HTTP methods that have the "Try it out" feature enabled. An empty array disables "Try it out" for all operations. This does not filter the operations from the display.
<a name="validatorUrl"></a>`validatorUrl` | `VALIDATOR_URL` | `String="https://validator.swagger.io/validator" OR null`. By default, Swagger UI attempts to validate specs against swagger.io's online validator. You can use this parameter to set a different validator URL, for example for locally deployed validators ([Validator Badge](https://github.com/swagger-api/validator-badge)). Setting it to either `none`, `127.0.0.1` or `localhost` will disable validation.
<a name="withCredentials"></a>`withCredentials` | `WITH_CREDENTIALS` | `Boolean=false` If set to `true`, enables passing credentials, [as defined in the Fetch standard](https://fetch.spec.whatwg.org/#credentials), in CORS requests that are sent by the browser. Note that Swagger UI cannot currently set cookies cross-domain (see [swagger-js#1163](https://github.com/swagger-api/swagger-js/issues/1163)) - as a result, you will have to rely on browser-supplied cookies (which this setting enables sending) that Swagger UI cannot control.
##### Macros
Parameter name | Docker variable | Description
--- | --- | -----
<a name="modelPropertyMacro"></a>`modelPropertyMacro` | _Unavailable_ | `Function`. Function to set default values to each property in model. Accepts one argument modelPropertyMacro(property), property is immutable
<a name="parameterMacro"></a>`parameterMacro` | _Unavailable_ | `Function`. Function to set default value to parameters. Accepts two arguments parameterMacro(operation, parameter). Operation and parameter are objects passed for context, both remain immutable
##### Authorization
Parameter name | Docker variable | Description
--- | --- | -----
<a name="persistAuthorization"></a>`persistAuthorization` | `PERSIST_AUTHORIZATION` | `Boolean=false`. If set to `true`, it persists authorization data and it would not be lost on browser close/refresh
### Instance methods
**💡 Take note! These are methods, not parameters**.
Method name | Docker variable | Description
--- | --- | -----
<a name="initOAuth"></a>`initOAuth` | [_See `oauth2.md`_](./oauth2.md) | `(configObj) => void`. Provide Swagger UI with information about your OAuth server - see the [OAuth 2.0 documentation](./oauth2.md) for more information.
<a name="preauthorizeBasic"></a>`preauthorizeBasic` | _Unavailable_ | `(authDefinitionKey, username, password) => action`. Programmatically set values for a Basic authorization scheme.
<a name="preauthorizeApiKey"></a>`preauthorizeApiKey` | _Unavailable_ | `(authDefinitionKey, apiKeyValue) => action`. Programmatically set values for an API key or Bearer authorization scheme. In case of OpenAPI 3.0 Bearer scheme, `apiKeyValue` must contain just the token itself without the `Bearer` prefix.
### Docker
If you're using the Docker image, you can also control most of these options with environment variables. Each parameter has its environment variable name noted, if available.
Below are the general guidelines for using the environment variable interface.
##### String variables
Set the value to whatever string you'd like, taking care to escape characters where necessary
Example:
```sh
FILTER="myFilterValue"
LAYOUT="BaseLayout"
```
##### Boolean variables
Set the value to `true` or `false`.
Example:
```sh
DISPLAY_OPERATION_ID="true"
DEEP_LINKING="false"
```
##### Number variables
Set the value to _`n`_, where _n_ is the number you'd like to provide.
Example:
```sh
DEFAULT_MODELS_EXPAND_DEPTH="5"
DEFAULT_MODEL_EXPAND_DEPTH="7"
```
##### Array variables
Set the value to the literal array value you'd like, taking care to escape characters where necessary.
Example:
```sh
SUPPORTED_SUBMIT_METHODS="[\"get\", \"post\"]"
URLS="[ { url: \"https://petstore.swagger.io/v2/swagger.json\", name: \"Petstore\" } ]"
```
##### Object variables
Set the value to the literal object value you'd like, taking care to escape characters where necessary.
Example:
```sh
SPEC="{ \"openapi\": \"3.0.4\" }"
```
### Docker-Compose
#### .env file example encoding
```sh
SUPPORTED_SUBMIT_METHODS=['get', 'post']
URLS=[ { url: 'https://petstore.swagger.io/v2/swagger.json', name: 'Petstore' } ]
```

View file

@ -0,0 +1,60 @@
# CORS
CORS is a technique to prevent websites from doing bad things with your personal data. Most browsers + JavaScript toolkits not only support CORS but enforce it, which has implications for your API server which supports Swagger.
You can read about CORS here: http://www.w3.org/TR/cors.
There are two cases where no action is needed for CORS support:
1. Swagger UI is hosted on the same server as the application itself (same host *and* port).
2. The application is located behind a proxy that enables the required CORS headers. This may already be covered within your organization.
Otherwise, CORS support needs to be enabled for:
1. Your Swagger docs. For Swagger 2.0 it's the `swagger.json`/`swagger.yaml` and any externally `$ref`ed docs.
2. For the `Try it now` button to work, CORS needs to be enabled on your API endpoints as well.
### Testing CORS Support
You can verify CORS support with one of three techniques:
- Curl your API and inspect the headers. For instance:
```bash
$ curl -I "https://petstore.swagger.io/v2/swagger.json"
HTTP/1.1 200 OK
Date: Sat, 31 Jan 2015 23:05:44 GMT
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, DELETE, PUT, PATCH, OPTIONS
Access-Control-Allow-Headers: Content-Type, api_key, Authorization
Content-Type: application/json
Content-Length: 0
```
This tells us that the petstore resource listing supports OPTIONS, and the following headers: `Content-Type`, `api_key`, `Authorization`.
- Try Swagger UI from your file system and look at the debug console. If CORS is not enabled, you'll see something like this:
```
XMLHttpRequest cannot load http://sad.server.com/v2/api-docs. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
```
Swagger UI cannot easily show this error state.
- Use the https://www.test-cors.org website to verify CORS support. Keep in mind this will show a successful result even if `Access-Control-Allow-Headers` is not available, which is still required for Swagger UI to function properly.
### Enabling CORS
The method of enabling CORS depends on the server and/or framework you use to host your application. https://enable-cors.org provides information on how to enable CORS in some common web servers.
Other servers/frameworks may provide you information on how to enable it specifically in their use case.
### CORS and Header Parameters
Swagger UI lets you easily send headers as parameters to requests. The name of these headers *MUST* be supported in your CORS configuration as well. From our example above:
```
Access-Control-Allow-Headers: Content-Type, api_key, Authorization
```
Only headers with these names will be allowed to be sent by Swagger UI.

View file

@ -0,0 +1,36 @@
# `deepLinking` parameter
Swagger UI allows you to deeply link into tags and operations within a spec. When Swagger UI is provided a URL fragment at runtime, it will automatically expand and scroll to a specified tag or operation.
## Usage
👉🏼 Add `deepLinking: true` to your Swagger UI configuration to enable this functionality. This is demonstrated in [`dist/index.html`](https://github.com/swagger-api/swagger-ui/blob/master/dist/index.html).
When you expand a tag or operation, Swagger UI will automatically update its URL fragment with a deep link to the item.
Conversely, when you collapse a tag or operation, Swagger UI will clear the URL fragment.
You can also right-click a tag name or operation path to copy a link to that tag or operation.
#### Fragment format
The fragment is formatted in one of two ways:
- `#/{tagName}`, to trigger the focus of a specific tag
- `#/{tagName}/{operationId}`, to trigger the focus of a specific operation within a tag
`operationId` is the explicit operationId provided in the spec, if one exists.
Otherwise, Swagger UI generates an implicit operationId by combining the operation's path and method, while escaping non-alphanumeric characters.
## FAQ
> I'm using Swagger UI in an application that needs control of the URL fragment. How do I disable deep-linking?
This functionality is disabled by default, but you can pass `deepLinking: false` into Swagger UI as a configuration item to be sure.
> Can I link to multiple tags or operations?
No, this is not supported.
> Can I collapse everything except the operation or tag I'm linking to?
Sure - use `docExpansion: none` to collapse all tags and operations. Your deep link will take precedence over the setting, so only the tag or operation you've specified will be expanded.

View file

@ -0,0 +1,207 @@
# Installation
## Distribution channels
### NPM Registry
We publish three modules to npm: **`swagger-ui`**, **`swagger-ui-dist`** and **`swagger-ui-react`**.
**`swagger-ui`** is meant for consumption by JavaScript web projects that include module bundlers,
such as Webpack, Browserify, and Rollup. Its main file exports Swagger UI's main function,
and the module also includes a namespaced stylesheet at `swagger-ui/dist/swagger-ui.css`. Here's an example:
### Installation
You can now install SwaggerUI packages using `npm`:
```sh
$ npm install swagger-ui
````
```sh
$ npm install swagger-ui-react
````
```sh
$ npm install swagger-ui-dist
````
```javascript
import SwaggerUI from 'swagger-ui'
// or use require if you prefer
const SwaggerUI = require('swagger-ui')
SwaggerUI({
dom_id: '#myDomId'
})
```
See the [Webpack Getting Started](../samples/webpack-getting-started) sample for details.
In contrast, **`swagger-ui-dist`** is meant for server-side projects that need assets to serve to clients. The module, when imported, includes an `absolutePath` helper function that returns the absolute filesystem path to where the `swagger-ui-dist` module is installed.
_Note: we suggest using `swagger-ui` when your tooling makes it possible, as `swagger-ui-dist`
will result in more code going across the wire._
The module's contents mirror the `dist` folder you see in the Git repository. The most useful file is `swagger-ui-bundle.js`, which is a build of Swagger UI that includes all the code it needs to run in one file. The folder also has an `index.html` asset, to make it easy to serve Swagger UI like so:
```javascript
const express = require('express')
const pathToSwaggerUi = require('swagger-ui-dist').absolutePath()
const app = express()
app.use(express.static(pathToSwaggerUi))
app.listen(3000)
```
The module also exports `SwaggerUIBundle` and `SwaggerUIStandalonePreset`, so
if you're in a JavaScript project that can't handle a traditional npm module,
you could do something like this:
```js
var SwaggerUIBundle = require('swagger-ui-dist').SwaggerUIBundle
const ui = SwaggerUIBundle({
url: "https://petstore.swagger.io/v2/swagger.json",
dom_id: '#swagger-ui',
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIBundle.SwaggerUIStandalonePreset
],
layout: "StandaloneLayout"
})
```
`SwaggerUIBundle` is equivalent to `SwaggerUI`.
### Docker
You can pull a pre-built docker image of the swagger-ui directly from **docker.swagger.io**:
```sh
docker pull docker.swagger.io/swaggerapi/swagger-ui
docker run -p 80:8080 docker.swagger.io/swaggerapi/swagger-ui
```
Will start nginx with Swagger UI on port 80.
Or you can provide your own swagger.json on your host
```sh
docker run -p 80:8080 -e SWAGGER_JSON=/foo/swagger.json -v /bar:/foo docker.swagger.io/swaggerapi/swagger-ui
```
You can also provide a URL to a swagger.json on an external host:
```sh
docker run -p 80:8080 -e SWAGGER_JSON_URL=https://petstore3.swagger.io/api/v3/openapi.json docker.swagger.io/swaggerapi/swagger-ui
```
The base URL of the web application can be changed by specifying the `BASE_URL` environment variable:
```sh
docker run -p 80:8080 -e BASE_URL=/swagger -e SWAGGER_JSON=/foo/swagger.json -v /bar:/foo docker.swagger.io/swaggerapi/swagger-ui
```
This will serve Swagger UI at `/swagger` instead of `/`.
You can specify a different port via `PORT` variable for accessing the application, default is `8080`.
```sh
docker run -p 80:80 -e PORT=80 docker.swagger.io/swaggerapi/swagger-ui
```
You can specify an IPv6 port via `PORT_IPV6` variable. By default, IPv6 port is not set.
```sh
docker run -p 80:80 -e PORT_IPV6=8080 docker.swagger.io/swaggerapi/swagger-ui
```
You can allow/disallow [embedding](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options) via `EMBEDDING` variable. By default, embedding is disabled.
```sh
docker run -p 80:80 -e EMBEDDING=true docker.swagger.io/swaggerapi/swagger-ui
```
For more information on controlling Swagger UI through the Docker image, see the Docker section of the [Configuration documentation](configuration.md#docker).
### unpkg
You can embed Swagger UI's code directly in your HTML by using [unpkg's](https://unpkg.com/) interface:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="description" content="SwaggerUI" />
<title>SwaggerUI</title>
<link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist@5.11.0/swagger-ui.css" />
</head>
<body>
<div id="swagger-ui"></div>
<script src="https://unpkg.com/swagger-ui-dist@5.11.0/swagger-ui-bundle.js" crossorigin></script>
<script>
window.onload = () => {
window.ui = SwaggerUIBundle({
url: 'https://petstore3.swagger.io/api/v3/openapi.json',
dom_id: '#swagger-ui',
});
};
</script>
</body>
</html>
```
Using `StandalonePreset` will render `TopBar` and `ValidatorBadge` as well.
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="description" content="SwaggerUI" />
<title>SwaggerUI</title>
<link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist@5.11.0/swagger-ui.css" />
</head>
<body>
<div id="swagger-ui"></div>
<script src="https://unpkg.com/swagger-ui-dist@5.11.0/swagger-ui-bundle.js" crossorigin></script>
<script src="https://unpkg.com/swagger-ui-dist@5.11.0/swagger-ui-standalone-preset.js" crossorigin></script>
<script>
window.onload = () => {
window.ui = SwaggerUIBundle({
url: 'https://petstore3.swagger.io/api/v3/openapi.json',
dom_id: '#swagger-ui',
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
layout: "StandaloneLayout",
});
};
</script>
</body>
</html>
```
See [unpkg's main page](https://unpkg.com/) for more information on how to use unpkg.
### Static files without HTTP or HTML
Once swagger-ui has successfully generated the `/dist` directory, you can copy this to your own file system and host from there.
## Plain old HTML/CSS/JS (Standalone)
The folder `/dist` includes all the HTML, CSS and JS files needed to run SwaggerUI on a static website or CMS, without requiring NPM.
1. Download the [latest release](https://github.com/swagger-api/swagger-ui/releases/latest).
1. Copy the contents of the `/dist` folder to your server.
1. Open `swagger-initializer.js` in your text editor and replace "https://petstore.swagger.io/v2/swagger.json" with the URL for your OpenAPI 3.0 spec.

View file

@ -0,0 +1,38 @@
# Limitations
### Forbidden header names
Some header names cannot be controlled by web applications, due to security
features built into web browsers.
Forbidden headers include:
> - Accept-Charset
> - Accept-Encoding
> - Access-Control-Request-Headers
> - Access-Control-Request-Method
> - Connection
> - Content-Length
> - Cookie
> - Cookie2
> - Date
> - DNT
> - Expect
> - Host
> - Keep-Alive
> - Origin
> - Proxy-*
> - Sec-*
> - Referer
> - TE
> - Trailer
> - Transfer-Encoding
> - Upgrade
> - Via
>
> _[Forbidden header names (developer.mozilla.org)](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name)_
The biggest impact of this is that OpenAPI 3.0 Cookie parameters cannot be
controlled when running Swagger UI in a browser.
For more context, see [#3956](https://github.com/swagger-api/swagger-ui/issues/3956).

View file

@ -0,0 +1,31 @@
# OAuth 2.0 configuration
You can configure OAuth 2.0 authorization by calling the `initOAuth` method.
Property name | Docker variable | Description
--- | --- | ------
clientId | `OAUTH_CLIENT_ID` | Default clientId. MUST be a string
clientSecret | `OAUTH_CLIENT_SECRET` | **🚨 Never use this parameter in your production environment. It exposes crucial security information. This feature is intended for dev/test environments only. 🚨** <br>Default clientSecret. MUST be a string
realm | `OAUTH_REALM` |realm query parameter (for oauth1) added to `authorizationUrl` and `tokenUrl`. MUST be a string
appName | `OAUTH_APP_NAME` |application name, displayed in authorization popup. MUST be a string
scopeSeparator | `OAUTH_SCOPE_SEPARATOR` |scope separator for passing scopes, encoded before calling, default value is a space (encoded value `%20`). MUST be a string
scopes | `OAUTH_SCOPES` |string array or scope separator (i.e. space) separated string of initially selected oauth scopes, default is empty array
additionalQueryStringParams | `OAUTH_ADDITIONAL_PARAMS` |Additional query parameters added to `authorizationUrl` and `tokenUrl`. MUST be an object
useBasicAuthenticationWithAccessCodeGrant | `OAUTH_USE_BASIC_AUTH` |Only activated for the `accessCode` flow. During the `authorization_code` request to the `tokenUrl`, pass the [Client Password](https://tools.ietf.org/html/rfc6749#section-2.3.1) using the HTTP Basic Authentication scheme (`Authorization` header with `Basic base64encode(client_id + client_secret)`). The default is `false`
usePkceWithAuthorizationCodeGrant | `OAUTH_USE_PKCE` | Only applies to `Authorization Code` flows. [Proof Key for Code Exchange](https://tools.ietf.org/html/rfc7636) brings enhanced security for OAuth public clients. The default is `false` <br/><br/>_Note:_ This option does not hide the client secret input because [neither PKCE nor client secrets are replacements for each other](https://oauth.net/2/pkce/).
```javascript
const ui = SwaggerUI({...})
// Method can be called in any place after calling constructor SwaggerUIBundle
ui.initOAuth({
clientId: "your-client-id",
clientSecret: "your-client-secret-if-required",
realm: "your-realms",
appName: "your-app-name",
scopeSeparator: " ",
scopes: "openid profile",
additionalQueryStringParams: {test: "hello"},
useBasicAuthenticationWithAccessCodeGrant: true,
usePkceWithAuthorizationCodeGrant: true
})
```

View file

@ -0,0 +1,54 @@
# Detecting your Swagger UI version
At times, you're going to need to know which version of Swagger UI you use.
The first step would be to detect which major version you currently use, as the method of detecting the version has changed. If your Swagger UI has been heavily modified and you cannot detect from the look and feel which major version you use, you'd have to try both methods to get the exact version.
To help you visually detect which version you're using, we've included supporting images.
# Swagger UI 3.x
![Swagger UI 3](/docs/images/swagger-ui3.png)
Some distinct identifiers to Swagger UI 3.x:
- The API version appears as a badge next to its title.
- If there are schemes or authorizations, they'd appear in a bar above the operations.
- Try it out functionality is not enabled by default.
- All the response codes in the operations appear at after the parameters.
- There's a models section after the operations.
If you've determined this is the version you have, to find the exact version:
- Open your browser's web console (changes between browsers)
- Type `JSON.stringify(versions)` in the console and execute the call.
- The result should look similar to `swaggerUi : Object { version: "3.1.6", gitRevision: "g786cd47", gitDirty: true, … }`.
- The version taken from that example would be `3.1.6`.
Note: This functionality was added in 3.0.8. If you're unable to execute it, you're likely to use an older version, and in that case the first step would be to upgrade.
# Swagger UI 2.x and under
![Swagger UI 2](/docs/images/swagger-ui2.png)
Some distinct identifiers to Swagger UI 2.x:
- The API version appears at the bottom of the page.
- Schemes are not rendered.
- Authorization, if rendered, will appear next to the navigation bar.
- Try it out functionality is enabled by default.
- The successful response code would appear above the parameters, the rest below them.
- There's no models section after the operations.
If you've determined this is the version you have, to find the exact version:
- Navigate to the sources of the UI. Either on your disk or via the view page source functionality in your browser.
- Find an open the `swagger-ui.js`
- At the top of the page, there would be a comment containing the exact version of Swagger UI. This example shows version `2.2.9`:
```
/**
* swagger-ui - Swagger UI is a dependency-free collection of HTML, JavaScript, and CSS assets that dynamically generate beautiful documentation from a Swagger-compliant API
* @version v2.2.9
* @link https://swagger.io
* @license Apache-2.0
*/
```

56
plugin/API/index.php Normal file
View file

@ -0,0 +1,56 @@
<?php
use OpenApi\Attributes as OA;
$configFile = __DIR__ . '/../../videos/configuration.php';
require_once $configFile;
$APISecret = '';
if (User::isAdmin()) {
$dataObj = AVideoPlugin::getDataObject('API');
//$APISecret = $dataObj->APISecret;
}
?>
<!-- HTML for static distribution bundle build -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Swagger UI</title>
<link rel="stylesheet" type="text/css" href="./docs/swagger-ui.css" />
<link rel="stylesheet" type="text/css" href="./docs/index.css" />
<link rel="stylesheet" type="text/css" href="./swagger.css" />
</head>
<body>
<div id="swagger-ui"></div>
<script src="./docs/swagger-ui-bundle.js" charset="UTF-8"> </script>
<script src="./docs/swagger-ui-standalone-preset.js" charset="UTF-8"> </script>
<script src="./docs/swagger-initializer.js?2" charset="UTF-8"> </script>
<script>
window.onload = function() {
window.ui = SwaggerUIBundle({
url: "./swagger.json.php",
dom_id: '#swagger-ui',
deepLinking: true,
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
],
layout: "StandaloneLayout",
tagsSorter: "alpha",
operationsSorter: (a, b) => {
return a.get("path").localeCompare(b.get("path"));
}
});
};
</script>
</body>
</html>

View file

@ -14,29 +14,13 @@ if (empty($plugin)) {
}
$obj = AVideoPlugin::getObjectData("API");
$resp = getSystemAPIs();
$methodsList = $resp['methodsList'];
$methodsList = array();
$reflector = new ReflectionClass('API');
$class_methods = get_class_methods('API');
foreach ($class_methods as $key => $method[0]) {
if (preg_match("/(get|set)_api_(.*)/", $method[0], $matches)) {
$methodsList[] = array($method[0], $reflector, $matches[1], $matches[2], '');
}
}
$plugins = Plugin::getAllEnabled();
foreach ($plugins as $value) {
$p = AVideoPlugin::loadPlugin($value['dirName']);
if (class_exists($value['dirName'])) {
$class_methods = get_class_methods($value['dirName']);
$reflector = new ReflectionClass($value['dirName']);
foreach ($class_methods as $key => $method[0]) {
if (preg_match("/API_(get|set)_(.*)/", $method[0], $matches)) {
$methodsList[] = array($method[0], $reflector, $matches[1], $matches[2], $value['dirName']);
}
}
}
if (!empty($_REQUEST['json'])) {
header('Content-Type: application/json');
echo json_encode($resp['response']);
exit;
}
$_page = new Page(array('API'));
@ -118,4 +102,4 @@ $_page = new Page(array('API'));
</div>
<?php
$_page->print();
?>
?>

192
plugin/API/router.php Normal file
View file

@ -0,0 +1,192 @@
<?php
if (empty($_REQUEST['APISecret'])) {
$_REQUEST['APISecret'] = getBearerToken();
}
//redirectIfPortOpen(3000);
$requestUri = $_SERVER['REQUEST_URI'];
$method = $_SERVER['REQUEST_METHOD'];
//error_log('APISecret: ' . json_encode($_REQUEST['APISecret']));
// Remove query string
$uri = parse_url($requestUri, PHP_URL_PATH);
// Extrai o valor após /api/
$matches = [];
if (preg_match('#^/api/([^/]+)#', $uri, $matches)) {
$apiName = $matches[1];
switch ($method) {
case 'GET':
include __DIR__ . "/get.json.php";
break;
case 'POST':
case 'DELETE':
include __DIR__ . "/set.json.php";
break;
default:
http_response_code(405);
echo json_encode(["error" => "Method Not Allowed"]);
break;
}
} else {
http_response_code(404);
echo json_encode(["error" => "Not Found"]);
}
function redirectIfPortOpen($newPort, $timeout = 1)
{
$host = $_SERVER['SERVER_NAME'];
$currentPort = $_SERVER['SERVER_PORT'];
$targetHost = $host;
$targetPort = (int)$newPort;
if ($currentPort == $targetPort) {
error_log("🔄 Current port is already target port ($targetPort), skipping redirect.");
return;
}
$connection = @fsockopen($targetHost, $targetPort, $errno, $errstr, $timeout);
if (!$connection) {
error_log("❌ Port $targetPort is not open or connection failed: $errstr ($errno)");
return;
}
fclose($connection);
$scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https" : "http";
$uri = $_SERVER['REQUEST_URI'];
$url = "{$scheme}://{$targetHost}:{$targetPort}{$uri}";
error_log("🔁 Redirecting to: $url");
// Get headers using getallheaders() if available
$headers = function_exists('getallheaders') ? getallheaders() : [];
if (empty($headers)) {
error_log("⚠️ getallheaders() returned empty. Building manually from \$_SERVER.");
foreach ($_SERVER as $key => $value) {
if (stripos($key, 'HTTP_') === 0) {
$headerName = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($key, 5)))));
$headers[$headerName] = $value;
}
}
}
// Fallback: Check for authorization header explicitly in $_SERVER
if (empty($headers['Authorization'])) {
if (!empty($_SERVER['HTTP_AUTHORIZATION'])) {
$headers['Authorization'] = $_SERVER['HTTP_AUTHORIZATION'];
error_log("🔐 Fallback: Found HTTP_AUTHORIZATION in \$_SERVER: " . $_SERVER['HTTP_AUTHORIZATION']);
} elseif (!empty($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) {
$headers['Authorization'] = $_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
error_log("🔐 Fallback: Found REDIRECT_HTTP_AUTHORIZATION in \$_SERVER: " . $_SERVER['REDIRECT_HTTP_AUTHORIZATION']);
} else {
// Attempt getBearerToken() as last resort.
$bearerToken = getBearerToken();
if ($bearerToken) {
$headers['Authorization'] = "Bearer {$bearerToken}";
error_log("🔐 Fallback: Retrieved token via getBearerToken(): Bearer {$bearerToken}");
}
}
}
error_log("📦 Forwarding headers:");
foreach ($headers as $key => $value) {
error_log("➡️ $key: $value");
}
$method = $_SERVER['REQUEST_METHOD'];
$body = file_get_contents('php://input');
if (!empty($body)) {
error_log("📝 Request body content: $body");
}
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
$curlHeaders = [];
foreach ($headers as $key => $value) {
$curlHeaders[] = "$key: $value";
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $curlHeaders);
$response = curl_exec($ch);
if ($response === false) {
error_log("❌ cURL error: " . curl_error($ch));
http_response_code(500);
echo "Internal cURL error: " . curl_error($ch);
exit;
}
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
curl_close($ch);
error_log("✅ Response received. HTTP Code: $httpCode {$url}");
$headerContent = substr($response, 0, $headerSize);
$bodyContent = substr($response, $headerSize);
foreach (explode("\r\n", $headerContent) as $headerLine) {
if (stripos($headerLine, 'Transfer-Encoding:') === 0) continue;
if (stripos($headerLine, 'Content-Length:') === 0) continue;
if (!empty($headerLine) && stripos($headerLine, 'HTTP/') !== 0) {
header($headerLine, true);
}
}
http_response_code($httpCode);
echo $bodyContent;
exit;
}
function getBearerToken()
{
$headers = [];
// 1. Try apache_request_headers() if available
if (function_exists('apache_request_headers')) {
$headers = apache_request_headers();
}
// 2. If still empty, try getallheaders()
if (empty($headers) && function_exists('getallheaders')) {
$headers = getallheaders();
}
// 3. If still empty, manually build headers from $_SERVER
if (empty($headers)) {
foreach ($_SERVER as $key => $value) {
if (stripos($key, 'HTTP_') === 0) {
// Convert HTTP_HEADER_NAME to Header-Name
$headerName = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($key, 5)))));
$headers[$headerName] = $value;
}
}
}
// 4. Normalize and extract Authorization header
foreach ($headers as $name => $value) {
if (strcasecmp($name, 'Authorization') === 0 && preg_match('/Bearer\s(\S+)/', $value, $matches)) {
return $matches[1]; // Return the token
}
}
// 5. Final fallback: check $_SERVER directly
if (isset($_SERVER['HTTP_AUTHORIZATION']) && preg_match('/Bearer\s(\S+)/', $_SERVER['HTTP_AUTHORIZATION'], $matches)) {
return $matches[1];
}
if (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION']) && preg_match('/Bearer\s(\S+)/', $_SERVER['REDIRECT_HTTP_AUTHORIZATION'], $matches)) {
return $matches[1];
}
return null; // Token not found
}

3
plugin/API/swagger.css Normal file
View file

@ -0,0 +1,3 @@
#swagger-ui .topbar, #swagger-ui .information-container{
display: none !important;
}

View file

@ -0,0 +1,28 @@
<?php
//$doNotConnectDatabaseIncludeConfig = 1;
$doNotStartSessionIncludeConfig = 1;
$configFile = __DIR__ . '/../../videos/configuration.php';
require_once $configFile;
use OpenApi\Generator;
$plugins = Plugin::getAllEnabled();
$sources = array();
// Sort plugins alphabetically by dirName
usort($plugins, function ($a, $b) {
return strcmp($a['dirName'], $b['dirName']);
});
foreach ($plugins as $value) {
$p = AVideoPlugin::loadPlugin($value['dirName']);
if (class_exists($value['dirName'])) {
$sources[] = "{$global['systemRootPath']}plugin/{$value['dirName']}/{$value['dirName']}.php";
}
}
$openapi = Generator::scan($sources);
header('Content-Type: application/json');
echo $openapi->toJson();

View file

@ -348,7 +348,7 @@ class CachesInDB extends ObjectYPT
$_deleteCacheStartingWithList = array();
}
if(!empty($_deleteCacheStartingWithList[$name])){
_error_log("CachesInDB::_deleteCacheStartingWith($name) error line=".__LINE__);
//_error_log("CachesInDB::_deleteCacheStartingWith($name) error line=".__LINE__);
return false;
}
$_deleteCacheStartingWithList[$name] = time();

View file

@ -1,5 +1,5 @@
<?php
use OpenApi\Attributes as OA;
require_once $global['systemRootPath'] . 'plugin/Plugin.abstract.php';
require_once $global['systemRootPath'] . 'plugin/AVideoPlugin.php';
require_once $global['systemRootPath'] . 'objects/Channel.php';
@ -79,8 +79,8 @@ class Gallery extends PluginAbstract
$o = new stdClass();
$o->type = [
Gallery::BigVideoLiveDisabled => 'Disable',
Gallery::BigVideoLiveShowLiveAndVOD => 'Show Live and VOD',
Gallery::BigVideoLiveDisabled => 'Disable',
Gallery::BigVideoLiveShowLiveAndVOD => 'Show Live and VOD',
Gallery::BigVideoLiveShowLiveOnly => 'Show Live Only'
];
$o->value = Gallery::BigVideoLiveShowLiveAndVOD;
@ -90,7 +90,7 @@ class Gallery extends PluginAbstract
self::addDataObjectHelper('BigVideoLiveOnFirstPageOnly', 'Big Video Live on First Page Only');
$obj->BigVideoLiveForLoggedUsersOnly = false;
self::addDataObjectHelper('BigVideoLiveForLoggedUsersOnly', 'Big Video Live will appear only if the user is logged');
$obj->useSuggestedVideosAsCarouselInBigVideo = true;
$obj->GifOnBigVideo = true;
$obj->Description = false;
@ -358,6 +358,58 @@ class Gallery extends PluginAbstract
* @example {webSiteRootURL}plugin/API/{getOrSet}.json.php?APIPlugin={APIPlugin}&APIName={APIName}
* @return \ApiObject
*/
#[OA\Get(
path: "/api/Gallery/firstPage",
summary: 'Get the homepage configuration and video list endpoints',
description: 'Returns homepage sections, each with an endpoint to retrieve a video list. Sections include Suggested, Trending, Shorts, Date Added, etc.',
tags: ['Gallery'],
security: [['APISecret' => []]],
responses: [
new OA\Response(
response: 200,
description: 'Successful response with the first page configuration and endpoints',
content: new OA\JsonContent(
type: 'object',
properties: [
new OA\Property(
property: 'error',
type: 'boolean',
example: false
),
new OA\Property(
property: 'msg',
type: 'string',
example: ''
),
new OA\Property(
property: 'response',
type: 'object',
properties: [
new OA\Property(
property: 'sections',
type: 'array',
items: new OA\Items(
type: 'object',
properties: [
new OA\Property(property: 'name', type: 'string'),
new OA\Property(property: 'title', type: 'string'),
new OA\Property(property: 'endpoint', type: 'string'),
new OA\Property(property: 'totalRows', type: 'integer')
]
)
),
new OA\Property(property: 'countSections', type: 'integer', example: 5),
new OA\Property(property: 'countVideos', type: 'integer', example: 25),
new OA\Property(property: 'responseTime', type: 'number', format: 'float', example: 0.123),
new OA\Property(property: 'responseCacheTime', type: 'number', format: 'float', example: 0.002)
]
)
]
)
)
]
)]
static function API_get_firstPage($parameters){
global $global;
$start = microtime(true);
@ -385,7 +437,7 @@ class Gallery extends PluginAbstract
$response->sections[] = $section;
} else
if ($value['name'] == 'Suggested') {
$title = !empty($obj->SuggestedCustomTitle) ? $obj->SuggestedCustomTitle : __("Suggested");
$rowCount = intval($obj->SuggestedRowCount);
$endpoint = "{$global['webSiteRootURL']}plugin/API/get.json.php?APIName=video&sort[suggested]=1";
@ -494,19 +546,19 @@ class Gallery extends PluginAbstract
}
$response->countVideos = $countVideos;
$response->countSections = $countSections;
$finish = microtime(true)-$start;
$response->responseTime = $finish;
$object = new ApiObject("", false, $response);
ObjectYPT::setCache($cacheName, $object);
}else{
$finish = microtime(true)-$start;
$object->response->responseCacheTime = $finish;
}
return $object;
}
}

View file

@ -1,7 +1,7 @@
<?php
require_once $global['systemRootPath'] . 'locale/function.php';
require_once $global['systemRootPath'] . 'objects/plugin.php';
require_once __DIR__ . '/../locale/function.php';
require_once __DIR__ . '/../objects/plugin.php';
abstract class PluginAbstract {
@ -42,10 +42,10 @@ abstract class PluginAbstract {
$dir = $global['systemRootPath'] . "plugin/{$pluginName}/install/";
//var_dump($dir);exit;
if(is_dir($dir)){
$files = scandir($dir);
$files = scandir($dir);
$versions = [];
foreach ($files as $file) {
if (preg_match($pattern, $file, $matches)) {
$versions[] = [
@ -54,12 +54,12 @@ abstract class PluginAbstract {
];
}
}
// Sort by version (optional)
usort($versions, function ($a, $b) {
return version_compare($a['version'], $b['version']);
});
// Iterate through sorted files
foreach ($versions as $entry) {
//var_dump($pluginName, $entry['version'], AVideoPlugin::compareVersion($pluginName, $entry['version']) < 0);
@ -82,10 +82,10 @@ abstract class PluginAbstract {
}
}
}
$files = scandir($dir);
$files = scandir($dir);
$versions = [];
foreach ($files as $file) {
if (preg_match($pattern, $file, $matches)) {
$versions[] = [
@ -94,12 +94,12 @@ abstract class PluginAbstract {
];
}
}
// Sort by version (optional)
usort($versions, function ($a, $b) {
return version_compare($a['version'], $b['version']);
});
// Iterate through sorted files
foreach ($versions as $entry) {
if (AVideoPlugin::compareVersion($pluginName, $entry['version']) < 0) {
@ -113,8 +113,8 @@ abstract class PluginAbstract {
}
}
}
return true;
return true;
}
public function getFooterCode() {
@ -192,7 +192,7 @@ abstract class PluginAbstract {
public function getDataObject() {
$uuid = $this->getUUID();
if (empty(PluginAbstract::$dataObject[$uuid])) {
if (empty(PluginAbstract::$dataObject[$uuid]) && class_exists('Plugin')) {
$obj = Plugin::getPluginByUUID($uuid);
//echo $obj['object_data'];
$o = self::getObjectDataFromDatabase($uuid);
@ -445,7 +445,7 @@ abstract class PluginAbstract {
}
/**
*
*
* @return string array(array("key"=>'live key', "users"=>false, "name"=>$userName, "user"=>$user, "photo"=>$photo, "UserPhoto"=>$UserPhoto, "title"=>''));
*/
public function getLiveApplicationArray() {
@ -494,7 +494,7 @@ abstract class PluginAbstract {
}
/**
*
*
* @return string return a list of IDs of the user groups
*/
public function getDynamicUserGroupsId($users_id) {
@ -554,7 +554,7 @@ abstract class PluginAbstract {
foreach ($ready['error'] as $value) {
$desc .= "<span class='btn btn-warning btn-sm btn-xs'><i class='fa fa-exclamation-triangle'></i> {$value['name']} plugin Not Found</span> ";
}
return $desc;
}
@ -564,16 +564,16 @@ abstract class PluginAbstract {
}
/**
*
*
* @param string $users_id
* @return 0 = I dont know, -1 = can not upload, 1 = can upload
*/
public function userCanUpload($users_id) {
return 0;
}
/**
*
*
* @param string $users_id
* @return 0 = I dont know, -1 = can not upload, 1 = can upload
*/
@ -582,7 +582,7 @@ abstract class PluginAbstract {
}
/**
*
*
* @param string $users_id
* @param string $videos_id
* @return 0 = I dont know, -1 = can not watch, 1 = can watch
@ -592,7 +592,7 @@ abstract class PluginAbstract {
}
/**
*
*
* @param string $users_id
* @param string $videos_id
* @return 0 = I dont know, -1 = can not watch, 1 = can watch
@ -722,147 +722,147 @@ abstract class PluginAbstract {
}
function onUserSocketConnect() {
}
function onUserSocketDisconnect() {
}
function onVideoSetLive_transmitions_history_id($video_id, $oldValue, $newValue) {
}
function onVideoSetEncoderURL($video_id, $oldValue, $newValue) {
}
function onVideoSetFilepath($video_id, $oldValue, $newValue) {
}
function onVideoSetUsers_id($video_id, $oldValue, $newValue) {
}
function onVideoSetSites_id($video_id, $oldValue, $newValue) {
}
function onVideoSetVideo_password($video_id, $oldValue, $newValue) {
}
function onVideoSetClean_title($video_id, $oldValue, $newValue) {
}
function onVideoSetDuration($video_id, $oldValue, $newValue) {
}
function onVideoSetIsSuggested($video_id, $oldValue, $newValue) {
}
function onVideoSetStatus($video_id, $oldValue, $newValue) {
}
function onVideoSetType($video_id, $oldValue, $newValue, $force) {
}
function onVideoSetRotation($video_id, $oldValue, $newValue) {
}
function onVideoSetZoom($video_id, $oldValue, $newValue) {
}
function onVideoSetDescription($video_id, $oldValue, $newValue) {
}
function onVideoSetCategories_id($video_id, $oldValue, $newValue) {
}
function onVideoSetVideoDownloadedLink($video_id, $oldValue, $newValue) {
}
function onVideoSetVideoGroups($video_id, $oldValue, $newValue) {
}
function onVideoSetTrailer1(Video &$videoObj, $newValue) {
}
function onVideoSetTrailer2(Video &$videoObj, $newValue) {
}
function onVideoSetTrailer3(Video &$videoObj, $newValue) {
}
function onVideoSetRate($video_id, $oldValue, $newValue) {
}
function onVideoSetYoutubeId($video_id, $oldValue, $newValue) {
}
function onVideoSetTitle($video_id, $oldValue, $newValue) {
}
function onVideoSetFilename($video_id, $oldValue, $newValue, $force) {
}
function onVideoSetNext_videos_id($video_id, $oldValue, $newValue) {
}
function onVideoSetVideoLink($video_id, $oldValue, $newValue) {
}
function onVideoSetCan_download($video_id, $oldValue, $newValue) {
}
function onVideoSetCan_share($video_id, $oldValue, $newValue) {
}
function onVideoSetOnly_for_paid($video_id, $oldValue, $newValue) {
}
function onVideoSetRrating($video_id, $oldValue, $newValue) {
}
function executeEveryMinute() {
}
function executeEveryHour() {
}
function executeEveryDay() {
}
function executeEveryMonth() {
}
/**
@ -881,15 +881,15 @@ abstract class PluginAbstract {
}
function onVideoSetExternalOptions($video_id, $oldValue, $newValue) {
}
function onVideoSetVideoStartSeconds($video_id, $oldValue, $newValue) {
}
function onVideoSetSerie_playlists_id($video_id, $oldValue, $newValue) {
}
function getMobileHomePageURL() {
@ -914,11 +914,11 @@ abstract class PluginAbstract {
public function getWalletConfigurationHTML($users_id, $wallet, $walletDataObject) {
return "";
}
function canRecordVideo($key) {
return true;
}
function canNotifyVideo($key) {
return true;
}

View file

@ -5,7 +5,9 @@ use function Safe\ob_end_flush;
require_once dirname(__FILE__) . '/../../videos/configuration.php';
require_once $global['systemRootPath'] . 'plugin/YPTSocket/functions.php';
ob_end_flush();
if (ob_get_level() > 0) {
ob_end_flush();
}
// 🔒 Força modo bloqueante para aguardar dados no STDIN
$stdin = fopen("php://stdin", "r");
@ -18,6 +20,12 @@ echo json_encode([
"response" => null
]) . PHP_EOL;
global $SystemAPIs;
if (empty($SystemAPIs)) {
$SystemAPIs = getSystemAPIs();
$SystemPluginsAPIs = $SystemAPIs['plugins'];
}
while (true) {
// Lê a linha do STDIN (bloqueia até que algo chegue)
$input = fgets($stdin);
@ -30,6 +38,8 @@ while (true) {
$input = trim($input);
//fwrite(STDERR, "📥 INPUT: {$input}\n");
// Se receber "exit", finaliza o loop
if ($input === "exit") {
echo json_encode([
@ -51,11 +61,15 @@ while (true) {
]) . PHP_EOL;
continue;
}
if(!empty($data['headers']) && !empty($data['headers']['Authorization'])){
if(preg_match('/Bearer\s(\S+)/', $data['headers']['Authorization'], $matches)) {
$_REQUEST['APISecret'] = $matches[1];
}
}
//fwrite(STDERR, "📥 INPUT: {$input} ".json_encode($_REQUEST).PHP_EOL);
$result = null;
$error = false;
$msg = "";
// Tenta executar a ação solicitada
try {
switch ($data["action"]) {
@ -91,6 +105,30 @@ while (true) {
case "getDecryptedInfo":
$result = getDecryptedInfo($data["token"]);
break;
case "APIList":
$result = $SystemPluginsAPIs;
break;
case "API":
$plugin = $data["plugin"];
$method = $data["method"];
$params = $data["params"];
if (empty($SystemPluginsAPIs[$plugin])) {
$error = true;
$msg = "Invalid plugin";
} else if (empty($SystemPluginsAPIs[$plugin][$method])) {
$error = true;
$msg = "Invalid method";
} else {
$p = AVideoPlugin::loadPluginIfEnabled($plugin);
if ($p) {
$exec = "try {\$result = \$p->{$method}({$params}); } catch (\Throwable \$th) {\$error = true;\$msg = \$th->getMessage();}";
eval($exec);
}
unset($p);
}
break;
default:
$error = true;
@ -106,10 +144,13 @@ while (true) {
"id" => $data["id"],
"error" => $error,
"msg" => $msg,
"response" => $result
"response" => $result,
"headers" => $data["headers"]
]) . PHP_EOL;
echo $response;
$_REQUEST['APISecret'] = null;
//fwrite(STDERR, "📤 OUTPUT: {$response}\n");
flush();
}

View file

@ -1,5 +1,5 @@
<?php
use OpenApi\Attributes as OA;
require_once $global['systemRootPath'] . 'plugin/Plugin.abstract.php';
require_once $global['systemRootPath'] . 'plugin/AVideoPlugin.php';
class YouPHPFlix2 extends PluginAbstract
@ -171,6 +171,58 @@ class YouPHPFlix2 extends PluginAbstract
* @example {webSiteRootURL}plugin/API/{getOrSet}.json.php?APIPlugin={APIPlugin}&APIName={APIName}
* @return \ApiObject
*/
#[OA\Get(
path: "/api/YouPHPFlix2/firstPage",
summary: 'Get homepage sections and their corresponding video list endpoints',
description: 'Returns configuration for the first page from the YouPHPFlix2 plugin, including sections like Suggested, Trending, Channels, Playlists, etc. Each section includes an endpoint to fetch related videos.',
tags: ['YouPHPFlix2'],
security: [['APISecret' => []]],
responses: [
new OA\Response(
response: 200,
description: 'Returns a list of sections for the homepage, each with a video list endpoint',
content: new OA\JsonContent(
type: 'object',
properties: [
new OA\Property(
property: 'error',
type: 'boolean',
example: false
),
new OA\Property(
property: 'msg',
type: 'string',
example: ''
),
new OA\Property(
property: 'response',
type: 'object',
properties: [
new OA\Property(
property: 'sections',
type: 'array',
items: new OA\Items(
type: 'object',
properties: [
new OA\Property(property: 'name', type: 'string', example: 'Suggested'),
new OA\Property(property: 'title', type: 'string', example: 'Suggested Videos'),
new OA\Property(property: 'endpoint', type: 'string', example: 'https://yourdomain.com/plugin/API/get.json.php?APIName=video&sort[suggested]=1'),
new OA\Property(property: 'totalRows', type: 'integer', example: 20)
]
)
),
new OA\Property(property: 'countSections', type: 'integer', example: 6),
new OA\Property(property: 'countVideos', type: 'integer', example: 120),
new OA\Property(property: 'responseTime', type: 'number', format: 'float', example: 0.201),
new OA\Property(property: 'responseCacheTime', type: 'number', format: 'float', nullable: true)
]
)
]
)
)
]
)]
static function API_get_firstPage($parameters)
{
global $global;
@ -302,7 +354,7 @@ class YouPHPFlix2 extends PluginAbstract
return $object;
}
public static function getAddChannelToYouPHPFlix2Button($users_id)
{
global $global, $config;

117
vendor/bin/openapi vendored Normal file
View file

@ -0,0 +1,117 @@
#!/usr/bin/env php
<?php
/**
* Proxy PHP file generated by Composer
*
* This file includes the referenced bin path (../zircote/swagger-php/bin/openapi)
* using a stream wrapper to prevent the shebang from being output on PHP<8
*
* @generated
*/
namespace Composer;
$GLOBALS['_composer_bin_dir'] = __DIR__;
$GLOBALS['_composer_autoload_path'] = __DIR__ . '/..'.'/autoload.php';
if (PHP_VERSION_ID < 80000) {
if (!class_exists('Composer\BinProxyWrapper')) {
/**
* @internal
*/
final class BinProxyWrapper
{
private $handle;
private $position;
private $realpath;
public function stream_open($path, $mode, $options, &$opened_path)
{
// get rid of phpvfscomposer:// prefix for __FILE__ & __DIR__ resolution
$opened_path = substr($path, 17);
$this->realpath = realpath($opened_path) ?: $opened_path;
$opened_path = $this->realpath;
$this->handle = fopen($this->realpath, $mode);
$this->position = 0;
return (bool) $this->handle;
}
public function stream_read($count)
{
$data = fread($this->handle, $count);
if ($this->position === 0) {
$data = preg_replace('{^#!.*\r?\n}', '', $data);
}
$this->position += strlen($data);
return $data;
}
public function stream_cast($castAs)
{
return $this->handle;
}
public function stream_close()
{
fclose($this->handle);
}
public function stream_lock($operation)
{
return $operation ? flock($this->handle, $operation) : true;
}
public function stream_seek($offset, $whence)
{
if (0 === fseek($this->handle, $offset, $whence)) {
$this->position = ftell($this->handle);
return true;
}
return false;
}
public function stream_tell()
{
return $this->position;
}
public function stream_eof()
{
return feof($this->handle);
}
public function stream_stat()
{
return array();
}
public function stream_set_option($option, $arg1, $arg2)
{
return true;
}
public function url_stat($path, $flags)
{
$path = substr($path, 17);
if (file_exists($path)) {
return stat($path);
}
return false;
}
}
}
if (function_exists('stream_wrapper_register') && stream_wrapper_register('phpvfscomposer', 'Composer\BinProxyWrapper')) {
include("phpvfscomposer://" . __DIR__ . '/..'.'/zircote/swagger-php/bin/openapi');
exit(0);
}
}
include __DIR__ . '/..'.'/zircote/swagger-php/bin/openapi';

5
vendor/bin/openapi.bat vendored Normal file
View file

@ -0,0 +1,5 @@
@ECHO OFF
setlocal DISABLEDELAYEDEXPANSION
SET BIN_TARGET=%~dp0/openapi
SET COMPOSER_RUNTIME_BIN_DIR=%~dp0
php "%BIN_TARGET%" %*

View file

@ -13,8 +13,8 @@ return array(
'ad155f8f1cf0d418fe49e248db8c661b' => $vendorDir . '/react/promise/src/functions_include.php',
'37a3dc5111fe8f707ab4c132ef1dbc62' => $vendorDir . '/guzzlehttp/guzzle/src/functions_include.php',
'e69f7f6ee287b969198c3c9d6777bd38' => $vendorDir . '/symfony/polyfill-intl-normalizer/bootstrap.php',
'0d59ee240a4cd96ddbb4ff164fccea4d' => $vendorDir . '/symfony/polyfill-php73/bootstrap.php',
'320cde22f66dd4f5d3fd621d3e88b98f' => $vendorDir . '/symfony/polyfill-ctype/bootstrap.php',
'0d59ee240a4cd96ddbb4ff164fccea4d' => $vendorDir . '/symfony/polyfill-php73/bootstrap.php',
'8825ede83f2f289127722d4e842cf7e8' => $vendorDir . '/symfony/polyfill-intl-grapheme/bootstrap.php',
'23c18046f52bef3eea034657bafda50f' => $vendorDir . '/symfony/polyfill-php81/bootstrap.php',
'a1105708a18b76903365ca1c4aa61b02' => $vendorDir . '/symfony/translation/Resources/functions.php',

View file

@ -24,12 +24,14 @@ return array(
'Symfony\\Contracts\\Service\\' => array($vendorDir . '/symfony/service-contracts'),
'Symfony\\Contracts\\HttpClient\\' => array($vendorDir . '/symfony/http-client-contracts'),
'Symfony\\Contracts\\EventDispatcher\\' => array($vendorDir . '/symfony/event-dispatcher-contracts'),
'Symfony\\Component\\Yaml\\' => array($vendorDir . '/symfony/yaml'),
'Symfony\\Component\\Translation\\' => array($vendorDir . '/symfony/translation'),
'Symfony\\Component\\String\\' => array($vendorDir . '/symfony/string'),
'Symfony\\Component\\OptionsResolver\\' => array($vendorDir . '/symfony/options-resolver'),
'Symfony\\Component\\Mime\\' => array($vendorDir . '/symfony/mime'),
'Symfony\\Component\\HttpFoundation\\' => array($vendorDir . '/symfony/http-foundation'),
'Symfony\\Component\\HttpClient\\' => array($vendorDir . '/symfony/http-client'),
'Symfony\\Component\\Finder\\' => array($vendorDir . '/symfony/finder'),
'Symfony\\Component\\EventDispatcher\\' => array($vendorDir . '/symfony/event-dispatcher'),
'Symfony\\Component\\Console\\' => array($vendorDir . '/symfony/console'),
'Stripe\\' => array($vendorDir . '/stripe/stripe-php/lib'),
@ -59,6 +61,7 @@ return array(
'PayPalCheckoutSdk\\' => array($vendorDir . '/paypal/paypal-checkout-sdk/lib/PayPalCheckoutSdk'),
'ParagonIE\\ConstantTime\\' => array($vendorDir . '/paragonie/constant_time_encoding/src'),
'PHPMailer\\PHPMailer\\' => array($vendorDir . '/phpmailer/phpmailer/src'),
'OpenApi\\' => array($vendorDir . '/zircote/swagger-php/src'),
'OneSignal\\' => array($vendorDir . '/norkunas/onesignal-php-api/src'),
'OTPHP\\' => array($vendorDir . '/spomky-labs/otphp/src'),
'Monolog\\' => array($vendorDir . '/monolog/monolog/src/Monolog'),

View file

@ -14,8 +14,8 @@ class ComposerStaticInitc3a61dba26daada128f5891f1a57c504
'ad155f8f1cf0d418fe49e248db8c661b' => __DIR__ . '/..' . '/react/promise/src/functions_include.php',
'37a3dc5111fe8f707ab4c132ef1dbc62' => __DIR__ . '/..' . '/guzzlehttp/guzzle/src/functions_include.php',
'e69f7f6ee287b969198c3c9d6777bd38' => __DIR__ . '/..' . '/symfony/polyfill-intl-normalizer/bootstrap.php',
'0d59ee240a4cd96ddbb4ff164fccea4d' => __DIR__ . '/..' . '/symfony/polyfill-php73/bootstrap.php',
'320cde22f66dd4f5d3fd621d3e88b98f' => __DIR__ . '/..' . '/symfony/polyfill-ctype/bootstrap.php',
'0d59ee240a4cd96ddbb4ff164fccea4d' => __DIR__ . '/..' . '/symfony/polyfill-php73/bootstrap.php',
'8825ede83f2f289127722d4e842cf7e8' => __DIR__ . '/..' . '/symfony/polyfill-intl-grapheme/bootstrap.php',
'23c18046f52bef3eea034657bafda50f' => __DIR__ . '/..' . '/symfony/polyfill-php81/bootstrap.php',
'a1105708a18b76903365ca1c4aa61b02' => __DIR__ . '/..' . '/symfony/translation/Resources/functions.php',
@ -162,12 +162,14 @@ class ComposerStaticInitc3a61dba26daada128f5891f1a57c504
'Symfony\\Contracts\\Service\\' => 26,
'Symfony\\Contracts\\HttpClient\\' => 29,
'Symfony\\Contracts\\EventDispatcher\\' => 34,
'Symfony\\Component\\Yaml\\' => 23,
'Symfony\\Component\\Translation\\' => 30,
'Symfony\\Component\\String\\' => 25,
'Symfony\\Component\\OptionsResolver\\' => 34,
'Symfony\\Component\\Mime\\' => 23,
'Symfony\\Component\\HttpFoundation\\' => 33,
'Symfony\\Component\\HttpClient\\' => 29,
'Symfony\\Component\\Finder\\' => 25,
'Symfony\\Component\\EventDispatcher\\' => 34,
'Symfony\\Component\\Console\\' => 26,
'Stripe\\' => 7,
@ -206,6 +208,7 @@ class ComposerStaticInitc3a61dba26daada128f5891f1a57c504
),
'O' =>
array (
'OpenApi\\' => 8,
'OneSignal\\' => 10,
'OTPHP\\' => 6,
),
@ -341,6 +344,10 @@ class ComposerStaticInitc3a61dba26daada128f5891f1a57c504
array (
0 => __DIR__ . '/..' . '/symfony/event-dispatcher-contracts',
),
'Symfony\\Component\\Yaml\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/yaml',
),
'Symfony\\Component\\Translation\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/translation',
@ -365,6 +372,10 @@ class ComposerStaticInitc3a61dba26daada128f5891f1a57c504
array (
0 => __DIR__ . '/..' . '/symfony/http-client',
),
'Symfony\\Component\\Finder\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/finder',
),
'Symfony\\Component\\EventDispatcher\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/event-dispatcher',
@ -483,6 +494,10 @@ class ComposerStaticInitc3a61dba26daada128f5891f1a57c504
array (
0 => __DIR__ . '/..' . '/phpmailer/phpmailer/src',
),
'OpenApi\\' =>
array (
0 => __DIR__ . '/..' . '/zircote/swagger-php/src',
),
'OneSignal\\' =>
array (
0 => __DIR__ . '/..' . '/norkunas/onesignal-php-api/src',

View file

@ -6958,6 +6958,72 @@
],
"install-path": "../symfony/event-dispatcher-contracts"
},
{
"name": "symfony/finder",
"version": "v5.4.45",
"version_normalized": "5.4.45.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/finder.git",
"reference": "63741784cd7b9967975eec610b256eed3ede022b"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/finder/zipball/63741784cd7b9967975eec610b256eed3ede022b",
"reference": "63741784cd7b9967975eec610b256eed3ede022b",
"shasum": ""
},
"require": {
"php": ">=7.2.5",
"symfony/deprecation-contracts": "^2.1|^3",
"symfony/polyfill-php80": "^1.16"
},
"time": "2024-09-28T13:32:08+00:00",
"type": "library",
"installation-source": "dist",
"autoload": {
"psr-4": {
"Symfony\\Component\\Finder\\": ""
},
"exclude-from-classmap": [
"/Tests/"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Fabien Potencier",
"email": "fabien@symfony.com"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
"description": "Finds files and directories via an intuitive fluent interface",
"homepage": "https://symfony.com",
"support": {
"source": "https://github.com/symfony/finder/tree/v5.4.45"
},
"funding": [
{
"url": "https://symfony.com/sponsor",
"type": "custom"
},
{
"url": "https://github.com/fabpot",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
"install-path": "../symfony/finder"
},
{
"name": "symfony/http-client",
"version": "v5.4.49",
@ -8385,6 +8451,84 @@
],
"install-path": "../symfony/translation-contracts"
},
{
"name": "symfony/yaml",
"version": "v5.4.45",
"version_normalized": "5.4.45.0",
"source": {
"type": "git",
"url": "https://github.com/symfony/yaml.git",
"reference": "a454d47278cc16a5db371fe73ae66a78a633371e"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/yaml/zipball/a454d47278cc16a5db371fe73ae66a78a633371e",
"reference": "a454d47278cc16a5db371fe73ae66a78a633371e",
"shasum": ""
},
"require": {
"php": ">=7.2.5",
"symfony/deprecation-contracts": "^2.1|^3",
"symfony/polyfill-ctype": "^1.8"
},
"conflict": {
"symfony/console": "<5.3"
},
"require-dev": {
"symfony/console": "^5.3|^6.0"
},
"suggest": {
"symfony/console": "For validating YAML files using the lint command"
},
"time": "2024-09-25T14:11:13+00:00",
"bin": [
"Resources/bin/yaml-lint"
],
"type": "library",
"installation-source": "dist",
"autoload": {
"psr-4": {
"Symfony\\Component\\Yaml\\": ""
},
"exclude-from-classmap": [
"/Tests/"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Fabien Potencier",
"email": "fabien@symfony.com"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
"description": "Loads and dumps YAML files",
"homepage": "https://symfony.com",
"support": {
"source": "https://github.com/symfony/yaml/tree/v5.4.45"
},
"funding": [
{
"url": "https://symfony.com/sponsor",
"type": "custom"
},
{
"url": "https://github.com/fabpot",
"type": "github"
},
{
"url": "https://tidelift.com/funding/github/packagist/symfony/symfony",
"type": "tidelift"
}
],
"install-path": "../symfony/yaml"
},
{
"name": "thecodingmachine/safe",
"version": "v2.5.0",
@ -8635,6 +8779,95 @@
"source": "https://github.com/vimeo/vimeo.php/tree/3.0.10"
},
"install-path": "../vimeo/vimeo-api"
},
{
"name": "zircote/swagger-php",
"version": "5.0.7",
"version_normalized": "5.0.7.0",
"source": {
"type": "git",
"url": "https://github.com/zircote/swagger-php.git",
"reference": "18457fa71f753cfd4a2b21916baf329864fdfaa6"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/zircote/swagger-php/zipball/18457fa71f753cfd4a2b21916baf329864fdfaa6",
"reference": "18457fa71f753cfd4a2b21916baf329864fdfaa6",
"shasum": ""
},
"require": {
"ext-json": "*",
"nikic/php-parser": "^4.19 || ^5.0",
"php": ">=7.4",
"psr/log": "^1.1 || ^2.0 || ^3.0",
"symfony/deprecation-contracts": "^2 || ^3",
"symfony/finder": "^5.0 || ^6.0 || ^7.0",
"symfony/yaml": "^5.0 || ^6.0 || ^7.0"
},
"conflict": {
"symfony/process": ">=6, <6.4.14"
},
"require-dev": {
"composer/package-versions-deprecated": "^1.11",
"doctrine/annotations": "^2.0",
"friendsofphp/php-cs-fixer": "^3.62.0",
"phpstan/phpstan": "^1.6 || ^2.0",
"phpunit/phpunit": "^9.0",
"rector/rector": "^1.0 || ^2.0",
"vimeo/psalm": "^4.30 || ^5.0"
},
"suggest": {
"doctrine/annotations": "^2.0"
},
"time": "2025-03-19T03:31:11+00:00",
"bin": [
"bin/openapi"
],
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "5.x-dev"
}
},
"installation-source": "dist",
"autoload": {
"psr-4": {
"OpenApi\\": "src"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"Apache-2.0"
],
"authors": [
{
"name": "Robert Allen",
"email": "zircote@gmail.com"
},
{
"name": "Bob Fanger",
"email": "bfanger@gmail.com",
"homepage": "https://bfanger.nl"
},
{
"name": "Martin Rademacher",
"email": "mano@radebatz.net",
"homepage": "https://radebatz.net"
}
],
"description": "swagger-php - Generate interactive documentation for your RESTful API using phpdoc annotations",
"homepage": "https://github.com/zircote/swagger-php/",
"keywords": [
"api",
"json",
"rest",
"service discovery"
],
"support": {
"issues": "https://github.com/zircote/swagger-php/issues",
"source": "https://github.com/zircote/swagger-php/tree/5.0.7"
},
"install-path": "../zircote/swagger-php"
}
],
"dev": true,
@ -8643,7 +8876,6 @@
"hamcrest/hamcrest-php",
"mockery/mockery",
"myclabs/deep-copy",
"nikic/php-parser",
"phar-io/manifest",
"phar-io/version",
"phpunit/php-code-coverage",

View file

@ -5,7 +5,7 @@
'type' => 'project',
'install_path' => __DIR__ . '/../../',
'aliases' => array(),
'reference' => '14677777576edadbe1b3dd1f1d1833040b092088',
'reference' => 'a573e1543cc1190a160807669d4044da00ada2d3',
'name' => 'wwbn/avideo',
'dev' => true,
),
@ -386,7 +386,7 @@
'install_path' => __DIR__ . '/../nikic/php-parser',
'aliases' => array(),
'reference' => '447a020a1f875a434d62f2a401f53b82a396e494',
'dev_requirement' => true,
'dev_requirement' => false,
),
'norkunas/onesignal-php-api' => array(
'pretty_version' => 'v2.15.0',
@ -998,6 +998,15 @@
0 => '2.0',
),
),
'symfony/finder' => array(
'pretty_version' => 'v5.4.45',
'version' => '5.4.45.0',
'type' => 'library',
'install_path' => __DIR__ . '/../symfony/finder',
'aliases' => array(),
'reference' => '63741784cd7b9967975eec610b256eed3ede022b',
'dev_requirement' => false,
),
'symfony/http-client' => array(
'pretty_version' => 'v5.4.49',
'version' => '5.4.49.0',
@ -1163,6 +1172,15 @@
0 => '2.3',
),
),
'symfony/yaml' => array(
'pretty_version' => 'v5.4.45',
'version' => '5.4.45.0',
'type' => 'library',
'install_path' => __DIR__ . '/../symfony/yaml',
'aliases' => array(),
'reference' => 'a454d47278cc16a5db371fe73ae66a78a633371e',
'dev_requirement' => false,
),
'thecodingmachine/safe' => array(
'pretty_version' => 'v2.5.0',
'version' => '2.5.0.0',
@ -1196,7 +1214,16 @@
'type' => 'project',
'install_path' => __DIR__ . '/../../',
'aliases' => array(),
'reference' => '14677777576edadbe1b3dd1f1d1833040b092088',
'reference' => 'a573e1543cc1190a160807669d4044da00ada2d3',
'dev_requirement' => false,
),
'zircote/swagger-php' => array(
'pretty_version' => '5.0.7',
'version' => '5.0.7.0',
'type' => 'library',
'install_path' => __DIR__ . '/../zircote/swagger-php',
'aliases' => array(),
'reference' => '18457fa71f753cfd4a2b21916baf329864fdfaa6',
'dev_requirement' => false,
),
),

View file

@ -19,7 +19,7 @@ class Comparator
private $target;
private $operator = '==';
public function __construct(string $target = null, string $operator = '==')
public function __construct(?string $target = null, string $operator = '==')
{
if (null === $target) {
trigger_deprecation('symfony/finder', '5.4', 'Constructing a "%s" without setting "$target" is deprecated.', __CLASS__);

View file

@ -35,7 +35,7 @@ namespace Symfony\Component\Finder\Comparator;
class NumberComparator extends Comparator
{
/**
* @param string|int $test A comparison string or an integer
* @param string|null $test A comparison string or null
*
* @throws \InvalidArgumentException If the test is not understood
*/

View file

@ -164,8 +164,8 @@ class Finder implements \IteratorAggregate, \Countable
*
* You can use patterns (delimited with / sign), globs or simple strings.
*
* $finder->name('*.php')
* $finder->name('/\.php$/') // same as above
* $finder->name('/\.php$/')
* $finder->name('*.php') // same as above, without dot files
* $finder->name('test.php')
* $finder->name(['test.py', 'test.php'])
*

View file

@ -17,6 +17,7 @@ namespace Symfony\Component\Finder\Iterator;
* @author Fabien Potencier <fabien@symfony.com>
*
* @extends \FilterIterator<string, \SplFileInfo>
*
* @implements \RecursiveIterator<string, \SplFileInfo>
*/
class ExcludeDirectoryFilterIterator extends \FilterIterator implements \RecursiveIterator

View file

@ -29,7 +29,7 @@ class RecursiveDirectoryIterator extends \RecursiveDirectoryIterator
/**
* @var bool
*/
private $rewindable;
private $ignoreFirstRewind = true;
// these 3 properties take part of the performance optimization to avoid redoing the same work in all iterations
private $rootPath;
@ -70,8 +70,9 @@ class RecursiveDirectoryIterator extends \RecursiveDirectoryIterator
$subPathname .= $this->directorySeparator;
}
$subPathname .= $this->getFilename();
$basePath = $this->rootPath;
if ('/' !== $basePath = $this->rootPath) {
if ('/' !== $basePath && !str_ends_with($basePath, $this->directorySeparator) && !str_ends_with($basePath, '/')) {
$basePath .= $this->directorySeparator;
}
@ -118,7 +119,6 @@ class RecursiveDirectoryIterator extends \RecursiveDirectoryIterator
$children->ignoreUnreadableDirs = $this->ignoreUnreadableDirs;
// performance optimization to avoid redoing the same work in all children
$children->rewindable = &$this->rewindable;
$children->rootPath = $this->rootPath;
}
@ -129,40 +129,30 @@ class RecursiveDirectoryIterator extends \RecursiveDirectoryIterator
}
/**
* Do nothing for non rewindable stream.
*
* @return void
*/
#[\ReturnTypeWillChange]
public function next()
{
$this->ignoreFirstRewind = false;
parent::next();
}
/**
* @return void
*/
#[\ReturnTypeWillChange]
public function rewind()
{
if (false === $this->isRewindable()) {
// some streams like FTP are not rewindable, ignore the first rewind after creation,
// as newly created DirectoryIterator does not need to be rewound
if ($this->ignoreFirstRewind) {
$this->ignoreFirstRewind = false;
return;
}
parent::rewind();
}
/**
* Checks if the stream is rewindable.
*
* @return bool
*/
public function isRewindable()
{
if (null !== $this->rewindable) {
return $this->rewindable;
}
if (false !== $stream = @opendir($this->getPath())) {
$infos = stream_get_meta_data($stream);
closedir($stream);
if ($infos['seekable']) {
return $this->rewindable = true;
}
}
return $this->rewindable = false;
}
}

View file

@ -1,4 +1,4 @@
Copyright (c) 2004-2023 Fabien Potencier
Copyright (c) 2004-present Fabien Potencier
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

View file

@ -43,7 +43,7 @@ class LintCommand extends Command
private $directoryIteratorProvider;
private $isReadableProvider;
public function __construct(string $name = null, callable $directoryIteratorProvider = null, callable $isReadableProvider = null)
public function __construct(?string $name = null, ?callable $directoryIteratorProvider = null, ?callable $isReadableProvider = null)
{
parent::__construct($name);
@ -133,7 +133,7 @@ EOF
return $this->display($io, $filesInfo);
}
private function validate(string $content, int $flags, string $file = null)
private function validate(string $content, int $flags, ?string $file = null)
{
$prevErrorHandler = set_error_handler(function ($level, $message, $file, $line) use (&$prevErrorHandler) {
if (\E_USER_DEPRECATED === $level) {

View file

@ -69,9 +69,7 @@ class Dumper
}
if (Yaml::DUMP_MULTI_LINE_LITERAL_BLOCK & $flags && \is_string($value) && false !== strpos($value, "\n") && false === strpos($value, "\r")) {
// If the first line starts with a space character, the spec requires a blockIndicationIndicator
// http://www.yaml.org/spec/1.2/spec.html#id2793979
$blockIndentationIndicator = (' ' === substr($value, 0, 1)) ? (string) $this->indentation : '';
$blockIndentationIndicator = $this->getBlockIndentationIndicator($value);
if (isset($value[-2]) && "\n" === $value[-2] && "\n" === $value[-1]) {
$blockChompingIndicator = '+';
@ -98,9 +96,7 @@ class Dumper
$output .= sprintf('%s%s !%s', $prefix, $dumpAsMap ? Inline::dump($key, $flags).':' : '-', $value->getTag());
if (Yaml::DUMP_MULTI_LINE_LITERAL_BLOCK & $flags && \is_string($value->getValue()) && false !== strpos($value->getValue(), "\n") && false === strpos($value->getValue(), "\r\n")) {
// If the first line starts with a space character, the spec requires a blockIndicationIndicator
// http://www.yaml.org/spec/1.2/spec.html#id2793979
$blockIndentationIndicator = (' ' === substr($value->getValue(), 0, 1)) ? (string) $this->indentation : '';
$blockIndentationIndicator = $this->getBlockIndentationIndicator($value->getValue());
$output .= sprintf(' |%s', $blockIndentationIndicator);
foreach (explode("\n", $value->getValue()) as $row) {
@ -145,9 +141,7 @@ class Dumper
$output = sprintf('%s!%s', $prefix ? $prefix.' ' : '', $value->getTag());
if (Yaml::DUMP_MULTI_LINE_LITERAL_BLOCK & $flags && \is_string($value->getValue()) && false !== strpos($value->getValue(), "\n") && false === strpos($value->getValue(), "\r\n")) {
// If the first line starts with a space character, the spec requires a blockIndicationIndicator
// http://www.yaml.org/spec/1.2/spec.html#id2793979
$blockIndentationIndicator = (' ' === substr($value->getValue(), 0, 1)) ? (string) $this->indentation : '';
$blockIndentationIndicator = $this->getBlockIndentationIndicator($value->getValue());
$output .= sprintf(' |%s', $blockIndentationIndicator);
foreach (explode("\n", $value->getValue()) as $row) {
@ -163,4 +157,20 @@ class Dumper
return $output."\n".$this->dump($value->getValue(), $inline - 1, $indent, $flags);
}
private function getBlockIndentationIndicator(string $value): string
{
$lines = explode("\n", $value);
// If the first line (that is neither empty nor contains only spaces)
// starts with a space character, the spec requires a block indentation indicator
// http://www.yaml.org/spec/1.2/spec.html#id2793979
foreach ($lines as $line) {
if ('' !== trim($line, ' ')) {
return (' ' === substr($line, 0, 1)) ? (string) $this->indentation : '';
}
}
return '';
}
}

View file

@ -29,7 +29,7 @@ class ParseException extends RuntimeException
* @param string|null $snippet The snippet of code near the problem
* @param string|null $parsedFile The file name where the error occurred
*/
public function __construct(string $message, int $parsedLine = -1, string $snippet = null, string $parsedFile = null, \Throwable $previous = null)
public function __construct(string $message, int $parsedLine = -1, ?string $snippet = null, ?string $parsedFile = null, ?\Throwable $previous = null)
{
$this->parsedFile = $parsedFile;
$this->parsedLine = $parsedLine;

View file

@ -34,7 +34,7 @@ class Inline
private static $objectForMap = false;
private static $constantSupport = false;
public static function initialize(int $flags, int $parsedLineNumber = null, string $parsedFilename = null)
public static function initialize(int $flags, ?int $parsedLineNumber = null, ?string $parsedFilename = null)
{
self::$exceptionOnInvalidType = (bool) (Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE & $flags);
self::$objectSupport = (bool) (Yaml::PARSE_OBJECT & $flags);
@ -50,16 +50,20 @@ class Inline
/**
* Converts a YAML string to a PHP value.
*
* @param string $value A YAML string
* @param int $flags A bit field of Yaml::PARSE_* constants to customize the YAML parser behavior
* @param array $references Mapping of variable names to values
* @param string|null $value A YAML string
* @param int $flags A bit field of Yaml::PARSE_* constants to customize the YAML parser behavior
* @param array $references Mapping of variable names to values
*
* @return mixed
*
* @throws ParseException
*/
public static function parse(string $value = null, int $flags = 0, array &$references = [])
public static function parse(?string $value = null, int $flags = 0, array &$references = [])
{
if (null === $value) {
return '';
}
self::initialize($flags);
$value = trim($value);
@ -265,7 +269,7 @@ class Inline
*
* @throws ParseException When malformed inline YAML string is parsed
*/
public static function parseScalar(string $scalar, int $flags = 0, array $delimiters = null, int &$i = 0, bool $evaluate = true, array &$references = [], bool &$isQuoted = null)
public static function parseScalar(string $scalar, int $flags = 0, ?array $delimiters = null, int &$i = 0, bool $evaluate = true, array &$references = [], ?bool &$isQuoted = null)
{
if (\in_array($scalar[$i], ['"', "'"], true)) {
// quoted scalar
@ -351,11 +355,18 @@ class Inline
++$i;
// [foo, bar, ...]
$lastToken = null;
while ($i < $len) {
if (']' === $sequence[$i]) {
return $output;
}
if (',' === $sequence[$i] || ' ' === $sequence[$i]) {
if (',' === $sequence[$i] && (null === $lastToken || 'separator' === $lastToken)) {
$output[] = null;
} elseif (',' === $sequence[$i]) {
$lastToken = 'separator';
}
++$i;
continue;
@ -399,6 +410,7 @@ class Inline
$output[] = $value;
$lastToken = 'value';
++$i;
}
@ -527,7 +539,7 @@ class Inline
if ('<<' === $key) {
$output += $value;
} elseif ($allowOverwrite || !isset($output[$key])) {
if (!$isValueQuoted && \is_string($value) && '' !== $value && '&' === $value[0] && Parser::preg_match(Parser::REFERENCE_PATTERN, $value, $matches)) {
if (!$isValueQuoted && \is_string($value) && '' !== $value && '&' === $value[0] && !self::isBinaryString($value) && Parser::preg_match(Parser::REFERENCE_PATTERN, $value, $matches)) {
$references[$matches['ref']] = $matches['value'];
$value = $matches['value'];
}
@ -558,7 +570,7 @@ class Inline
*
* @throws ParseException when object parsing support was disabled and the parser detected a PHP object or when a reference could not be resolved
*/
private static function evaluateScalar(string $scalar, int $flags, array &$references = [], bool &$isQuotedString = null)
private static function evaluateScalar(string $scalar, int $flags, array &$references = [], ?bool &$isQuotedString = null)
{
$isQuotedString = false;
$scalar = trim($scalar);
@ -696,8 +708,13 @@ class Inline
case Parser::preg_match('/^(-|\+)?[0-9][0-9_]*(\.[0-9_]+)?$/', $scalar):
return (float) str_replace('_', '', $scalar);
case Parser::preg_match(self::getTimestampRegex(), $scalar):
// When no timezone is provided in the parsed date, YAML spec says we must assume UTC.
$time = new \DateTime($scalar, new \DateTimeZone('UTC'));
try {
// When no timezone is provided in the parsed date, YAML spec says we must assume UTC.
$time = new \DateTime($scalar, new \DateTimeZone('UTC'));
} catch (\Exception $e) {
// Some dates accepted by the regex are not valid dates.
throw new ParseException(\sprintf('The date "%s" could not be parsed as it is an invalid date.', $scalar), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename, $e);
}
if (Yaml::PARSE_DATETIME & $flags) {
return $time;

View file

@ -1,4 +1,4 @@
Copyright (c) 2004-2023 Fabien Potencier
Copyright (c) 2004-present Fabien Potencier
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

View file

@ -199,9 +199,8 @@ class Parser
|| self::preg_match('#^(?P<key>'.Inline::REGEX_QUOTED_STRING.'|[^ \'"\{\[].*?) *\:(\s+(?P<value>.+?))?\s*$#u', $this->trimTag($values['value']), $matches)
)
) {
// this is a compact notation element, add to next block and parse
$block = $values['value'];
if ($this->isNextLineIndented()) {
if ($this->isNextLineIndented() || isset($matches['value']) && '>-' === $matches['value']) {
$block .= "\n".$this->getNextEmbedBlock($this->getCurrentLineIndentation() + \strlen($values['leadspaces']) + 1);
}
@ -577,7 +576,7 @@ class Parser
*
* @throws ParseException When indentation problem are detected
*/
private function getNextEmbedBlock(int $indentation = null, bool $inSequence = false): string
private function getNextEmbedBlock(?int $indentation = null, bool $inSequence = false): string
{
$oldLineIndentation = $this->getCurrentLineIndentation();
@ -654,12 +653,12 @@ class Parser
}
if ($this->isCurrentLineBlank()) {
$data[] = substr($this->currentLine, $newIndent);
$data[] = substr($this->currentLine, $newIndent ?? 0);
continue;
}
if ($indent >= $newIndent) {
$data[] = substr($this->currentLine, $newIndent);
$data[] = substr($this->currentLine, $newIndent ?? 0);
} elseif ($this->isCurrentLineComment()) {
$data[] = $this->currentLine;
} elseif (0 == $indent) {
@ -949,6 +948,10 @@ class Parser
} while (!$EOF && ($this->isCurrentLineEmpty() || $this->isCurrentLineComment()));
if ($EOF) {
for ($i = 0; $i < $movements; ++$i) {
$this->moveToPreviousLine();
}
return false;
}
@ -1079,7 +1082,7 @@ class Parser
*
* @internal
*/
public static function preg_match(string $pattern, string $subject, array &$matches = null, int $flags = 0, int $offset = 0): int
public static function preg_match(string $pattern, string $subject, ?array &$matches = null, int $flags = 0, int $offset = 0): int
{
if (false === $ret = preg_match($pattern, $subject, $matches, $flags, $offset)) {
switch (preg_last_error()) {

View file

@ -0,0 +1,83 @@
## Contributing
Contributions of any kind are welcome.
Feel free to submit [Github Issues](https://github.com/zircote/swagger-php/issues)
or [pull requests](https://github.com/zircote/swagger-php/pulls).
## Quick Guide
The documentation site has [some details](https://zircote.github.io/swagger-php/guide/under-the-hood.html#documentation) about internals.
### How-To
* [Fork](https://help.github.com/articles/fork-a-repo/) the repo.
* [Checkout](https://git-scm.com/docs/git-checkout) the branch you want to make changes on.
* Typically, this will be `master`. Note that most of the time, `master` represents the next release of swagger-php, so Pull Requests that break backwards compatibility might be postponed.
* Install dependencies: `composer install`.
* Create a new branch, e.g. `feature-foo` or `bugfix-bar`.
* Make changes.
* If you are adding functionality or fixing a bug - add a test!
Prefer adding new test cases over modifying existing ones.
* Update documentation: `composer docs:gen`.
* Run static analysis using PHPStan/Psalm: `composer analyse`.
* Check if tests pass: `composer test`.
* Fix code style issues: `composer cs`.
## Documentation
The documentation website is build from the [docs](docs/) folder with [vitepress](https://vitepress.vuejs.org).
This process involves converting the existing markdown (`.md`) files into static HTML pages and publishing them.
Some reference content is based on the existing code, so changes to annotations, attributes and processors will require to re-generate those markdown files: `composer docs:gen`.
The actual published content is managed in the [gh-pages](https://github.com/zircote/swagger-php/tree/gh-pages) branch and driven by a [publish action](https://github.com/zircote/swagger-php/actions/workflows/gh-pages.yml).
## Useful commands
### To run both unit tests and linting execute
```shell
composer test
```
### To run static-analysis execute
```shell
composer analyse
```
### Running unit tests only
```shell
./bin/phpunit
```
### Regenerate reference markup docs
```shell
composer docs:gen
```
### Running linting only
```shell
composer lint
```
### To make `php-cs-fixer` fix linting errors
```shell
composer cs
```
### Run dev server for local development of `gh-pages`
```shell
composer docs:dev
```
## Project's Standards
* [PSR-1: Basic Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-1-basic-coding-standard.md)
* [PSR-2: Coding Style Guide](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)
* [PSR-4: Autoloading Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader.md)
* [PSR-5: PHPDoc (draft)](https://github.com/phpDocumentor/fig-standards/blob/master/proposed/phpdoc.md)

202
vendor/zircote/swagger-php/LICENSE vendored Normal file
View file

@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

2
vendor/zircote/swagger-php/NOTICE vendored Normal file
View file

@ -0,0 +1,2 @@
swagger-php
Copyright 2022 The swagger-php project

124
vendor/zircote/swagger-php/README.md vendored Normal file
View file

@ -0,0 +1,124 @@
[![Build Status](https://img.shields.io/github/actions/workflow/status/zircote/swagger-php/build.yml?branch=master)](https://github.com/zircote/swagger-php/actions?query=workflow:build)
[![Total Downloads](https://img.shields.io/packagist/dt/zircote/swagger-php.svg)](https://packagist.org/packages/zircote/swagger-php)
[![License](https://img.shields.io/badge/license-Apache2.0-blue.svg)](LICENSE)
# swagger-php
Generate interactive [OpenAPI](https://www.openapis.org) documentation for your RESTful API using [PHP attributes](https://www.php.net/manual/en/language.attributes.overview.php) (preferred) or
[doctrine annotations](https://www.doctrine-project.org/projects/annotations.html) (requires additional `doctrine/annotations` library).
See the [documentation website](https://zircote.github.io/swagger-php/guide/attributes.html) for supported attributes and annotations.
Annotations are deprecated and may be removed in a future release of swagger-php.
## Features
- Compatible with the OpenAPI **3.0** and **3.1** specification.
- Extracts information from code & existing phpdoc annotations.
- Command-line interface available.
- [Documentation site](https://zircote.github.io/swagger-php/) with a getting started guide.
- Exceptional error reporting (with hints, context)
- As of PHP 8.1 all annotations are also available as PHP attributes
## OpenAPI version support
`swagger-php` allows to generate specs either for **OpenAPI 3.0.0** or **OpenAPI 3.1.0**.
By default the spec will be in version `3.0.0`. The command line option `--version` may be used to change this
to `3.1.0`.
Programmatically, the method `Generator::setVersion()` can be used to change the version.
## Requirements
`swagger-php` requires at least PHP 7.4 for annotations and PHP 8.1 for using attributes.
## Installation (with [Composer](https://getcomposer.org))
```shell
composer require zircote/swagger-php
```
For cli usage from anywhere install swagger-php globally and make sure to place the `~/.composer/vendor/bin` directory in your PATH so the `openapi` executable can be located by your system.
```shell
composer global require zircote/swagger-php
```
### doctrine/annotations
As of version `4.8` the [doctrine annotations](https://www.doctrine-project.org/projects/annotations.html) library **is optional** and **no longer installed by default**.
To use PHPDoc annotations this needs to be installed on top of `swagger-php`:
```shell
composer require doctrine/annotations
```
If your code uses PHPDoc annotations you will need to install this as well:
```shell
composer require doctrine/annotations
```
## Usage
Add annotations to your php files.
```php
/**
* @OA\Info(title="My First API", version="0.1")
*/
/**
* @OA\Get(
* path="/api/resource.json",
* @OA\Response(response="200", description="An example resource")
* )
*/
```
Visit the [Documentation website](https://zircote.github.io/swagger-php/) for the [Getting started guide](https://zircote.github.io/swagger-php/guide) or look at the [examples directory](docs/examples) for more examples.
### Usage from php
Generate always-up-to-date documentation.
```php
<?php
require("vendor/autoload.php");
$openapi = \OpenApi\Generator::scan(['/path/to/project']);
header('Content-Type: application/x-yaml');
echo $openapi->toYaml();
```
Documentation of how to use the `Generator` class can be found in the [Generator reference](https://zircote.github.io/swagger-php/reference/generator).
### Usage from the Command Line Interface
The `openapi` command line interface can be used to generate the documentation to a static yaml/json file.
```shell
./vendor/bin/openapi --help
```
### Usage from the Deserializer
Generate the OpenApi annotation object from a json string, which makes it easier to manipulate objects programmatically.
```php
<?php
use OpenApi\Serializer;
$serializer = new Serializer();
$openapi = $serializer->deserialize($jsonString, 'OpenApi\Annotations\OpenApi');
echo $openapi->toJson();
```
## [Contributing](CONTRIBUTING.md)
## More on OpenApi & Swagger
- https://swagger.io
- https://www.openapis.org
- [OpenApi Documentation](https://swagger.io/docs/)
- [OpenApi Specification](http://swagger.io/specification/)
- [Related projects](docs/related-projects.md)

241
vendor/zircote/swagger-php/bin/openapi vendored Normal file
View file

@ -0,0 +1,241 @@
#!/usr/bin/env php
<?php
use OpenApi\Analysers\AttributeAnnotationFactory;
use OpenApi\Analysers\DocBlockAnnotationFactory;
use OpenApi\Analysers\ReflectionAnalyser;
use OpenApi\Annotations\OpenApi;
use OpenApi\Generator;
use OpenApi\Util;
use OpenApi\Loggers\ConsoleLogger;
if (class_exists(Generator::class) === false) {
if (file_exists(__DIR__.'/../vendor/autoload.php')) { // cloned / dev environment?
require_once(__DIR__.'/../vendor/autoload.php');
} else {
require_once(realpath(__DIR__.'/../../../').'/autoload.php');
}
}
error_reporting(E_ALL);
// Possible options and their default values.
$options = [
'config' => [],
'output' => false,
'format' => 'auto',
'exclude' => [],
'pattern' => '*.php',
'bootstrap' => [],
'help' => false,
'debug' => false,
'processor' => [],
'version' => null,
];
$aliases = [
'c' => 'config',
'o' => 'output',
'e' => 'exclude',
'n' => 'pattern',
'b' => 'bootstrap',
'h' => 'help',
'd' => 'debug',
'p' => 'processor',
'f' => 'format'
];
$needsArgument = [
'config',
'output',
'format',
'exclude',
'pattern',
'bootstrap',
'processor',
'version',
];
$paths = [];
$error = false;
try {
// Parse cli arguments
for ($i = 1; $i < $argc; $i++) {
$arg = $argv[$i];
if (substr($arg, 0, 2) === '--') { // longopt
$option = substr($arg, 2);
} elseif ($arg[0] === '-') { // shortopt
if (array_key_exists(substr($arg, 1), $aliases)) {
$option = $aliases[$arg[1]];
} else {
throw new Exception('Unknown option: "' . $arg . '"');
}
} else {
$paths[] = $arg;
continue;
}
if (array_key_exists($option, $options) === false) {
throw new Exception('Unknown option: "' . $arg . '"');
}
if (in_array($option, $needsArgument)) {
if (empty($argv[$i + 1]) || $argv[$i + 1][0] === '-') {
throw new Exception('Missing argument for "' . $arg . '"');
}
if (is_array($options[$option])) {
$options[$option][] = $argv[$i + 1];
} else {
$options[$option] = $argv[$i + 1];
}
$i++;
} else {
$options[$option] = true;
}
}
} catch (\Exception $e) {
$error = $e->getMessage();
}
$logger = new ConsoleLogger($options['debug']);
if (!$error && $options['bootstrap']) {
foreach ($options['bootstrap'] as $bootstrap) {
$filenames = glob($bootstrap);
if (false === $filenames) {
$error = 'Invalid `--bootstrap` value: "' . $bootstrap . '"';
break;
}
foreach ($filenames as $filename) {
if ($options['debug']) {
$logger->debug('Bootstrapping: ' . $filename);
}
require_once($filename);
}
}
}
if (count($paths) === 0) {
$error = 'Specify at least one path.';
}
if ($options['help'] === false && $error) {
$logger->error('', ['prefix' => '']);
$logger->error($error);
// Show help
$options['help'] = true;
}
$defaultVersion = OpenApi::DEFAULT_VERSION;
if ($options['help']) {
$help = <<<EOF
Usage: openapi [--option value] [/path/to/project ...]
Options:
--config (-c) Generator config
ex: -c operationId.hash=false
--output (-o) Path to store the generated documentation.
ex: --output openapi.yaml
--exclude (-e) Exclude path(s).
ex: --exclude vendor,library/Zend
--pattern (-n) Pattern of files to scan.
ex: --pattern "*.php" or --pattern "/\.(phps|php)$/"
--bootstrap (-b) Bootstrap php file(s) for defining constants, etc.
ex: --bootstrap config/constants.php
--processor (-p) Register an additional processor.
--format (-f) Force yaml or json.
--debug (-d) Show additional error information.
--version The OpenAPI version; defaults to {$defaultVersion}.
--help (-h) Display this help message.
EOF;
$logger->info($help);
exit(1);
}
$errorTypes = [
E_ERROR => 'Error',
E_WARNING => 'Warning',
E_PARSE => 'Parser error',
E_NOTICE => 'Notice',
E_DEPRECATED => 'Deprecated',
E_CORE_ERROR => 'Error(Core)',
E_CORE_WARNING => 'Warning(Core)',
E_COMPILE_ERROR => 'Error(compile)',
E_COMPILE_WARNING => 'Warning(Compile)',
E_RECOVERABLE_ERROR => 'Error(Recoverable)',
E_USER_ERROR => 'Error',
E_USER_WARNING => 'Warning',
E_USER_NOTICE => 'Notice',
E_USER_DEPRECATED => 'Deprecated',
];
set_error_handler(function ($errno, $errstr, $file, $line) use ($errorTypes, $options, $logger) {
if (!(error_reporting() & $errno)) {
// This error code is not included in error_reporting
return;
}
$type = array_key_exists($errno, $errorTypes) ? $errorTypes[$errno] : 'Error';
if ($type === 'Deprecated') {
$logger->info($errstr, ['prefix' => $type . ': ']);
} else {
$logger->error($errstr, ['prefix' => $type . ': ']);
}
if ($options['debug']) {
$logger->info(' in '.$file.' on line '.$line);
}
if (substr($type, 0, 5) === 'Error') {
exit($errno);
}
});
set_exception_handler(function ($exception) use ($logger) {
$logger->error($exception);
exit($exception->getCode() ?: 1);
});
$exclude = null;
if ($options['exclude']) {
$exclude = $options['exclude'];
if (strpos($exclude[0], ',') !== false) {
$exploded = explode(',', $exclude[0]);
$logger->error('Comma-separated exclude paths are deprecated, use multiple --exclude statements: --exclude '.$exploded[0].' --exclude '.$exploded[1]);
$exclude[0] = array_shift($exploded);
$exclude = array_merge($exclude, $exploded);
}
}
$pattern = "*.php";
if ($options['pattern']) {
$pattern = $options['pattern'];
}
$generator = new Generator($logger);
foreach ($options["processor"] as $processor) {
$class = '\OpenApi\Processors\\'.$processor;
if (class_exists($class)) {
$processor = new $class();
} elseif (class_exists($processor)) {
$processor = new $processor();
}
$generator->getProcessorPipeline()->add($processor);
}
$analyser = new ReflectionAnalyser([new DocBlockAnnotationFactory(), new AttributeAnnotationFactory()]);
$openapi = $generator
->setVersion($options['version'])
->setConfig($options['config'])
->setAnalyser($analyser)
->generate(Util::finder($paths, $exclude, $pattern));
if ($options['output'] === false) {
if (strtolower($options['format']) === 'json') {
echo $openapi->toJson();
} else {
echo $openapi->toYaml();
}
echo "\n";
} else {
if (is_dir($options['output'])) {
$options['output'] .= '/openapi.yaml';
}
$openapi->saveAs($options['output'], $options['format']);
}
exit($logger->loggedMessageAboveNotice() ? 1 : 0);

139
vendor/zircote/swagger-php/composer.json vendored Normal file
View file

@ -0,0 +1,139 @@
{
"name": "zircote/swagger-php",
"type": "library",
"license": "Apache-2.0",
"bin": [
"bin/openapi"
],
"description": "swagger-php - Generate interactive documentation for your RESTful API using phpdoc annotations",
"keywords": [
"json",
"rest",
"api",
"service discovery"
],
"homepage": "https://github.com/zircote/swagger-php/",
"authors": [
{
"name": "Robert Allen",
"email": "zircote@gmail.com"
},
{
"name": "Bob Fanger",
"email": "bfanger@gmail.com",
"homepage": "https://bfanger.nl"
},
{
"name": "Martin Rademacher",
"email": "mano@radebatz.net",
"homepage": "https://radebatz.net"
}
],
"config": {
"bin-dir": "bin",
"optimize-autoloader": true,
"sort-packages": true,
"allow-plugins": {
"composer/package-versions-deprecated": true
}
},
"minimum-stability": "stable",
"extra": {
"branch-alias": {
"dev-master": "5.x-dev"
}
},
"require": {
"php": ">=7.4",
"ext-json": "*",
"nikic/php-parser": "^4.19 || ^5.0",
"psr/log": "^1.1 || ^2.0 || ^3.0",
"symfony/deprecation-contracts": "^2 || ^3",
"symfony/finder": "^5.0 || ^6.0 || ^7.0",
"symfony/yaml": "^5.0 || ^6.0 || ^7.0"
},
"autoload": {
"psr-4": {
"OpenApi\\": "src"
}
},
"autoload-dev": {
"exclude-from-classmap": [
"/tests/Fixtures"
],
"psr-4": {
"OpenApi\\Tools\\": "tools/src/",
"OpenApi\\Tests\\": "tests/",
"AnotherNamespace\\": "tests/Fixtures/AnotherNamespace"
}
},
"require-dev": {
"composer/package-versions-deprecated": "^1.11",
"doctrine/annotations": "^2.0",
"friendsofphp/php-cs-fixer": "^3.62.0",
"phpstan/phpstan": "^1.6 || ^2.0",
"phpunit/phpunit": "^9.0",
"rector/rector": "^1.0 || ^2.0",
"vimeo/psalm": "^4.30 || ^5.0"
},
"conflict": {
"symfony/process": ">=6, <6.4.14"
},
"suggest": {
"doctrine/annotations": "^2.0"
},
"scripts-descriptions": {
"cs": "Fix all codestyle issues",
"rector": "Automatic refactoring",
"lint": "Test codestyle",
"test": "Run all PHP, codestyle and rector tests",
"analyse": "Run static analysis (phpstan/psalm)",
"spectral-examples": "Run spectral lint over all .yaml files in the docs/examples folder",
"spectral-scratch": "Run spectral lint over all .yaml files in the tests/Fixtures/Scratch folder",
"spectral": "Run all spectral tests",
"redocly-examples": "Run redocly lint over all .yaml files in the docs/examples folder",
"redocly-scratch": "Run redocly lint over all .yaml files in the tests/Fixtures/Scratch folder",
"redocly": "Run all redocly tests",
"docs:gen": "Rebuild reference documentation",
"docs:dev": "Run dev server for local development of gh-pages",
"docs:build": "Re-build static gh-pages"
},
"scripts": {
"cs": "export XDEBUG_MODE=off && php-cs-fixer fix --allow-risky=yes",
"rector": "rector process src",
"lint": [
"@cs --dry-run",
"@rector --dry-run"
],
"test": [
"export XDEBUG_MODE=off && phpunit",
"@lint"
],
"analyse": [
"export XDEBUG_MODE=off && phpstan analyse --memory-limit=2G",
"export XDEBUG_MODE=off && psalm --threads=1"
],
"spectral-examples": "for ff in `find docs/examples -name '*.yaml'`; do npm run spectral lint $ff; done",
"spectral-scratch": "for ff in `find tests/Fixtures/Scratch -name '*.yaml'`; do npm run spectral lint $ff; done",
"spectral": [
"@spectral-examples",
"@spectral-scratch"
],
"redocly-examples": "for ff in `find docs/examples -name '*.yaml'`; do npm run redocly lint $ff; done",
"redocly-scratch": "for ff in `find tests/Fixtures/Scratch -name '*.yaml'`; do npm run redocly lint $ff; done",
"redocly": [
"@redocly-examples",
"@redocly-scratch"
],
"docs:gen": [
"@php tools/refgen.php",
"@php tools/procgen.php",
"@php tools/examplegen.php"
],
"docs:dev": "cd docs && npm run dev",
"docs:build": [
"@docs:gen",
"cd docs && npm run build"
]
}
}

13
vendor/zircote/swagger-php/package.json vendored Normal file
View file

@ -0,0 +1,13 @@
{
"name": "swagger-php-tools",
"version": "1.0.0",
"license": "Apache-2.0",
"scripts": {
"spectral": "spectral",
"redocly": "redocly"
},
"devDependencies": {
"@stoplight/spectral-cli": "^6",
"@redocly/cli": "^1.30"
}
}

31
vendor/zircote/swagger-php/rector.php vendored Normal file
View file

@ -0,0 +1,31 @@
<?php
use Rector\CodeQuality\Rector\ClassMethod\ExplicitReturnNullRector;
use Rector\CodeQuality\Rector\For_\ForRepeatedCountToOwnVariableRector;
use Rector\CodeQuality\Rector\If_\CombineIfRector;
use Rector\CodeQuality\Rector\If_\ExplicitBoolCompareRector;
use Rector\CodeQuality\Rector\If_\ShortenElseIfRector;
use Rector\Config\RectorConfig;
use Rector\DeadCode\Rector\If_\RemoveAlwaysTrueIfConditionRector;
use Rector\DeadCode\Rector\If_\RemoveDeadInstanceOfRector;
use Rector\TypeDeclaration\Rector\Property\TypedPropertyFromStrictConstructorRector;
use Rector\ValueObject\PhpVersion;
return RectorConfig::configure()
->withRules([
TypedPropertyFromStrictConstructorRector::class
])
->withSkip([
CombineIfRector::class,
ExplicitBoolCompareRector::class,
ForRepeatedCountToOwnVariableRector::class,
RemoveAlwaysTrueIfConditionRector::class => [
__DIR__ . '/src/Processors/ExpandEnums.php',
] ,
RemoveDeadInstanceOfRector::class => [
__DIR__ . '/src/Processors/ExpandEnums.php',
],
ShortenElseIfRector::class,
])
->withPreparedSets(true, true)
->withPhpVersion(PhpVersion::PHP_74);

View file

@ -0,0 +1,18 @@
<?php declare(strict_types=1);
/**
* @license Apache 2.0
*/
namespace OpenApi\Analysers;
use OpenApi\Analysis;
use OpenApi\Context;
use OpenApi\Generator;
interface AnalyserInterface
{
public function setGenerator(Generator $generator): void;
public function fromFile(string $filename, Context $context): Analysis;
}

View file

@ -0,0 +1,26 @@
<?php declare(strict_types=1);
/**
* @license Apache 2.0
*/
namespace OpenApi\Analysers;
use OpenApi\Annotations as OA;
use OpenApi\Context;
use OpenApi\Generator;
interface AnnotationFactoryInterface
{
/**
* Checks if this factory is supported by the current runtime.
*/
public function isSupported(): bool;
public function setGenerator(Generator $generator): void;
/**
* @return array<OA\AbstractAnnotation> top level annotations
*/
public function build(\Reflector $reflector, Context $context): array;
}

View file

@ -0,0 +1,159 @@
<?php declare(strict_types=1);
/**
* @license Apache 2.0
*/
namespace OpenApi\Analysers;
use OpenApi\Annotations as OA;
use OpenApi\Context;
use OpenApi\Generator;
class AttributeAnnotationFactory implements AnnotationFactoryInterface
{
use GeneratorAwareTrait;
public function isSupported(): bool
{
return \PHP_VERSION_ID >= 80100;
}
public function build(\Reflector $reflector, Context $context): array
{
if (!$this->isSupported() || !method_exists($reflector, 'getAttributes')) {
return [];
}
if ($reflector instanceof \ReflectionProperty && method_exists($reflector, 'isPromoted') && $reflector->isPromoted()) {
// handled via __construct() parameter
return [];
}
// no proper way to inject
Generator::$context = $context;
/** @var OA\AbstractAnnotation[] $annotations */
$annotations = [];
try {
foreach ($reflector->getAttributes() as $attribute) {
if (class_exists($attribute->getName())) {
$instance = $attribute->newInstance();
if ($instance instanceof OA\AbstractAnnotation) {
$annotations[] = $instance;
} else {
if ($context->is('other') === false) {
$context->other = [];
}
$context->other[] = $instance;
}
} else {
$context->logger->debug(sprintf('Could not instantiate attribute "%s"; class not found.', $attribute->getName()));
}
}
if ($reflector instanceof \ReflectionMethod) {
// also look at parameter attributes
foreach ($reflector->getParameters() as $rp) {
foreach ([OA\Property::class, OA\Parameter::class, OA\RequestBody::class] as $attributeName) {
foreach ($rp->getAttributes($attributeName, \ReflectionAttribute::IS_INSTANCEOF) as $attribute) {
/** @var OA\Property|OA\Parameter|OA\RequestBody $instance */
$instance = $attribute->newInstance();
$type = (($rnt = $rp->getType()) && $rnt instanceof \ReflectionNamedType) ? $rnt->getName() : Generator::UNDEFINED;
$nullable = $rnt ? $rnt->allowsNull() : true;
if ($instance instanceof OA\RequestBody) {
$instance->required = !$nullable;
} elseif ($instance instanceof OA\Property) {
if (Generator::isDefault($instance->property)) {
$instance->property = $rp->getName();
}
if (Generator::isDefault($instance->type)) {
$instance->type = $type;
}
$instance->nullable = $nullable ?: Generator::UNDEFINED;
if ($rp->isPromoted()) {
// ensure each property has its own context
$instance->_context = new Context(['generated' => true, 'annotations' => [$instance]], $context);
// promoted parameter - docblock is available via class/property
if ($comment = $rp->getDeclaringClass()->getProperty($rp->getName())->getDocComment()) {
$instance->_context->comment = $comment;
}
}
} else {
if (!$instance->name || Generator::isDefault($instance->name)) {
$instance->name = $rp->getName();
}
$instance->required = !$nullable;
$context = new Context(['nested' => $this], $context);
$context->comment = null;
$instance->merge([new OA\Schema(['type' => $type, '_context' => $context])]);
}
$annotations[] = $instance;
}
}
}
if (($rrt = $reflector->getReturnType()) && $rrt instanceof \ReflectionNamedType) {
foreach ($annotations as $annotation) {
if ($annotation instanceof OA\Property && Generator::isDefault($annotation->type)) {
// pick up simple return types
$annotation->type = $rrt->getName();
}
}
}
}
} finally {
Generator::$context = null;
}
// merge backwards into parents...
$isParent = function (OA\AbstractAnnotation $annotation, OA\AbstractAnnotation $possibleParent): bool {
// regular annotation hierarchy
$explicitParent = null !== $possibleParent->matchNested($annotation) && !$annotation instanceof OA\Attachable;
$isParentAllowed = false;
// support Attachable subclasses
if ($isAttachable = $annotation instanceof OA\Attachable) {
if (!$isParentAllowed = (null === $annotation->allowedParents())) {
// check for allowed parents
foreach ($annotation->allowedParents() as $allowedParent) {
if ($possibleParent instanceof $allowedParent) {
$isParentAllowed = true;
break;
}
}
}
}
// Attachables can always be nested (unless explicitly restricted)
return ($isAttachable && $isParentAllowed)
|| ($annotation->getRoot() !== $possibleParent->getRoot() && $explicitParent);
};
$annotationsWithoutParent = [];
foreach ($annotations as $index => $annotation) {
$mergedIntoParent = false;
for ($ii = 0; $ii < count($annotations); ++$ii) {
if ($ii === $index) {
continue;
}
$possibleParent = $annotations[$ii];
if ($isParent($annotation, $possibleParent)) {
$mergedIntoParent = true; //
$possibleParent->merge([$annotation]);
}
}
if (!$mergedIntoParent) {
$annotationsWithoutParent[] = $annotation;
}
}
return $annotationsWithoutParent;
}
}

View file

@ -0,0 +1,53 @@
<?php declare(strict_types=1);
/**
* @license Apache 2.0
*/
namespace OpenApi\Analysers;
use Composer\Autoload\ClassLoader;
/**
* Scans for classes/interfaces/traits.
*
* Relies on a <code>composer --optimized</code> run in order to utilize
* the generated class map.
*/
class ComposerAutoloaderScanner
{
/**
* Collect all classes/interfaces/traits known by composer.
*
* @param array<string> $namespaces
*
* @return array<string>
*/
public function scan(array $namespaces): array
{
$units = [];
if ($autoloader = $this->getComposerAutoloader()) {
foreach (array_keys($autoloader->getClassMap()) as $unit) {
foreach ($namespaces as $namespace) {
if (0 === strpos($unit, $namespace)) {
$units[] = $unit;
break;
}
}
}
}
return $units;
}
public static function getComposerAutoloader(): ?ClassLoader
{
foreach (spl_autoload_functions() as $fkt) {
if (is_array($fkt) && $fkt[0] instanceof ClassLoader) {
return $fkt[0];
}
}
return null;
}
}

View file

@ -0,0 +1,74 @@
<?php declare(strict_types=1);
/**
* @license Apache 2.0
*/
namespace OpenApi\Analysers;
use OpenApi\Annotations as OA;
use OpenApi\Context;
use OpenApi\Generator;
class DocBlockAnnotationFactory implements AnnotationFactoryInterface
{
use GeneratorAwareTrait;
protected ?DocBlockParser $docBlockParser = null;
public function __construct(?DocBlockParser $docBlockParser = null)
{
$this->docBlockParser = $docBlockParser ?: new DocBlockParser();
}
public function isSupported(): bool
{
return DocBlockParser::isEnabled();
}
public function setGenerator(Generator $generator): void
{
$this->generator = $generator;
$this->docBlockParser->setAliases($generator->getAliases());
}
public function build(\Reflector $reflector, Context $context): array
{
$aliases = $this->generator ? $this->generator->getAliases() : [];
if (method_exists($reflector, 'getShortName') && method_exists($reflector, 'getName')) {
$aliases[strtolower($reflector->getShortName())] = $reflector->getName();
}
if ($context->with('scanned')) {
$details = $context->scanned;
foreach ($details['uses'] as $alias => $name) {
$aliasKey = strtolower($alias);
if ($name != $alias && !array_key_exists($aliasKey, $aliases)) {
// real aliases only
$aliases[strtolower($alias)] = $name;
}
}
}
$this->docBlockParser->setAliases($aliases);
if (method_exists($reflector, 'getDocComment') && ($comment = $reflector->getDocComment())) {
$annotations = [];
foreach ($this->docBlockParser->fromComment($comment, $context) as $instance) {
if ($instance instanceof OA\AbstractAnnotation) {
$annotations[] = $instance;
} else {
if ($context->is('other') === false) {
$context->other = [];
}
$context->other[] = $instance;
}
}
return $annotations;
}
return [];
}
}

View file

@ -0,0 +1,89 @@
<?php declare(strict_types=1);
/**
* @license Apache 2.0
*/
namespace OpenApi\Analysers;
use Doctrine\Common\Annotations\DocParser;
use OpenApi\Annotations as OA;
use OpenApi\Context;
use OpenApi\Generator;
/**
* Extract swagger-php annotations from a [PHPDoc](http://en.wikipedia.org/wiki/PHPDoc) using Doctrine's DocParser.
*/
class DocBlockParser
{
protected DocParser $docParser;
/**
* @param array<string, class-string> $aliases
*/
public function __construct(array $aliases = [])
{
if (DocBlockParser::isEnabled()) {
$docParser = new DocParser();
$docParser->setIgnoreNotImportedAnnotations(true);
$docParser->setImports($aliases);
$this->docParser = $docParser;
}
}
/**
* Check if we can process annotations.
*/
public static function isEnabled(): bool
{
return class_exists('Doctrine\\Common\\Annotations\\DocParser');
}
/**
* @param array<string, class-string> $aliases
*/
public function setAliases(array $aliases): void
{
$this->docParser->setImports($aliases);
}
/**
* Use doctrine to parse the comment block and return the detected annotations.
*
* @param string $comment a T_DOC_COMMENT
*
* @return array<OA\AbstractAnnotation|object>
*/
public function fromComment(string $comment, Context $context): array
{
$context->comment = $comment;
try {
Generator::$context = $context;
if ($context->is('annotations') === false) {
$context->annotations = [];
}
return $this->docParser->parse($comment, $context->getDebugLocation());
} catch (\Exception $e) {
if (preg_match('/^(.+) at position ([0-9]+) in ' . preg_quote((string) $context, '/') . '\.$/', $e->getMessage(), $matches)) {
$errorMessage = $matches[1];
$errorPos = (int) $matches[2];
$atPos = strpos($comment, '@');
$context->line -= substr_count($comment, "\n", $atPos + $errorPos) + 1;
$lines = explode("\n", substr($comment, $atPos, $errorPos));
$context->character = strlen(array_pop($lines)) + 1; // position starts at 0 character starts at 1
$context->logger->error($errorMessage . ' in ' . $context, ['exception' => $e]);
} else {
$context->logger->error(
$e->getMessage() . ($context->filename ? ('; file=' . $context->filename) : ''),
['exception' => $e]
);
}
return [];
} finally {
Generator::$context = null;
}
}
}

View file

@ -0,0 +1,19 @@
<?php declare(strict_types=1);
/**
* @license Apache 2.0
*/
namespace OpenApi\Analysers;
use OpenApi\Generator;
trait GeneratorAwareTrait
{
protected ?Generator $generator = null;
public function setGenerator(Generator $generator): void
{
$this->generator = $generator;
}
}

View file

@ -0,0 +1,192 @@
<?php declare(strict_types=1);
/**
* @license Apache 2.0
*/
namespace OpenApi\Analysers;
use OpenApi\Analysis;
use OpenApi\Annotations as OA;
use OpenApi\Context;
use OpenApi\Generator;
use OpenApi\OpenApiException;
/**
* OpenApi analyser using reflection.
*
* Can read either PHP <code>DocBlock</code>s or <code>Attribute</code>s.
*
* Due to the nature of reflection this requires all related classes
* to be auto-loadable.
*/
class ReflectionAnalyser implements AnalyserInterface
{
use GeneratorAwareTrait;
/** @var AnnotationFactoryInterface[] */
protected array $annotationFactories = [];
/**
* @param array<AnnotationFactoryInterface> $annotationFactories
*/
public function __construct(array $annotationFactories = [])
{
foreach ($annotationFactories as $annotationFactory) {
if ($annotationFactory->isSupported()) {
$this->annotationFactories[] = $annotationFactory;
}
}
if (!$this->annotationFactories) {
throw new OpenApiException('No suitable annotation factory found. At least one of "Doctrine Annotations" or PHP 8.1 are required');
}
}
public function setGenerator(Generator $generator): void
{
$this->generator = $generator;
foreach ($this->annotationFactories as $annotationFactory) {
$annotationFactory->setGenerator($generator);
}
}
public function fromFile(string $filename, Context $context): Analysis
{
$scanner = new TokenScanner();
$fileDetails = $scanner->scanFile($filename);
$analysis = new Analysis([], $context);
foreach ($fileDetails as $fqdn => $details) {
$this->analyzeFqdn($fqdn, $analysis, $details);
}
return $analysis;
}
public function fromFqdn(string $fqdn, Analysis $analysis): Analysis
{
$fqdn = ltrim($fqdn, '\\');
$rc = new \ReflectionClass($fqdn);
if (!$filename = $rc->getFileName()) {
return $analysis;
}
$scanner = new TokenScanner();
$fileDetails = $scanner->scanFile($filename);
$this->analyzeFqdn($fqdn, $analysis, $fileDetails[$fqdn]);
return $analysis;
}
protected function analyzeFqdn(string $fqdn, Analysis $analysis, array $details): Analysis
{
if (!class_exists($fqdn) && !interface_exists($fqdn) && !trait_exists($fqdn) && (!function_exists('enum_exists') || !enum_exists($fqdn))) {
$analysis->context->logger->warning('Skipping unknown ' . $fqdn);
return $analysis;
}
$rc = new \ReflectionClass($fqdn);
$contextType = $rc->isInterface() ? 'interface' : ($rc->isTrait() ? 'trait' : ((method_exists($rc, 'isEnum') && $rc->isEnum()) ? 'enum' : 'class'));
$context = new Context([
$contextType => $rc->getShortName(),
'namespace' => $rc->getNamespaceName() ?: null,
'uses' => $details['uses'],
'comment' => $rc->getDocComment() ?: null,
'filename' => $rc->getFileName() ?: null,
'line' => $rc->getStartLine(),
'annotations' => [],
'scanned' => $details,
], $analysis->context);
$definition = [
$contextType => $rc->getShortName(),
'extends' => null,
'implements' => [],
'traits' => [],
'properties' => [],
'methods' => [],
'context' => $context,
];
$normaliseClass = fn (string $name): string => '\\' . ltrim($name, '\\');
if ($parentClass = $rc->getParentClass()) {
$definition['extends'] = $normaliseClass($parentClass->getName());
}
$definition[$contextType === 'class' ? 'implements' : 'extends'] = array_map($normaliseClass, $details['interfaces']);
$definition['traits'] = array_map($normaliseClass, $details['traits']);
foreach ($this->annotationFactories as $annotationFactory) {
$analysis->addAnnotations($annotationFactory->build($rc, $context), $context);
}
foreach ($rc->getMethods() as $method) {
if (in_array($method->name, $details['methods'])) {
$definition['methods'][$method->getName()] = $ctx = new Context([
'method' => $method->getName(),
'comment' => $method->getDocComment() ?: null,
'filename' => $method->getFileName() ?: null,
'line' => $method->getStartLine(),
'annotations' => [],
], $context);
foreach ($this->annotationFactories as $annotationFactory) {
$analysis->addAnnotations($annotationFactory->build($method, $ctx), $ctx);
}
}
}
foreach ($rc->getProperties() as $property) {
if (in_array($property->name, $details['properties'])) {
$definition['properties'][$property->getName()] = $ctx = new Context([
'property' => $property->getName(),
'comment' => $property->getDocComment() ?: null,
'annotations' => [],
], $context);
if ($property->isStatic()) {
$ctx->static = true;
}
if ($type = $property->getType()) {
$ctx->nullable = $type->allowsNull();
if ($type instanceof \ReflectionNamedType) {
$ctx->type = $type->getName();
// Context::fullyQualifiedName(...) expects this
if (class_exists($absFqn = '\\' . $ctx->type)) {
$ctx->type = $absFqn;
}
}
}
foreach ($this->annotationFactories as $annotationFactory) {
$analysis->addAnnotations($annotationFactory->build($property, $ctx), $ctx);
}
}
}
foreach ($rc->getReflectionConstants() as $constant) {
foreach ($this->annotationFactories as $annotationFactory) {
$definition['constants'][$constant->getName()] = $ctx = new Context([
'constant' => $constant->getName(),
'comment' => $constant->getDocComment() ?: null,
'annotations' => [],
], $context);
foreach ($annotationFactory->build($constant, $ctx) as $annotation) {
if ($annotation instanceof OA\Property) {
if (Generator::isDefault($annotation->property)) {
$annotation->property = $constant->getName();
}
if (Generator::isDefault($annotation->const)) {
$annotation->const = $constant->getValue();
}
$analysis->addAnnotation($annotation, $ctx);
}
}
}
}
$addDefinition = 'add' . ucfirst($contextType) . 'Definition';
$analysis->{$addDefinition}($definition);
return $analysis;
}
}

View file

@ -0,0 +1,154 @@
<?php declare(strict_types=1);
/**
* @license Apache 2.0
*/
namespace OpenApi\Analysers;
use PhpParser\Error;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\ClassLike;
use PhpParser\Node\Stmt\Enum_;
use PhpParser\Node\Stmt\Interface_;
use PhpParser\Node\Stmt\Namespace_;
use PhpParser\Node\Stmt\Trait_;
use PhpParser\Node\Stmt\Use_;
use PhpParser\ParserFactory;
/**
* High level, PHP token based, scanner.
*/
class TokenScanner
{
/**
* Scan file for all classes, interfaces and traits.
*
* @return string[][] File details
*/
public function scanFile(string $filename): array
{
$parser = (new ParserFactory())->createForNewestSupportedVersion();
try {
$stmts = $parser->parse(file_get_contents($filename));
} catch (Error $e) {
throw new \RuntimeException($e->getMessage(), $e->getCode(), $e);
}
$result = [];
$result += $this->collect_stmts($stmts, '');
foreach ($stmts as $stmt) {
if ($stmt instanceof Namespace_) {
$namespace = (string) $stmt->name;
$result += $this->collect_stmts($stmt->stmts, $namespace);
}
}
return $result;
}
protected function collect_stmts(array $stmts, string $namespace): array
{
/** @var array $uses */
$uses = [];
$resolve = function (string $name) use ($namespace, &$uses) {
if (array_key_exists($name, $uses)) {
return $uses[$name];
}
return $namespace . '\\' . $name;
};
$details = function () use (&$uses) {
return [
'uses' => $uses,
'interfaces' => [],
'traits' => [],
'enums' => [],
'methods' => [],
'properties' => [],
];
};
$result = [];
foreach ($stmts as $stmt) {
switch (get_class($stmt)) {
case Use_::class:
$uses += $this->collect_uses($stmt);
break;
case Class_::class:
$result += $this->collect_class($stmt, $details(), $resolve);
break;
case Interface_::class:
$result += $this->collect_interface($stmt, $details(), $resolve);
break;
case Trait_::class:
case Enum_::class:
$result += $this->collect_classlike($stmt, $details(), $resolve);
break;
}
}
return $result;
}
protected function collect_uses(Use_ $stmt): array
{
$uses = [];
foreach ($stmt->uses as $use) {
$uses[(string) $use->getAlias()] = (string) $use->name;
}
return $uses;
}
protected function collect_classlike(ClassLike $stmt, array $details, callable $resolve): array
{
foreach ($stmt->getProperties() as $properties) {
foreach ($properties->props as $prop) {
$details['properties'][] = (string) $prop->name;
}
}
foreach ($stmt->getMethods() as $method) {
$details['methods'][] = (string) $method->name;
}
foreach ($stmt->getTraitUses() as $traitUse) {
foreach ($traitUse->traits as $trait) {
$details['traits'][] = $resolve((string) $trait);
}
}
return [
$resolve($stmt->name->name) => $details,
];
}
protected function collect_class(Class_ $stmt, array $details, callable $resolve): array
{
foreach ($stmt->implements as $implement) {
$details['interfaces'][] = $resolve((string) $implement);
}
// promoted properties
if ($ctor = $stmt->getMethod('__construct')) {
foreach ($ctor->getParams() as $param) {
if ($param->flags) {
$details['properties'][] = $param->var->name;
}
}
}
return $this->collect_classlike($stmt, $details, $resolve);
}
protected function collect_interface(Interface_ $stmt, array $details, callable $resolve): array
{
foreach ($stmt->extends as $extend) {
$details['interfaces'][] = $resolve((string) $extend);
}
return $this->collect_classlike($stmt, $details, $resolve);
}
}

View file

@ -0,0 +1,430 @@
<?php declare(strict_types=1);
/**
* @license Apache 2.0
*/
namespace OpenApi;
use OpenApi\Annotations as OA;
/**
* Result of the analyser.
*
* Pretends to be an array of annotations, but also contains detected classes
* and helper functions for the processors.
*/
class Analysis
{
public \SplObjectStorage $annotations;
/**
* Class definitions.
*/
public array $classes = [];
/**
* Interface definitions.
*/
public array $interfaces = [];
/**
* Trait definitions.
*/
public array $traits = [];
/**
* Enum definitions.
*/
public array $enums = [];
/**
* The target OpenApi annotation.
*/
public ?OA\OpenApi $openapi = null;
public ?Context $context = null;
public function __construct(array $annotations = [], ?Context $context = null)
{
$this->annotations = new \SplObjectStorage();
$this->context = $context;
$this->addAnnotations($annotations, $context);
}
public function addAnnotation(object $annotation, Context $context): void
{
if ($this->annotations->contains($annotation)) {
return;
}
$context->ensureRoot($this->context);
if ($annotation instanceof OA\OpenApi) {
$this->openapi = $this->openapi ?: $annotation;
} else {
if ($context->is('annotations') === false) {
$context->annotations = [];
}
if (in_array($annotation, $context->annotations, true) === false) {
$context->annotations[] = $annotation;
}
}
$this->annotations->attach($annotation, $context);
$blacklist = property_exists($annotation, '_blacklist') ? $annotation::$_blacklist : [];
foreach ($annotation as $property => $value) {
if (in_array($property, $blacklist)) {
if ($property === '_unmerged') {
foreach ($value as $item) {
$this->addAnnotation($item, $context);
}
}
} elseif (is_array($value)) {
foreach ($value as $item) {
if ($item instanceof OA\AbstractAnnotation) {
$this->addAnnotation($item, $context);
}
}
} elseif ($value instanceof OA\AbstractAnnotation) {
$this->addAnnotation($value, $context);
}
}
}
public function addAnnotations(array $annotations, Context $context): void
{
foreach ($annotations as $annotation) {
$this->addAnnotation($annotation, $context);
}
}
public function addClassDefinition(array $definition): void
{
$class = $definition['context']->fullyQualifiedName($definition['class']);
$this->classes[$class] = $definition;
}
public function addInterfaceDefinition(array $definition): void
{
$interface = $definition['context']->fullyQualifiedName($definition['interface']);
$this->interfaces[$interface] = $definition;
}
public function addTraitDefinition(array $definition): void
{
$trait = $definition['context']->fullyQualifiedName($definition['trait']);
$this->traits[$trait] = $definition;
}
public function addEnumDefinition(array $definition): void
{
$enum = $definition['context']->fullyQualifiedName($definition['enum']);
$this->enums[$enum] = $definition;
}
public function addAnalysis(Analysis $analysis): void
{
foreach ($analysis->annotations as $annotation) {
$this->addAnnotation($annotation, $analysis->annotations[$annotation]);
}
$this->classes = array_merge($this->classes, $analysis->classes);
$this->interfaces = array_merge($this->interfaces, $analysis->interfaces);
$this->traits = array_merge($this->traits, $analysis->traits);
$this->enums = array_merge($this->enums, $analysis->enums);
if (!$this->openapi instanceof OA\OpenApi && $analysis->openapi instanceof OA\OpenApi) {
$this->openapi = $analysis->openapi;
}
}
/**
* Get all subclasses of the given parent class.
*
* @param string $parent the parent class
*
* @return array map of class => definition pairs of sub-classes
*/
public function getSubClasses(string $parent): array
{
$definitions = [];
foreach ($this->classes as $class => $classDefinition) {
if ($classDefinition['extends'] === $parent) {
$definitions[$class] = $classDefinition;
$definitions = array_merge($definitions, $this->getSubClasses($class));
}
}
return $definitions;
}
/**
* Get a list of all super classes for the given class.
*
* @param string $class the class name
* @param bool $direct flag to find only the actual class parents
*
* @return array map of class => definition pairs of parent classes
*/
public function getSuperClasses(string $class, bool $direct = false): array
{
$classDefinition = $this->classes[$class] ?? null;
if (!$classDefinition || empty($classDefinition['extends'])) {
// unknown class, or no inheritance
return [];
}
$extends = $classDefinition['extends'];
$extendsDefinition = $this->classes[$extends] ?? null;
if (!$extendsDefinition) {
return [];
}
$parentDetails = [$extends => $extendsDefinition];
if ($direct) {
return $parentDetails;
}
return array_merge($parentDetails, $this->getSuperClasses($extends));
}
/**
* Get the list of interfaces used by the given class or by classes which it extends.
*
* @param string $class the class name
* @param bool $direct flag to find only the actual class interfaces
*
* @return array map of class => definition pairs of interfaces
*/
public function getInterfacesOfClass(string $class, bool $direct = false): array
{
$classes = $direct ? [] : array_keys($this->getSuperClasses($class));
// add self
$classes[] = $class;
$definitions = [];
foreach ($classes as $clazz) {
if (isset($this->classes[$clazz])) {
$definition = $this->classes[$clazz];
if (isset($definition['implements'])) {
foreach ($definition['implements'] as $interface) {
if (array_key_exists($interface, $this->interfaces)) {
$definitions[$interface] = $this->interfaces[$interface];
}
}
}
}
}
if (!$direct) {
// expand recursively for interfaces extending other interfaces
$collect = function ($interfaces, $cb) use (&$definitions): void {
foreach ($interfaces as $interface) {
if (isset($this->interfaces[$interface]['extends'])) {
$cb($this->interfaces[$interface]['extends'], $cb);
foreach ($this->interfaces[$interface]['extends'] as $fqdn) {
$definitions[$fqdn] = $this->interfaces[$fqdn];
}
}
}
};
$collect(array_keys($definitions), $collect);
}
return $definitions;
}
/**
* Get the list of traits used by the given class/trait or by classes which it extends.
*
* @param string $source the source name
* @param bool $direct flag to find only the actual class traits
*
* @return array map of class => definition pairs of traits
*/
public function getTraitsOfClass(string $source, bool $direct = false): array
{
$sources = $direct ? [] : array_keys($this->getSuperClasses($source));
// add self
$sources[] = $source;
$definitions = [];
foreach ($sources as $sourze) {
if (isset($this->classes[$sourze]) || isset($this->traits[$sourze])) {
$definition = $this->classes[$sourze] ?? $this->traits[$sourze];
if (isset($definition['traits'])) {
foreach ($definition['traits'] as $trait) {
if (array_key_exists($trait, $this->traits)) {
$definitions[$trait] = $this->traits[$trait];
}
}
}
}
}
if (!$direct) {
// expand recursively for traits using other traits
$collect = function ($traits, $cb) use (&$definitions): void {
foreach ($traits as $trait) {
if (isset($this->traits[$trait]['traits'])) {
$cb($this->traits[$trait]['traits'], $cb);
foreach ($this->traits[$trait]['traits'] as $fqdn) {
$definitions[$fqdn] = $this->traits[$fqdn];
}
}
}
};
$collect(array_keys($definitions), $collect);
}
return $definitions;
}
/**
* @param class-string|array<class-string> $classes one or more class names
* @param bool $strict in non-strict mode child classes are also detected
*
* @return OA\AbstractAnnotation[]
*/
public function getAnnotationsOfType($classes, bool $strict = false): array
{
$unique = new \SplObjectStorage();
$annotations = [];
foreach ((array) $classes as $class) {
/** @var OA\AbstractAnnotation $annotation */
foreach ($this->annotations as $annotation) {
if ($annotation instanceof $class && (!$strict || ($annotation->isRoot($class) && !$unique->contains($annotation)))) {
$unique->attach($annotation);
$annotations[] = $annotation;
}
}
}
return $annotations;
}
/**
* @param string $fqdn the source class/interface/trait
*/
public function getSchemaForSource(string $fqdn): ?OA\Schema
{
return $this->getAnnotationForSource($fqdn, OA\Schema::class);
}
/**
* @template T of OA\AbstractAnnotation
*
* @param string $fqdn the source class/interface/trait
* @param class-string<T> $class
* @return T|null
*/
public function getAnnotationForSource(string $fqdn, string $class): ?OA\AbstractAnnotation
{
$fqdn = '\\' . ltrim($fqdn, '\\');
foreach ([$this->classes, $this->interfaces, $this->traits, $this->enums] as $definitions) {
if (array_key_exists($fqdn, $definitions)) {
$definition = $definitions[$fqdn];
if (is_iterable($definition['context']->annotations)) {
/** @var OA\AbstractAnnotation $annotation */
foreach (array_reverse($definition['context']->annotations) as $annotation) {
if ($annotation instanceof $class && $annotation->isRoot($class) && !$annotation->_context->is('generated')) {
return $annotation;
}
}
}
}
}
return null;
}
public function getContext(object $annotation): ?Context
{
if ($annotation instanceof OA\AbstractAnnotation) {
return $annotation->_context;
}
if ($this->annotations->contains($annotation) === false) {
throw new OpenApiException('Annotation not found');
}
$context = $this->annotations[$annotation];
if ($context instanceof Context) {
return $context;
}
throw new OpenApiException('Annotation has no context - did you use addAnnotation()/addAnnotations()');
}
/**
* Build an analysis with only the annotations that are merged into the OpenAPI annotation.
*/
public function merged(): Analysis
{
if (!$this->openapi instanceof OA\OpenApi) {
throw new OpenApiException('No openapi target set. Run the MergeIntoOpenApi processor');
}
$unmerged = $this->openapi->_unmerged;
$this->openapi->_unmerged = [];
$analysis = new Analysis([$this->openapi], $this->context);
$this->openapi->_unmerged = $unmerged;
return $analysis;
}
/**
* Analysis with only the annotations that not merged.
*/
public function unmerged(): Analysis
{
return $this->split()->unmerged;
}
/**
* Split the annotation into two analysis.
* One with annotations that are merged and one with annotations that are not merged.
*
* @return \stdClass {merged: Analysis, unmerged: Analysis}
*/
public function split()
{
$result = new \stdClass();
$result->merged = $this->merged();
$result->unmerged = new Analysis([], $this->context);
foreach ($this->annotations as $annotation) {
if ($result->merged->annotations->contains($annotation) === false) {
$result->unmerged->annotations->attach($annotation, $this->annotations[$annotation]);
}
}
return $result;
}
/**
* Apply the processor(s).
*
* @param callable|array<callable> $processors One or more processors
*/
public function process($processors = null): void
{
if (false === is_array($processors) && is_callable($processors)) {
$processors = [$processors];
}
foreach ($processors as $processor) {
$processor($this);
}
}
public function validate(): bool
{
if ($this->openapi instanceof OA\OpenApi) {
return $this->openapi->validate();
}
$this->context->logger->warning('No openapi target set. Run the MergeIntoOpenApi processor before validate()');
return false;
}
}

Some files were not shown because too many files have changed in this diff Show more