Skip to content

drmmr763/php-asyncapi-annotations

Repository files navigation

PHP AsyncAPI Annotations

A comprehensive PHP library providing annotations/attributes for the AsyncAPI 3.0.0 specification. This library enables you to define AsyncAPI specifications using modern PHP 8.3+ attributes.

Latest Stable Version Tests PHP Version License

Features

  • Complete AsyncAPI 3.0.0 Support - Full implementation of all AsyncAPI 3.0.0 objects and properties
  • Modern PHP 8.3+ - Uses PHP 8.3+ attributes with strict typing
  • Protocol Bindings - Support for all protocol-specific bindings (Kafka, MQTT, AMQP, HTTP, WebSockets, etc.)
  • Security Schemes - Complete security scheme support (OAuth2, API Keys, HTTP Auth, etc.)
  • Reusable Components - Full support for reusable components via the Components object
  • Specification Extensions - Support for custom x-* fields
  • PSR Compliant - Follows PSR-12 coding standards and PSR-4 autoloading
  • Well Tested - Comprehensive PHPUnit test suite
  • Portable - Designed to be integrated into Symfony bundles, Laravel packages, and other frameworks

Requirements

  • PHP 8.3 or higher

Installation

Install via Composer:

composer require drmmr763/php-asyncapi-annotations

Usage

Basic Example

<?php

use AsyncApi\Attributes\AsyncApi;
use AsyncApi\Attributes\Info;
use AsyncApi\Attributes\Contact;
use AsyncApi\Attributes\License;
use AsyncApi\Attributes\Server;
use AsyncApi\Attributes\Channel;
use AsyncApi\Attributes\Message;
use AsyncApi\Attributes\Schema;

#[AsyncApi(
    asyncapi: '3.0.0',
    info: new Info(
        title: 'User Service API',
        version: '1.0.0',
        description: 'API for managing user events',
        contact: new Contact(
            name: 'API Support',
            email: 'support@example.com',
            url: 'https://example.com/support'
        ),
        license: new License(
            name: 'MIT',
            url: 'https://opensource.org/licenses/MIT'
        )
    ),
    defaultContentType: 'application/json'
)]
class UserServiceApi
{
    // Your API implementation
}

Defining Servers

use AsyncApi\Attributes\Server;
use AsyncApi\Attributes\ServerVariable;
use AsyncApi\Attributes\Servers;

#[Server(
    host: '{environment}.example.com:9092',
    protocol: 'kafka',
    protocolVersion: '2.8.0',
    description: 'Kafka broker for user events',
    variables: [
        'environment' => new ServerVariable(
            enum: ['dev', 'staging', 'prod'],
            default: 'dev',
            description: 'Environment name'
        )
    ]
)]
class KafkaServer
{
}

Defining Messages

use AsyncApi\Attributes\Message;
use AsyncApi\Attributes\Schema;

#[Message(
    name: 'UserCreated',
    title: 'User Created Event',
    summary: 'Event emitted when a new user is created',
    contentType: 'application/json',
    payload: new Schema(
        type: 'object',
        required: ['id', 'email', 'createdAt'],
        properties: [
            'id' => new Schema(
                type: 'string',
                description: 'Unique user identifier',
                format: 'uuid'
            ),
            'email' => new Schema(
                type: 'string',
                description: 'User email address',
                format: 'email'
            ),
            'name' => new Schema(
                type: 'string',
                description: 'User full name'
            ),
            'createdAt' => new Schema(
                type: 'string',
                description: 'Timestamp when user was created',
                format: 'date-time'
            )
        ]
    )
)]
class UserCreatedMessage
{
}

Defining Channels and Operations

use AsyncApi\Attributes\Channel;
use AsyncApi\Attributes\Operation;
use AsyncApi\Attributes\Reference;

#[Channel(
    address: 'user.events.{eventType}',
    description: 'Channel for user-related events',
    parameters: new Parameters(
        parameters: [
            'eventType' => new Parameter(
                description: 'Type of user event',
                enum: ['created', 'updated', 'deleted']
            )
        ]
    )
)]
class UserEventsChannel
{
}

#[Operation(
    action: 'send',
    channel: new Reference(ref: '#/channels/userEvents'),
    summary: 'Send user events',
    messages: [
        new Reference(ref: '#/components/messages/UserCreated')
    ]
)]
class SendUserEvent
{
}

Using Security Schemes

use AsyncApi\Attributes\SecurityScheme;
use AsyncApi\Attributes\OAuthFlows;
use AsyncApi\Attributes\OAuthFlow;

#[SecurityScheme(
    type: 'oauth2',
    description: 'OAuth2 authentication',
    flows: new OAuthFlows(
        authorizationCode: new OAuthFlow(
            authorizationUrl: 'https://example.com/oauth/authorize',
            tokenUrl: 'https://example.com/oauth/token',
            scopes: [
                'read:users' => 'Read user information',
                'write:users' => 'Create and update users'
            ]
        )
    )
)]
class OAuth2Security
{
}

Using Components for Reusability

use AsyncApi\Attributes\Components;

#[Components(
    schemas: [
        'User' => new Schema(
            type: 'object',
            properties: [
                'id' => new Schema(type: 'string', format: 'uuid'),
                'email' => new Schema(type: 'string', format: 'email'),
                'name' => new Schema(type: 'string')
            ]
        )
    ],
    messages: [
        'UserCreated' => new Message(
            payload: new Reference(ref: '#/components/schemas/User')
        )
    ]
)]
class ApiComponents
{
}

Available Annotations

Core Objects

  • AsyncApi - Root document object
  • Info - API metadata
  • Contact - Contact information
  • License - License information
  • Server - Server/broker definition
  • ServerVariable - Server URL template variable
  • Servers - Collection of servers
  • Channel - Communication channel
  • Channels - Collection of channels
  • Operation - Send/receive operation
  • Operations - Collection of operations
  • OperationTrait - Reusable operation properties
  • OperationReply - Request/reply pattern response
  • OperationReplyAddress - Reply address specification
  • Message - Message definition
  • Messages - Collection of messages
  • MessageTrait - Reusable message properties
  • MessageExample - Message example
  • Parameter - Channel parameter
  • Parameters - Collection of parameters
  • Components - Reusable components

Schema Objects

  • Schema - JSON Schema Draft 07 superset
  • MultiFormatSchema - Multi-format schema support (Avro, etc.)

Supporting Objects

  • Tag - Metadata tag
  • ExternalDocumentation - External documentation reference
  • Reference - Component reference ($ref)
  • CorrelationId - Message correlation identifier

Bindings Objects

  • ServerBindings - Protocol-specific server configuration
  • ChannelBindings - Protocol-specific channel configuration
  • OperationBindings - Protocol-specific operation configuration
  • MessageBindings - Protocol-specific message configuration

Security Objects

  • SecurityScheme - Security scheme definition
  • OAuthFlows - OAuth flow configurations
  • OAuthFlow - Individual OAuth flow

Supported Protocols

The library supports bindings for all AsyncAPI protocols:

  • HTTP
  • WebSockets
  • Kafka
  • AMQP 0-9-1
  • AMQP 1.0
  • MQTT
  • MQTT 5
  • NATS
  • JMS
  • SNS
  • SQS
  • STOMP
  • Redis
  • Solace
  • Mercure
  • IBM MQ
  • Google Pub/Sub
  • Pulsar
  • Anypoint MQ

Development

Running Tests

composer test

Code Quality

# Run all quality checks
composer quality

# Individual checks
composer phpstan      # Static analysis
composer cs:check     # Code style check
composer cs:fix       # Fix code style
composer phpmd        # Mess detector

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This library is licensed under the MIT License. See the LICENSE file for details.

Credits

Links

About

PHP Annotations for AsyncAPI

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages