VOOZH about

URL: https://deepwiki.com/mathsgod/light

⇱ mathsgod/light | DeepWiki


Loading...
Last indexed: 31 January 2026 (cf9511)
Menu

Overview

Purpose and Scope

Light is a PHP framework for building GraphQL APIs with integrated authentication, authorization, file management, and audit capabilities. It provides a code-first GraphQL API layer built on GraphQLite, a comprehensive security system with multiple authentication methods and role-based access control (RBAC), cloud-agnostic file storage via Flysystem, and automatic audit trail generation for all data operations.

This page provides a high-level introduction to the Light framework's architecture, capabilities, and technology stack. For detailed information on specific subsystems, see:

Sources: composer.json1-65 Diagram 1 (Overall System Architecture), Diagram 2 (HTTP Request Processing Pipeline)


Framework Purpose

Light solves the common requirement of building secure, auditable web APIs by providing pre-built, integrated solutions for:

  1. GraphQL API development - Code-first schema generation from PHP classes using annotations
  2. Multi-factor authentication - Password, TOTP 2FA, WebAuthn, and OAuth (Google/Microsoft/Facebook)
  3. Granular authorization - Role-based access control with field-level permission checking
  4. File management - Unified interface for local and cloud storage (S3, Aliyun OSS)
  5. Audit compliance - Automatic tracking of all data changes with before/after snapshots
  6. Rapid development - CLI-based code generation from database schema definitions

The framework is designed for applications requiring enterprise-grade security and compliance features without the overhead of implementing these systems from scratch.

Sources: composer.json10-36 Diagram 1 (Overall System Architecture), Diagram 3 (Authentication, Authorization, and Session Management System)


Technology Stack

Light is built on modern PHP libraries following PSR standards:

ComponentLibraryPurpose
GraphQL Enginethecodingmachine/graphqliteCode-first GraphQL schema generation
HTTP Layerlaminas/laminas-stratigilityPSR-15 middleware pipeline
Databaselaminas/laminas-dbSQL abstraction over MySQL
File Storageleague/flysystemMulti-backend filesystem abstraction
Authenticationfirebase/php-jwtJWT token generation and validation
Authorizationmathsgod/light-rbacRole-based access control
Dependency Injectionleague/containerPSR-11 container with autowiring
Cachingsymfony/cachePSR-6/PSR-16 cache implementations
CLIsymfony/consoleCommand-line interface framework
2FA/QR Codesendroid/qr-codeTOTP QR code generation
WebAuthnweb-auth/webauthn-libBiometric authentication
Serializationsymfony/serializerObject transformation for GraphQL

Sources: composer.json10-36


Core Components Architecture

The following diagram maps Light's major system components to their implementation classes:


Sources: Diagram 1 (Overall System Architecture), src/App.php1-500 src/Type/App.php1-200


Request Processing Flow

Light processes HTTP requests through a multi-stage pipeline:


Key Processing Stages:

  1. Middleware Pipeline - Laminas Stratigility processes PSR-15 middleware stack
  2. Request Parsing - Light\App::process() extracts GraphQL operations and file uploads
  3. Authentication - Auth\Service validates JWT tokens and loads user context
  4. GraphQL Execution - webonyx/graphql-php executes query against GraphQLite schema
  5. Authorization - Light\Rbac checks @Right and @Logged annotations on fields
  6. Response Serialization - Results converted to JSON with optional debug information

Sources: Diagram 2 (HTTP Request Processing Pipeline), src/App.php1-500 src/Auth/Service.php1-200


Main Capabilities

1. GraphQL API Generation

Light uses GraphQLite's annotation-based approach to generate GraphQL schemas from PHP classes:

  • Code-First Schema - @Type, @Field, @Query, @Mutation annotations define GraphQL types
  • Automatic Type Mapping - PHP classes automatically mapped to GraphQL object types
  • Input Validation - @Factory methods provide input validation and transformation
  • Custom Scalars - Support for mixed types, DateTime, JSON via type mappers

Key Classes:

  • Light\Type\App - Root query type exposing system-level queries
  • Light\Controller\* - GraphQL controllers implementing mutations
  • Schema configuration in Light\App::__construct()

Sources: src/Type/App.php1-200 src/Controller/AuthController.php1-400 Diagram 5 (GraphQL API Structure)


2. Multi-Factor Authentication

Supports four authentication methods with unified JWT token generation:

MethodImplementationStorage
Passwordpassword_hash() with bcryptUser.password field
TOTP 2FARFC 6238 time-based codesUser.totp_secret field
WebAuthnFIDO2 biometric/security keysUserAuthenticator table
OAuthGoogle, Microsoft, FacebookUser.google_id, User.microsoft_id, User.facebook_id

JWT Token System:

  • Access Tokens - Short-lived (default 15 minutes) for API requests
  • Refresh Tokens - Long-lived (default 7 days) for token renewal
  • Storage - HTTP-only, partitioned cookies with SameSite protection
  • Revocation - Cache-based immediate revocation via revoked_token_{jti} keys

Key Classes:

  • Light\Controller\AuthController - Authentication mutations
  • Auth\Service - JWT validation and user context
  • Light\Model\User - User identity and credentials
  • Light\Model\UserLog - Session tracking with JTI

Sources: src/Controller/AuthController.php1-400 src/Auth/Service.php1-200 src/Model/User.php1-300 Diagram 3 (Authentication, Authorization, and Session Management System)


3. Role-Based Access Control (RBAC)

Granular permission system with multiple enforcement points:

  • Role Hierarchy - Defined in permissions.yml with inheritance support
  • Database Roles - Role, Permission, UserRole models for runtime management
  • Field-Level Authorization - @Right("permission.name") annotations on GraphQL fields
  • Authentication Check - @Logged annotation requires valid session
  • Menu-Based Permissions - menus.yml defines navigation with permission requirements
  • Permission Discovery - Automatic scanning of @Right annotations across codebase

Permission Checking Flow:

  1. GraphQLite schema factory encounters @Right annotation
  2. Calls Light\Rbac::isAllowed() with user and permission
  3. Checks user's roles against permission mappings
  4. Returns boolean result or throws authorization error

Key Classes:

  • Light\Rbac - Core RBAC engine
  • Light\Model\Role, Light\Model\Permission - Database models
  • Light\Type\App::getPermissions() - Permission discovery query

Sources: src/Rbac.php1-200 src/Model/Role.php1-100 src/Model/Permission.php1-100 permissions.yml1-50 Diagram 3 (Authentication, Authorization, and Session Management System)


4. Multi-Backend File Storage

Cloud-agnostic file system abstraction using Flysystem's MountManager:

Supported Backends:

  • Local Filesystem - league/flysystem-local
  • Amazon S3 - league/flysystem-aws-s3-v3
  • Aliyun OSS - alphasnow/aliyun-oss-flysystem
  • Hostlink Storage - hostlink/hostlink-storage-adapter

File System Features:

  • Unified API - Common interface across all storage backends
  • Location String Parsing - Format: {filesystem}://{path}
  • Node Abstraction - Light\Filesystem\Node interface for files and folders
  • Security - Extension blacklist (65 prohibited types), hidden file prevention
  • Events - Pre-operation hooks for validation (FileUploading, FolderCreating, etc.)
  • Configuration - JSON storage in Config.fs field with filesystem credentials

Key Classes:

  • Light\Filesystem\Node - File/folder interface
  • Light\Filesystem\Drive - Filesystem wrapper
  • Light\Controller\FileSystemController - File operation mutations
  • League\Flysystem\MountManager - Multi-backend coordinator

Sources: src/Filesystem/Node.php1-200 src/Filesystem/Drive.php1-150 src/Controller/FileSystemController.php1-500 Diagram 6 (File System and Storage Architecture)


5. Automatic Audit Trails

Comprehensive revision tracking for all data operations:

Audit Mechanism:

  • Lifecycle Hooks - Light\Model::save() and Light\Model::delete() intercepted
  • Automatic Timestamps - created_time, updated_time populated on save
  • User Tracking - created_by, updated_by populated from authenticated user
  • State Snapshots - Before/after states stored in EventLog table
  • Revision Types:
    • Insert - Captures new state in target field
    • Update - Captures old state in source, new state in target
    • Delete - Captures final state in source field before removal

Audit Trail Features:

  • Immutable History - Foreign key uses SET NULL ON DELETE to preserve logs
  • Field-Level Restoration - RevisionController can restore individual fields
  • Query Interface - GraphQL queries for revision history by table/record
  • Diff Visualization - Sebastian\Diff integration for change comparison

Key Classes:

  • Light\Model - Base model with audit hooks
  • Light\Model\EventLog - Audit trail storage
  • Light\Controller\RevisionController - Revision queries and restoration

Sources: src/Model.php1-300 src/Model/EventLog.php1-150 src/Controller/RevisionController.php1-200 Diagram 4 (Data Persistence and Audit Architecture)


6. CLI-Driven Development

Symfony Console-based CLI tool for rapid development:

Code Generation Commands:

  • bin/light make:model - Generate model classes from db.json schema
  • bin/light make:controller - Generate GraphQL controller boilerplate
  • bin/light make:input - Generate input type classes for mutations
  • bin/light make:ts - Generate TypeScript type definitions

Database Management:

  • bin/light db:install - Execute schema DDL from db.json
  • Schema migration via mathsgod/mysql-schema-migrate
  • DDL generation via mathsgod/json-to-sql

Schema-Driven Development Flow:

  1. Define database schema in db.json (tables, columns, relationships)
  2. Run db:install to create/update database tables
  3. Run make:model to generate PHP model classes with typed properties
  4. Run make:controller to generate GraphQL CRUD operations
  5. Run make:ts to generate frontend TypeScript definitions

Sources: bin/light1-50 src/Command/*1-100 Diagram 5 (GraphQL API Structure and Code Generation)


System Entry Points

Light can be accessed through two primary entry points:

HTTP Server Entry Point

PSR-15 middleware-based HTTP server using Laminas components:


Implementation:

  • Light\Server class wraps Laminas HTTP handler runner
  • Implements PSR-15 middleware pattern via Stratigility
  • Light\App implements both MiddlewareInterface and RequestHandlerInterface
  • Processes GraphQL queries at /graphql endpoint
  • Serves refresh tokens at /refresh_token endpoint

Sources: src/Server.php1-100 Diagram 2 (HTTP Request Processing Pipeline)


CLI Entry Point

Symfony Console application for development and maintenance:


Implementation:

  • Entry script: bin/light
  • Symfony Console application with custom commands
  • Same Light\App instance provides dependency injection
  • Direct database and filesystem access for code generation

Sources: bin/light1-50 Diagram 5 (GraphQL API Structure and Code Generation)


Configuration Management

Light uses a multi-source configuration strategy:

Configuration SourceStoragePurposeExample Settings
Environment Variables.env fileSecurity-sensitive credentialsDATABASE_HOST, JWT_SECRET, GOOGLE_CLIENT_ID
Config ModelDatabase tableRuntime-configurable settingsToken TTL, 2FA enable, mailer configuration
YAML Filespermissions.yml, menus.ymlStructural definitionsRole definitions, navigation hierarchy
Schema Definitiondb.jsonDatabase schemaTable structure, relationships, indexes

Config Model Features:

  • Key-value storage with JSON support for complex values
  • Static Config::Value($key) method for accessing settings
  • Commonly used for: application mode, filesystem configurations, SMTP settings
  • GraphQL queries/mutations via AppController

Sources: src/Model/Config.php1-100 db.json1-500 permissions.yml1-100 Diagram 7 (Configuration, Deployment, and External Services)


Development Workflow

Typical development workflow using Light:


  1. Schema Definition - Design database structure in db.json
  2. Schema Installation - Apply DDL changes to MySQL database
  3. Code Generation - Generate models, controllers, input types
  4. Permission Configuration - Add @Right annotations for RBAC
  5. Frontend Types - Generate TypeScript definitions for type safety
  6. Deployment - Deploy with environment-specific .env configuration
  7. Monitoring - Query audit logs via RevisionController
  8. Iteration - Update schema and regenerate code as needed

Sources: Diagram 5 (GraphQL API Structure and Code Generation), bin/light1-50


Target Use Cases

Light is optimized for applications requiring:

  • Enterprise APIs - GraphQL APIs with complex authorization requirements
  • Multi-Tenancy - User isolation with role-based data access
  • Audit Compliance - Financial, healthcare, or regulatory systems requiring change tracking
  • File Management - Document management systems with cloud storage
  • Multi-Factor Security - Applications requiring enhanced authentication (2FA, WebAuthn)
  • Rapid Prototyping - Quick API development with automatic code generation

The framework eliminates the need to implement authentication, authorization, audit, and file management infrastructure, allowing developers to focus on business logic.

Sources: Diagram 1 (Overall System Architecture), Diagram 3 (Authentication, Authorization, and Session Management System), Diagram 4 (Data Persistence and Audit Architecture)