PHP code example of ironcurtaindev / easy-doc

1. Go to this page and download the library: Download ironcurtaindev/easy-doc library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

ironcurtaindev / easy-doc example snippets


// config/easy-doc.php
'auto_discover_models' => true,
'model_path' => app_path('Models'),

// config/easy-doc.php
'auth_headers' => [
    [
        'name' => 'x-api-key',
        'type' => 'api_key',
        'description' => 'API Key for authentication',
        'uired' => true,
        'example' => 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...',
    ],
],

#[DocAPI(
    name: 'Get User Profile',
    headers: ['x-api-key', 'x-access-token']  // Uses config headers
)]

->setHeaders(['x-api-key', 'x-access-token'])
// or
->withConfigHeaders(['x-api-key', 'x-access-token'])

// config/easy-doc.php
'default_headers' => [
    ['name' => 'Accept', 'value' => 'application/json', 'description' => 'Response content type'],
    ['name' => 'Content-Type', 'value' => 'application/json', 'description' => 'Request content type'],
],

// AuthController.php

public function register(Request $request) {
    document(function() {
        return (new APICall())
            ->setName('Register User')
            ->setGroup('Authentication')
            ->setParams([
                Param::make('name', Param::TYPE_STRING, 'Full name')->sword')->

// PartnerController.php

public function show(Request $request) {
    document(function() {
        return (new APICall())
            ->setName('Get Partner')
            ->setGroup('Partner')
            ->addHeader(
                Param::header('Authorization', 'Bearer token')->example('Bearer eyJ...')
            )
            // Automatically documents the response based on the Partner model schema
            ->setSuccessObject(Partner::class)
            ->setErrorExample(['result' => false, 'message' => 'Not found'], 404, 'No partner found');
    });

    // ... logic
}

// PlaceController.php

public function index(Request $request) {
    document(function() {
        return (new APICall())
            ->setName('List Places')
            ->setGroup('Places')
            ->addHeader(Param::header('Authorization', 'Bearer token'))
            // Documents a paginated list of Place models
            ->setSuccessPaginatedObject(Place::class)
            ->setSuccessExample([/* ... example JSON ... */], 200, 'Places list');
    });

    $places = $request->user()->places()->paginate(10);
    return response()->apiSuccessPaginated($places);
}

use EasyDoc\Attributes\DocAPI;
use EasyDoc\Attributes\DocParam;
use EasyDoc\Attributes\DocHeader;
use EasyDoc\Attributes\DocResponse;

#[DocAPI(
    name: 'Login User',
    group: 'Authentication',
    description: 'Authenticate user with email and password, returns access token',
    successObject: User::class,
    tags: ['auth', 'login'],
    possibleErrors: [401 => 'Unauthorized', 422 => 'Validation Error']
)]
#[DocHeader(name: 'api_key', description: 'API Key for authentication')]
#[DocHeader(name: 'x-access-token', description: 'Access token', rue
)]
public function login(Request $request)
{
    // Only business logic here - no documentation code!
    $validated = $request->validate([
        'email' => '

use EasyDoc\Attributes\DocRequest;
use App\Http\Requests\RegisterRequest;

#[DocAPI(name: 'Register', group: 'Auth')]
#[DocRequest(RegisterRequest::class)] // <--- Magic happens here!
public function register(RegisterRequest $request)
{
    // ...
}

#[DocAPI(
    // Basic Information
    name: 'Login User',                      // Endpoint name
    group: 'Authentication',                 // Group/category
    description: 'Authenticate user...',     // Detailed description
    version: '1.0.0',                        // API version
    operationId: 'loginUser',                // Custom OpenAPI operation ID

    // Response Configuration
    successObject: User::class,              // Model class for response schema
    successPaginatedObject: Place::class,    // Model class for paginated response
    successMessageOnly: false,               // Response is just a message (no payload)
    successParams: [                         // Custom success response fields
        ['name' => 'token', 'type' => 'string', 'description' => 'Auth token']
    ],

    // Schema References
    successSchema: 'UserResponse',           // Custom success schema name
    errorSchema: 'ErrorResponse',            // Custom error schema name

    // Metadata
    tags: ['auth', 'login'],                 // Additional categorization
    deprecated: 'Use /v2/login instead',     // Deprecation message (null if active)
    rateLimit: ['limit' => 60, 'period' => 'minute'],  // Rate limiting info
    consumes: ['application/json'],          // Content types accepted

    // Headers & Parameters
    headers: ['api_key', 'x-access-token'],  // Config header names to 

#[DocParam(
    name: 'age',                    // Parameter name
    type: 'integer',                // Type: string, integer, number, boolean, array, file
    description: 'User age',        // Description
    example: 25,                    // Example value
    / Regex pattern
    location: 'body'                // body, query, or path
)]

#[DocHeader(
    name: 'Authorization',          // Header name
    description: 'Bearer token',    // Description
    example: 'Bearer eyJ...',       // Example value
    

#[DocResponse(
    status: 200,                    // HTTP status code
    description: 'Success',         // Response description
    example: ['result' => true],    // Example response body
    isError: false                  // Is this an error response?
)]

use EasyDoc\Attributes\DocAPI;
use EasyDoc\Attributes\DocParam;
use EasyDoc\Attributes\DocResponse;

#[DocAPI(
    name: 'Register User',
    group: 'Authentication',
    description: 'Create a new user account and return an authentication token. The user will be immediately logged in and can use the returned token for subsequent API requests.',
    successObject: User::class,
    version: '1.0.0',
    operationId: 'registerUser',
    tags: ['auth', 'registration', 'public'],
    consumes: ['application/json'],
    successParams: [
        ['name' => 'token', 'type' => 'string', 'description' => 'JWT authentication token'],
        ['name' => 'token_type', 'type' => 'string', 'description' => 'Token type (Bearer)']
    ],
    possibleErrors: [
        422 => 'Validation Error - Invalid input data',
        500 => 'Server Error - Failed to create user'
    ],
    rateLimit: ['limit' => 5, 'period' => 'minute'],
    requestExample: [
        'name' => 'John Doe',
        'email' => '[email protected]',
        'password' => 'secret123',
        'password_confirmation' => 'secret123'
    ]
)]
#[DocParam(
    name: 'name',
    type: 'string',
    description: 'Full name of the user',
    example: 'John Doe',
     been taken.']],
    ],
    isError: true
)]
public function register(Request $request)
{
    // Clean controller - only business logic!
}

use EasyDoc\Traits\ApiResponses;

class AuthController extends Controller
{
    use ApiResponses;

    public function login()
    {
        // ...
        return $this->apiSuccess(['token' => '...']);
    }
}

use EasyDoc\Contracts\HasExtraApiColumns;

class User extends Authenticatable implements HasExtraApiColumns
{
    /**
     * Define extra API columns for Swagger documentation.
     */
    public function addExtraAPIColumns(): array
    {
        return [
            // Simple type
            'token' => type('string')
                ->description('Authentication token')
                ->nullable(),

            // Relationship (Array of Models)
            'places' => type('array')
                ->description('User places')
                ->of(Place::class), // Links to Place schema

            // Relationship (Single Model)
            'partner' => type('object')
                ->description('User partner')
                ->model(Partner::class)
                ->nullable(),
        ];
    }
}

Param::make('age', Param::TYPE_INT)
    ->min(18)           // Minimum value
    ->max(100)          // Maximum value
    ->optional()        // Mark as optional
    ->description('User age');

Param::make('role', Param::TYPE_STRING)
    ->enum(['admin', 'user', 'guest']) // Enum validation
    ->defaultValue('user');

Param::make('zip_code', Param::TYPE_STRING)
    ->pattern('^\d{5}(?:[-\s]\d{4})?$') // Regex validation
    ->example('90210');

document(function() {
    return (new APICall())
        ->setName('Upload Avatar')
        ->setMethod('POST')
        ->setConsumes(['multipart/form-data']) // Important!
        ->setParams([
            Param::make('avatar', Param::TYPE_FILE, 'Profile picture')
                ->

    'output' => [
        'typescript' => [
            'enabled' => true,
            'file' => 'types.ts', // Generates to public/docs/types.ts
        ],
    ],
    

// config/easy-doc.php
'response_wrapper' => [
    'success' => true,
    'data' => '__DATA__', // The placeholder for your actual response
    'meta' => '__META__',
],

// config/easy-doc.php
'servers' => [
    ['url' => 'http://localhost/api/v1', 'description' => 'Local Dev'],
    ['url' => 'https://staging.api.com/v1', 'description' => 'Staging'],
    ['url' => 'https://api.com/v1', 'description' => 'Production'],
],

(new APICall())
    ->name('Legacy Endpoint')
    ->deprecated('Use /new-api instead') // Marks as deprecated
    ->rateLimit(60, 'minute'); // Documents 60 req/min limit

use EasyDoc\Attributes\DocGroup;
use EasyDoc\Attributes\DocAPI;

#[DocGroup(
    group: 'Authentication',
    version: '1.0.0',
    tags: ['auth'],
    consumes: ['application/json'],
    headers: ['x-api-key'],            // All methods get this header
    possibleErrors: [401 => 'Unauthenticated']  // Common errors
)]
class AuthController extends Controller
{
    #[DocAPI(name: 'Login')]  // Inherits group, version, tags from DocGroup
    public function login() { }

    #[DocAPI(name: 'Logout')]  // Also inherits all DocGroup settings
    public function logout() { }
}

// config/easy-doc.php
'error_presets' => [
    'validation' => [
        'status' => 422,
        'description' => 'Validation Error',
        'example' => ['result' => false, 'message' => 'The given data was invalid.'],
    ],
    'unauthenticated' => [
        'status' => 401,
        'description' => 'Unauthenticated',
        'example' => ['result' => false, 'message' => 'Unauthenticated.'],
    ],
    'not_found' => [
        'status' => 404,
        'description' => 'Not Found',
        'example' => ['result' => false, 'message' => 'Resource not found.'],
    ],
],

use EasyDoc\Attributes\DocError;

#[DocAPI(name: 'Update User')]
#[DocError('validation')]      // Uses 422 preset
#[DocError('unauthenticated')] // Uses 401 preset
#[DocError('not_found')]       // Uses 404 preset
public function update(Request $request, User $user) { }

// config/easy-doc.php
'param_templates' => [
    'email' => [
        'type' => 'string',
        'description' => 'Email address',
        'example' => '[email protected]',
        ' => 'secret123',
        '

// Instead of this:
#[DocParam(name: 'email', type: 'string', description: 'Email address', example: '[email protected]',  Just write this:
#[DocParam(template: 'email')]
#[DocParam(template: 'password')]
public function login(Request $request) { }

// Use template but override specific values
#[DocParam(template: 'email', description: 'Admin email address')]

#[DocAPI(
    name: 'Login',
    group: 'Authentication',
    version: '1.0.0',
    tags: ['auth'],
    consumes: ['application/json']
)]
#[DocParam(name: 'email', type: 'string', description: 'Email', example: '[email protected]')]
#[DocParam(name: 'password', type: 'string', description: 'Password', example: 'secret123', min: 8)]
#[DocResponse(status: 422, description: 'Validation Error',
    example: ['result' => false, 'message' => 'Invalid data'], isError: true)]
#[DocResponse(status: 401, description: 'Unauthenticated',
    example: ['result' => false, 'message' => 'Unauthenticated.'], isError: true)]
public function login() { }

#[DocGroup(group: 'Authentication', version: '1.0.0', tags: ['auth'])]
class AuthController extends Controller
{
    #[DocAPI(name: 'Login')]
    #[DocParam(template: 'email')]
    #[DocParam(template: 'password')]
    #[DocError('validation')]
    #[DocError('unauthenticated')]
    public function login() { }
}
bash
php artisan vendor:publish --provider="EasyDoc\EasyDocServiceProvider"
bash
php artisan easy-doc:generate --markdown --openapi3 --sdk
bash
php artisan easy-doc:cache
bash
php artisan easy-doc:clear