laravel

package
v1.1.8 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 25, 2025 License: MIT Imports: 15 Imported by: 0

README

Laravel Framework Analyzer

Laravel-specific analyzer module for detecting and extracting framework features.

Overview

This module provides framework-aware analysis on top of the base PHP analyzer. It detects Laravel-specific patterns and extracts ORM relationships, controller actions, routes, and other framework features.

Architecture

laravel/
├── types.go        - Laravel-specific type definitions
├── analyzer.go     - Main Laravel analyzer coordinator
├── eloquent.go     - Eloquent Model analyzer
├── controller.go   - Controller analyzer
└── routes.go       - Route file parser (TODO)

Features

✅ Implemented
  1. Eloquent Model Detection

    • Detects classes extending Illuminate\Database\Eloquent\Model
    • Extracts model properties:
      • $fillable - mass assignable attributes
      • $guarded - protected attributes
      • $casts - attribute type casting
      • $hidden - hidden attributes for serialization
      • $table - custom table name
      • $primaryKey - custom primary key
    • Detects SoftDeletes trait usage
    • Extracts query scopes (scopeMethodName)
    • Detects accessors/mutators (getXxxAttribute, setXxxAttribute)
  2. Relationship Detection

    • hasOne() - one-to-one
    • hasMany() - one-to-many
    • belongsTo() - inverse one-to-many
    • belongsToMany() - many-to-many
    • hasManyThrough() - has-many-through
    • Polymorphic relations (TODO)
  3. Controller Analysis

    • Detects classes in App\Http\Controllers namespace
    • Identifies resource controllers (index, create, store, show, edit, update, destroy)
    • Distinguishes API controllers
    • Extracts controller actions with:
      • HTTP method inference
      • Parameter extraction
      • Return type detection
    • Middleware detection (TODO: requires method body parsing)
🚧 In Progress
  1. Route Analysis (TODO)

    • Parse routes/web.php and routes/api.php
    • Extract route definitions:
      • HTTP method (GET, POST, PUT, DELETE, etc.)
      • URI pattern
      • Controller@action binding
      • Route names
      • Middleware
    • Map routes to controller actions
  2. Migration Analysis (TODO)

    • Parse migration files
    • Extract table schemas
    • Track database structure evolution
❌ Planned
  1. Service Provider Analysis

    • Detect service bindings
    • Extract IoC container registrations
    • Map contracts to implementations
  2. Middleware Analysis

    • Parse middleware classes
    • Track middleware stacks
    • Analyze middleware groups

Usage

Basic Analysis
import (
    "github.com/doITmagic/rag-code-mcp/internal/ragcode/analyzers/php"
    "github.com/doITmagic/rag-code-mcp/internal/ragcode/analyzers/php/laravel"
)

// First, analyze PHP code
phpAnalyzer := php.NewCodeAnalyzer()
packageInfo, err := phpAnalyzer.AnalyzePath("app/Models")

// Then apply Laravel-specific analysis
laravelAnalyzer := laravel.NewAnalyzer(packageInfo)
laravelInfo := laravelAnalyzer.Analyze()

// Access Laravel-specific features
for _, model := range laravelInfo.Models {
    fmt.Printf("Model: %s\n", model.ClassName)
    fmt.Printf("  Table: %s\n", model.Table)
    fmt.Printf("  Fillable: %v\n", model.Fillable)
    
    for _, relation := range model.Relations {
        fmt.Printf("  Relation: %s -> %s (%s)\n", 
            relation.Name, relation.RelatedModel, relation.Type)
    }
}
Integration with PHP Analyzer
// The Laravel analyzer works as a decorator over PHP analyzer
phpAnalyzer := php.NewCodeAnalyzer()
pkgInfo, _ := phpAnalyzer.AnalyzePath("app/")

// Detect if it's a Laravel project
isLaravel := detectLaravelProject(pkgInfo)

if isLaravel {
    laravelAnalyzer := laravel.NewAnalyzer(pkgInfo)
    laravelInfo := laravelAnalyzer.Analyze()
    
    // Use Laravel-specific information for better RAG chunking
    chunks := createLaravelAwareChunks(pkgInfo, laravelInfo)
}

Design Patterns

1. Layered Analysis
Base PHP AST → PHP Analyzer → Laravel Analyzer → RAG Chunks
  • Base PHP AST: VKCOM/php-parser provides syntax tree
  • PHP Analyzer: Extracts classes, methods, properties (generic PHP)
  • Laravel Analyzer: Detects framework patterns (Eloquent, Controllers, Routes)
  • RAG Chunks: Smart chunking based on Laravel semantics
2. Framework Detection

The analyzer uses multiple signals to detect Laravel:

  • Class inheritance (extends Model, extends Controller)
  • Namespace patterns (App\Models\, App\Http\Controllers\)
  • Directory structure (app/Models/, routes/)
  • Trait usage (SoftDeletes, Notifiable)
3. Semantic Chunking

Instead of arbitrary character limits, chunks are created based on:

  • Model = Class + Properties + Relations + Scopes
  • Controller = Class + Actions + Middleware + Related Routes
  • Route Group = Related routes with shared middleware/prefix

Limitations

Current Limitations
  1. Property Array Extraction: Requires AST parsing of class property initializers

    • $fillable = ['name', 'email'] → Need to parse array literals
    • Workaround: Parse raw source code for simple cases
  2. Method Body Analysis: Relationship detection requires method body parsing

    • return $this->hasMany(Post::class) → Need to parse method calls
    • Workaround: Use PHPDoc annotations when available
  3. Route Files: Routes are procedural, not class-based

    • Requires special parser for Route::get() calls
    • Workaround: Simple regex patterns for common cases
Future Improvements
  1. AST-based Property Extraction

    • Traverse PropertyList nodes
    • Parse array initialization expressions
    • Handle complex array structures
  2. Method Call Graph

    • Build call graph from method bodies
    • Detect relationship chains
    • Trace service container resolutions
  3. Route-Controller Mapping

    • Parse route files using AST
    • Match routes to controllers
    • Build complete request flow graph

Testing

# Run Laravel analyzer tests
go test ./internal/ragcode/analyzers/php/laravel/

# Test with real Laravel project
go test -v -run TestLaravelProjectAnalysis

Examples

See laravel/examples/ for sample Laravel code and expected analysis output.

Contributing

When adding new Laravel features:

  1. Add types to types.go
  2. Create analyzer in separate file (e.g., middleware.go)
  3. Integrate into analyzer.go
  4. Add tests with real Laravel code samples
  5. Update this README

References

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ASTPropertyExtractor

type ASTPropertyExtractor struct{}

ASTPropertyExtractor helps extract property values from PHP AST nodes

func NewASTPropertyExtractor

func NewASTPropertyExtractor() *ASTPropertyExtractor

NewASTPropertyExtractor creates a new AST property extractor

func (*ASTPropertyExtractor) ExtractMapFromClass

func (e *ASTPropertyExtractor) ExtractMapFromClass(classNode *ast.StmtClass, propertyName string) map[string]string

ExtractMapFromClass extracts an associative array (map) from a class property Example: protected $casts = ['is_admin' => 'boolean', 'age' => 'integer'];

func (*ASTPropertyExtractor) ExtractMethodCalls

func (e *ASTPropertyExtractor) ExtractMethodCalls(methodNode *ast.StmtClassMethod) []MethodCall

ExtractMethodCalls extracts method calls from a method body Example: return $this->hasMany(Post::class);

func (*ASTPropertyExtractor) ExtractStringArrayFromClass

func (e *ASTPropertyExtractor) ExtractStringArrayFromClass(classNode *ast.StmtClass, propertyName string) []string

ExtractStringArrayFromClass extracts a protected/private string array property from a class node Example: protected $fillable = ['name', 'email'];

func (*ASTPropertyExtractor) ExtractStringPropertyFromClass

func (e *ASTPropertyExtractor) ExtractStringPropertyFromClass(classNode *ast.StmtClass, propertyName string) string

ExtractStringPropertyFromClass extracts a simple string property value Example: protected $table = 'users';

type Adapter

type Adapter struct {
	// contains filtered or unexported fields
}

Adapter implements codetypes.PathAnalyzer for Laravel projects It wraps the standard PHP analyzer and adds Laravel-specific analysis

func NewAdapter

func NewAdapter() *Adapter

NewAdapter creates a new Laravel analyzer adapter

func (*Adapter) AnalyzePaths

func (a *Adapter) AnalyzePaths(paths []string) ([]codetypes.CodeChunk, error)

AnalyzePaths implements the PathAnalyzer interface

type Analyzer

type Analyzer struct {
	// contains filtered or unexported fields
}

Analyzer is the main Laravel framework analyzer that coordinates all Laravel-specific analyzers

func NewAnalyzer

func NewAnalyzer(packageInfo *php.PackageInfo) *Analyzer

NewAnalyzer creates a new Laravel framework analyzer

func (*Analyzer) Analyze

func (a *Analyzer) Analyze() *LaravelInfo

Analyze performs complete Laravel framework analysis on the package

func (*Analyzer) AnalyzeWithRoutes

func (a *Analyzer) AnalyzeWithRoutes(routePaths []string) *LaravelInfo

AnalyzeWithRoutes performs analysis including route files

type Controller

type Controller struct {
	ClassName      string             `json:"class_name"`
	Namespace      string             `json:"namespace"`
	FullName       string             `json:"full_name"`
	Description    string             `json:"description"`
	BaseController string             `json:"base_controller,omitempty"` // Extends Controller/ApiController
	IsResource     bool               `json:"is_resource"`               // Resource controller
	IsApi          bool               `json:"is_api"`                    // API controller
	Actions        []ControllerAction `json:"actions"`
	Middleware     []string           `json:"middleware,omitempty"` // Middleware applied
	FilePath       string             `json:"file_path"`
	StartLine      int                `json:"start_line"`
	EndLine        int                `json:"end_line"`
}

Controller represents a Laravel controller

type ControllerAction

type ControllerAction struct {
	Name        string   `json:"name"`        // Method name
	Description string   `json:"description"` // PHPDoc description
	HttpMethods []string `json:"http_methods,omitempty"`
	Route       string   `json:"route,omitempty"`      // Associated route pattern
	Parameters  []string `json:"parameters,omitempty"` // Method parameters
	Returns     string   `json:"returns,omitempty"`    // Return type
	StartLine   int      `json:"start_line"`
	EndLine     int      `json:"end_line"`
}

ControllerAction represents a controller method/action

type ControllerAnalyzer

type ControllerAnalyzer struct {
	// contains filtered or unexported fields
}

ControllerAnalyzer detects and analyzes Laravel controllers

func NewControllerAnalyzer

func NewControllerAnalyzer(pkgInfo *php.PackageInfo) *ControllerAnalyzer

NewControllerAnalyzer creates a new controller analyzer

func (*ControllerAnalyzer) AnalyzeControllers

func (a *ControllerAnalyzer) AnalyzeControllers() []Controller

AnalyzeControllers detects controllers and extracts actions

type EloquentAnalyzer

type EloquentAnalyzer struct {
	// contains filtered or unexported fields
}

EloquentAnalyzer extracts Eloquent model information from PHP package info

func NewEloquentAnalyzer

func NewEloquentAnalyzer(packageInfo *php.PackageInfo) *EloquentAnalyzer

NewEloquentAnalyzer creates a new Eloquent analyzer

func (*EloquentAnalyzer) AnalyzeModels

func (a *EloquentAnalyzer) AnalyzeModels() []EloquentModel

AnalyzeModels detects Eloquent models in the package and extracts Laravel-specific features

type EloquentAttribute

type EloquentAttribute struct {
	Name        string `json:"name"`        // Attribute name
	MethodName  string `json:"method_name"` // Method name (e.g., "getFullNameAttribute")
	Type        string `json:"type"`        // "accessor" or "mutator"
	Description string `json:"description,omitempty"`
	StartLine   int    `json:"start_line"`
	EndLine     int    `json:"end_line"`
}

EloquentAttribute represents an accessor or mutator

type EloquentModel

type EloquentModel struct {
	ClassName   string              `json:"class_name"`
	Namespace   string              `json:"namespace"`
	FullName    string              `json:"full_name"`
	Description string              `json:"description"`
	Table       string              `json:"table,omitempty"`       // $table property
	Fillable    []string            `json:"fillable,omitempty"`    // $fillable array
	Guarded     []string            `json:"guarded,omitempty"`     // $guarded array
	Casts       map[string]string   `json:"casts,omitempty"`       // $casts array
	Dates       []string            `json:"dates,omitempty"`       // $dates array (legacy)
	Hidden      []string            `json:"hidden,omitempty"`      // $hidden array
	Visible     []string            `json:"visible,omitempty"`     // $visible array
	Appends     []string            `json:"appends,omitempty"`     // $appends array
	Relations   []EloquentRelation  `json:"relations,omitempty"`   // Detected relations
	Scopes      []EloquentScope     `json:"scopes,omitempty"`      // Query scopes
	Attributes  []EloquentAttribute `json:"attributes,omitempty"`  // Accessors/Mutators
	PrimaryKey  string              `json:"primary_key,omitempty"` // $primaryKey
	Timestamps  bool                `json:"timestamps"`            // $timestamps (default true)
	SoftDeletes bool                `json:"soft_deletes"`          // Uses SoftDeletes trait
	FilePath    string              `json:"file_path"`
	StartLine   int                 `json:"start_line"`
	EndLine     int                 `json:"end_line"`
}

EloquentModel represents a Laravel Eloquent model with ORM features

type EloquentRelation

type EloquentRelation struct {
	Name         string `json:"name"`          // Method name (e.g., "posts")
	Type         string `json:"type"`          // hasOne, hasMany, belongsTo, belongsToMany, etc.
	RelatedModel string `json:"related_model"` // Related model class (e.g., "App\\Models\\Post")
	ForeignKey   string `json:"foreign_key,omitempty"`
	LocalKey     string `json:"local_key,omitempty"`
	Description  string `json:"description,omitempty"`
	StartLine    int    `json:"start_line"`
	EndLine      int    `json:"end_line"`
}

EloquentRelation represents a relationship method in an Eloquent model

type EloquentScope

type EloquentScope struct {
	Name        string `json:"name"`        // Scope name without "scope" prefix
	MethodName  string `json:"method_name"` // Full method name (e.g., "scopeActive")
	Description string `json:"description,omitempty"`
	StartLine   int    `json:"start_line"`
	EndLine     int    `json:"end_line"`
}

EloquentScope represents a query scope (scopeMethodName)

type LaravelInfo

type LaravelInfo struct {
	Models      []EloquentModel `json:"models"`
	Controllers []Controller    `json:"controllers"`
	Routes      []Route         `json:"routes"`
	Migrations  []Migration     `json:"migrations,omitempty"`
	Middleware  []Middleware    `json:"middleware,omitempty"`
}

LaravelInfo contains Laravel-specific framework information extracted from a project

type MethodCall

type MethodCall struct {
	Object string   // Variable name ($this, $variable)
	Method string   // Method name (hasMany, belongsTo)
	Args   []string // Arguments
}

MethodCall represents a method call found in code

type Middleware

type Middleware struct {
	ClassName   string `json:"class_name"`
	Namespace   string `json:"namespace"`
	FullName    string `json:"full_name"`
	Description string `json:"description"`
	Alias       string `json:"alias,omitempty"` // Middleware alias in kernel
	FilePath    string `json:"file_path"`
	StartLine   int    `json:"start_line"`
	EndLine     int    `json:"end_line"`
}

Middleware represents a middleware class

type Migration

type Migration struct {
	ClassName   string   `json:"class_name"`
	Description string   `json:"description"`
	Table       string   `json:"table,omitempty"`      // Table being modified
	Operations  []string `json:"operations,omitempty"` // create, update, drop, etc.
	FilePath    string   `json:"file_path"`
	StartLine   int      `json:"start_line"`
	EndLine     int      `json:"end_line"`
}

Migration represents a database migration file

type Route

type Route struct {
	Method      string   `json:"method"` // GET, POST, PUT, DELETE, etc.
	URI         string   `json:"uri"`    // Route pattern (e.g., "/users/{id}")
	Name        string   `json:"name,omitempty"`
	Controller  string   `json:"controller,omitempty"` // Controller@action or FQCN
	Action      string   `json:"action,omitempty"`     // Action method name
	Middleware  []string `json:"middleware,omitempty"`
	Description string   `json:"description,omitempty"`
	FilePath    string   `json:"file_path"` // routes/web.php or routes/api.php
	Line        int      `json:"line"`
}

Route represents a Laravel route definition

type RouteAnalyzer

type RouteAnalyzer struct {
	// contains filtered or unexported fields
}

RouteAnalyzer parses Laravel route files

func NewRouteAnalyzer

func NewRouteAnalyzer() *RouteAnalyzer

NewRouteAnalyzer creates a new route analyzer

func (*RouteAnalyzer) Analyze

func (ra *RouteAnalyzer) Analyze(filePaths []string) ([]Route, error)

Analyze parses the given route files and returns extracted routes

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL