# Overview

PteroCA is built on modern PHP technologies and follows industry-standard architectural patterns. This document provides a high-level overview of the system architecture.

***

## Technology Stack

### Core Framework

**Symfony 7.0+**

* Modern PHP framework with dependency injection
* Console commands for CLI operations
* Event dispatcher for loose coupling
* Security component for authentication and authorization
* Doctrine ORM for database operations

**PHP 8.1+**

* Modern PHP features (enums, attributes, typed properties)
* Strong typing throughout the codebase
* Composer for dependency management

### Admin Interface

**EasyAdminBundle 4.x**

* CRUD interfaces for entities
* Customizable dashboards
* Field configurators and filters
* Action management
* Form customization

### Frontend

**Twig 3.x**

* Template engine for rendering views
* Template inheritance and includes
* Custom filters and functions
* Theme system support

**Bootstrap 5**

* Responsive UI components
* Custom styling with Tailwind CSS
* JavaScript for interactivity

### Database

**MySQL/MariaDB**

* Primary database
* Doctrine ORM for abstraction
* Database migrations
* Foreign key constraints

***

## Directory Structure

```
/
├── bin/
│   └── console              # Symfony console entry point
├── config/
│   ├── packages/            # Bundle configurations
│   ├── routes/              # Route definitions
│   └── services.yaml        # Service container configuration
├── migrations/              # Doctrine migrations
├── plugins/                 # Plugin directory (v0.6+)
│   ├── hello-world/         # Example plugin
│   └── paypal-payment/      # PayPal payment provider
├── public/
│   ├── index.php            # Application entry point
│   └── assets/              # Public assets (CSS, JS, images)
├── src/
│   ├── Core/                # Core system components
│   │   ├── Controller/      # Controllers (Client, Admin, API)
│   │   ├── Entity/          # Doctrine entities
│   │   ├── Repository/      # Entity repositories
│   │   ├── Service/         # Business logic services
│   │   ├── EventSubscriber/ # Event subscribers
│   │   ├── Security/        # Security components (voters, authenticators)
│   │   ├── Form/            # Form types
│   │   ├── Resources/       # Resources (translations, views)
│   │   └── Command/         # Console commands
│   ├── Plugin/              # Plugin system
│   │   ├── PluginManager    # Plugin management
│   │   ├── Scanner/         # Plugin discovery and scanning
│   │   └── Security/        # Plugin security scanning
│   └── Kernel.php           # Application kernel
├── templates/               # Default theme templates
│   ├── admin/               # Admin panel templates
│   ├── client/              # Client area templates
│   ├── email/               # Email templates
│   └── bundles/             # Bundle overrides
├── themes/                  # Custom themes
│   └── default/             # Default theme
├── translations/            # Translation files
├── var/
│   ├── cache/               # Application cache
│   └── log/                 # Application logs
└── vendor/                  # Composer dependencies
```

***

## Application Flow

### Request/Response Cycle

1. **Request arrives** at `public/index.php`
2. **Symfony Kernel** boots and loads configuration
3. **Routing** matches the request to a controller
4. **Security** checks authentication and authorization
5. **Controller** processes the request:
   * Fetches data from repositories
   * Calls business logic in services
   * Prepares data for the view
6. **Template** renders the response
7. **Response** sent back to the client

### Authentication Flow

1. User submits login form
2. Security component validates credentials
3. Password verified against database (hashed)
4. User entity loaded with roles
5. Session created
6. User redirected to dashboard

### Authorization Flow

1. User attempts to access a resource
2. Security voters check permissions
3. Role-based access control (RBAC) evaluated
4. Access granted or denied
5. If denied, redirect to access denied page

***

## Key Design Patterns

### Dependency Injection

All services are registered in the service container and injected via constructor:

```php
class ServerService
{
    public function __construct(
        private ServerRepository $serverRepository,
        private PterodactylService $pterodactylService,
        private EventDispatcherInterface $eventDispatcher
    ) {}
}
```

### Repository Pattern

Entities accessed through repositories for data abstraction:

```php
class ServerRepository extends ServiceEntityRepository
{
    public function findActiveByUser(User $user): array
    {
        return $this->createQueryBuilder('s')
            ->where('s.user = :user')
            ->andWhere('s.status = :status')
            ->setParameter('user', $user)
            ->setParameter('status', ServerStatus::ACTIVE)
            ->getQuery()
            ->getResult();
    }
}
```

### Event-Driven Architecture

Events dispatched for loose coupling:

```php
$event = new ServerCreatedEvent($server);
$this->eventDispatcher->dispatch($event);
```

Event subscribers handle events:

```php
class ServerSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents(): array
    {
        return [
            ServerCreatedEvent::class => 'onServerCreated',
        ];
    }

    public function onServerCreated(ServerCreatedEvent $event): void
    {
        // Handle server creation
    }
}
```

### Service Layer

Business logic encapsulated in services:

```php
class PaymentService
{
    public function processPayment(Payment $payment): void
    {
        // Validate payment
        // Process with payment provider
        // Update user balance
        // Dispatch events
        // Create logs
    }
}
```

***

## Plugin System Architecture

**Plugin Isolation**

* Plugins in separate directories
* No direct access to core code
* Defined hooks and interfaces

**Plugin Lifecycle**

1. Discovery (scanning)
2. Validation (manifest, dependencies)
3. Security scanning
4. Loading
5. Bootstrapping
6. Execution

**Plugin Capabilities**

* Custom routes and controllers
* Database entities and migrations
* Event subscribers
* Console commands
* Cron tasks
* UI components (widgets, tabs)
* Payment providers

For detailed plugin architecture, see [Plugin Development](https://github.com/PteroCA-Org/pteroca-homepage/blob/docs/for-developers/plugins/README.md).

***

## Security Architecture

**Multi-Layer Security**

1. **Network:** SSL/TLS, firewall, DDoS protection
2. **Application:** CSRF protection, XSS prevention, SQL injection protection
3. **Authentication:** Bcrypt password hashing, session management
4. **Authorization:** RBAC with 89 permissions, security voters
5. **Data:** Encrypted sensitive data, secure API keys

**RBAC System**

* 89 granular permissions
* Custom roles with permission sets
* Database-driven (not JSON)
* Voter-based access control
* Automatic menu visibility

***

## Performance Considerations

**Caching**

* Symfony cache for configuration
* Twig template caching
* Doctrine query result cache
* Plugin manifest caching

**Database Optimization**

* Indexed columns for queries
* Lazy loading for relations
* Query optimization
* Connection pooling

**Asset Management**

* Asset versioning
* CSS/JS minification
* Image optimization
* CDN support

***

## Testing Strategy

**Unit Tests**

* Service layer testing
* Repository testing
* Utility function testing

**Integration Tests**

* API endpoint testing
* Database interaction testing
* Event system testing

**End-to-End Tests**

* User flow testing
* Admin operations testing
* Payment processing testing


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.pteroca.com/for-developers/overview.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
