Skip to content

Commit

Permalink
🚀 first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
waadmawlood committed Jan 30, 2025
0 parents commit e01bd78
Show file tree
Hide file tree
Showing 16 changed files with 389 additions and 0 deletions.
Binary file added .DS_Store
Binary file not shown.
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
vendor/
node_modules/
*.log
*.lock
.phpunit.result.cache
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2025 Waad Mawlood

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

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

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

![Logo](banner.jpg)

A Laravel package that seamlessly integrates with [Dedoc Scramble](https://github.com/dedoc/scramble) to automatically generate Swagger/OpenAPI documentation for your APIs and support multiple versions of your API. No manual documentation required - your API endpoints are documented based on your route definitions and code.

> :warning: This package depends on [Dedoc Scramble](https://github.com/dedoc/scramble).
## Requirements

- Laravel 10.x or higher
- PHP 8.1 or higher

## Installation

```bash
composer require waad/scramble-swagger
```
```bash
php artisan vendor:publish --provider "Waad\ScrambleSwagger\ScrambleSwaggerServiceProvider"
```

## Usage

1. Configure the `config/scramble.php` and `config/scramble-swagger.php` files.
2. Open URL Swagger documentation `/docs/swagger` depend on `scramble-swagger.url`.


## Main Features

- All Features of [Dedoc Scramble](https://github.com/dedoc/scramble).
- Support multiple versions of your API.
- Use Swagger UI v5.18.3
- Use OAS 3.1.0

## License

Package is open-source software licensed under the [MIT license](LICENSE.md).



Binary file added banner.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
47 changes: 47 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
{
"name": "waad/scramble-swagger",
"description": "A Laravel package for generating Swagger/OpenAPI documentation",
"type": "library",
"keywords": ["laravel", "swagger", "openapi", "api", "documentation", "scramble"],
"license": "MIT",
"authors": [
{
"name": "Waad Mawlood",
"email": "[email protected]"
}
],
"require": {
"php": "^8.1",
"dedoc/scramble": "^0.11",
"laravel/framework": "^10.0|^11.0"
},
"require-dev": {
"laravel/pint": "^1.20",
"orchestra/testbench": "^8.0|^9.0",
"pestphp/pest-plugin-laravel": "^2.2"
},
"autoload": {
"psr-4": {
"Waad\\ScrambleSwagger\\": "src/"
}
},
"extra": {
"laravel": {
"providers": [
"Waad\\ScrambleSwagger\\ScrambleSwaggerServiceProvider"
]
}
},
"config": {
"sort-packages": true,
"allow-plugins": {
"pestphp/pest-plugin": true
}
},
"minimum-stability": "dev",
"prefer-stable": true,
"scripts": {
"lint": "vendor/bin/pint",
"test": "vendor/bin/pest"
}
}
43 changes: 43 additions & 0 deletions src/Commands/GenerateScrambleSwagger.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php

namespace Waad\ScrambleSwagger\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;

class GenerateScrambleSwagger extends Command
{
protected $signature = 'scramble:swagger:auto';

protected $description = 'Generate Scramble Swagger documentation and copy paths to components';

public function handle()
{
$path = public_path('scramble-swagger/doc.json');
Artisan::call('scramble:export', ['--path' => $path]);

$this->copyPathsToComponents($path);

return Command::SUCCESS;
}

private function copyPathsToComponents($filePath)
{
$jsonContent = file_get_contents($filePath);
$swaggerData = json_decode($jsonContent, true);

if ($swaggerData === null) {
throw new \Exception("Error decoding JSON from file: $filePath");
}

if (isset($swaggerData['paths'])) {
$swaggerData['components']['paths'] = $swaggerData['paths'];
} else {
throw new \Exception("No 'paths' key found in the JSON.");
}

file_put_contents($filePath, json_encode($swaggerData));

return $filePath;
}
}
95 changes: 95 additions & 0 deletions src/Controllers/ScrambleSwaggerController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
<?php

namespace Waad\ScrambleSwagger\Controllers;

use Illuminate\Support\Facades\Artisan;
use Waad\ScrambleSwagger\Commands\GenerateScrambleSwagger;

class ScrambleSwaggerController
{
public function __construct()
{
if (! config('scramble-swagger.enable')) {
abort(404);
}
}

public function show()
{
$response = $this->responseJson();
$versions = $this->getApiVersions();

return view('scramble-swagger::docs', compact('response', 'versions'));
}

public function responseJson()
{
$status = Artisan::call(GenerateScrambleSwagger::class);
if ($status !== 0) {
throw new \Exception('Failed to generate Swagger documentation');
}

$filePath = public_path('scramble-swagger/doc.json');
if (! file_exists($filePath)) {
return [];
}

$jsonContent = file_get_contents($filePath);
$data = json_decode($jsonContent, true);

if (empty($data)) {
return [];
}

return request()->filled('version') ? $this->filterByVersion($data) : $data;
}

private function getApiVersions()
{
$config = config('scramble-swagger');
$configVersions = $config['versions'];

if (empty($configVersions)) {
return ['all'];
}

$versions = [];
foreach ($configVersions as $version) {
$versions[] = [
'url' => url(sprintf('%s/json?version=%s', $config['url'], $version)),
'name' => $version,
];
}

return [
'default' => $config['default_version'] ?? $configVersions[0] ?? 'all',
'versions' => $versions,
];
}

public function filterByVersion($dataJson)
{
$searchTerm = request()->version;
if ($searchTerm === 'all' || is_null($searchTerm)) {
return $dataJson;
}

$paths = [];
$tags = [];
foreach ($dataJson['components']['paths'] as $key => $path) {
if (! str_contains($key, $searchTerm)) {
continue;
}

$paths[$key] = $dataJson['components']['paths'][$key];
foreach ($path as $path_value) {
$tags[] = $path_value['tags'][0] ?? '';
}
}

$dataJson['components']['paths'] = $dataJson['paths'] = $paths;
$dataJson['components']['tags'] = $dataJson['tags'] = array_unique(array_filter($tags));

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

namespace Waad\ScrambleSwagger;

use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\ServiceProvider;
use Waad\ScrambleSwagger\Commands\GenerateScrambleSwagger;

class ScrambleSwaggerServiceProvider extends ServiceProvider
{
/**
* Register services.
*/
public function register()
{
$this->mergeConfigFrom(__DIR__.'/config/scramble-swagger.php', 'scramble-swagger');
$this->commands([
GenerateScrambleSwagger::class,
]);
}

/**
* Bootstrap services.
*/
public function boot()
{
if ($this->app->runningInConsole()) {
$this->publishes([
__DIR__.'/config/scramble-swagger.php' => config_path('scramble-swagger.php'),
], 'scramble-swagger-config');

$this->publishes([
__DIR__.'/scramble-swagger' => public_path('scramble-swagger'),
], 'scramble-swagger-assets');

Artisan::call('vendor:publish', [
'--provider' => "Dedoc\Scramble\ScrambleServiceProvider",
'--tag' => 'scramble-config',
]);
}

$this->loadViewsFrom(__DIR__.'/views', 'scramble-swagger');
$this->loadRoutesFrom(__DIR__.'/routes/web.php');
}
}
25 changes: 25 additions & 0 deletions src/config/scramble-swagger.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

return [

/*
* Enable Swagger
*/
'enable' => env('SCRAMBLE_SWAGGER_ENABLED', true),

/*
* API URL
*/
'url' => env('SCRAMBLE_SWAGGER_URL', 'docs/swagger'),

/*
* API Versions
*/
'versions' => [
'all',
// "v1",
],

'default_version' => 'all',

];
9 changes: 9 additions & 0 deletions src/routes/web.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

use Illuminate\Support\Facades\Route;
use Waad\ScrambleSwagger\Controllers\ScrambleSwaggerController;

Route::prefix(config('scramble-swagger.url'))->group(function () {
Route::get('/', [ScrambleSwaggerController::class, 'show'])->name('scramble-swagger.show');
Route::get('/json', [ScrambleSwaggerController::class, 'responseJson'])->name('scramble-swagger.responseJson');
});
1 change: 1 addition & 0 deletions src/scramble-swagger/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
doc.json
1 change: 1 addition & 0 deletions src/scramble-swagger/css/swagger-ui.css

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions src/scramble-swagger/js/swagger-ui-bundle.js

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions src/scramble-swagger/js/swagger-ui-standalone-preset.js

Large diffs are not rendered by default.

52 changes: 52 additions & 0 deletions src/views/docs.blade.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{ config('app.name') }}</title>
<link rel="stylesheet" href="{{ asset('scramble-swagger/css/swagger-ui.css') }}">
<style>
.swagger-ui .info { margin: 15px 0; }
.swagger-ui .scheme-container { padding: 5px 0 15px; }
</style>
</head>

<body>
<div id="scramble-swagger-ui"></div>

<script src="{{ asset('scramble-swagger/js/swagger-ui-bundle.js') }}"></script>
<script src="{{ asset('scramble-swagger/js/swagger-ui-standalone-preset.js') }}"></script>

<script>
window.onload = function() {
window.ui = SwaggerUIBundle({
urls: [
@foreach ($versions['versions'] as $version)
{
url: '{{ $version['url'] }}',
name: '{{ $version['name'] }}',
},
@endforeach
],
"urls.primaryName": "{{ $versions['default'] }}",
dom_id: '#scramble-swagger-ui',
deepLinking: true,
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
layout: 'StandaloneLayout',
requestInterceptor: (request) => {
request.headers['accept'] = 'application/json';
return request;
},
responseInterceptor: (response) => {
response.headers['content-type'] = 'application/json';
response.headers['accept'] = 'application/json';
return response;
}
});
};
</script>
</body>
</html>

0 comments on commit e01bd78

Please sign in to comment.