# Services Reference

Complete reference for Entity Builder services.

## Core Services

### OperationDataBuilder

**Service ID:** `eb.operation_data_builder`

**Purpose:** Single source of truth for converting definition data to operation arrays.

```php
$operationDataBuilder = \Drupal::service('eb.operation_data_builder');

// Check if data is in definition format
$isDefinitionFormat = $operationDataBuilder->isDefinitionFormat($data);

// Convert definition data to operations
$operations = $operationDataBuilder->build([
    'bundle_definitions' => [...],
    'field_definitions' => [...],
    'display_field_definitions' => [...],
]);

// Get all recognized definition keys
$keys = $operationDataBuilder->getAllDefinitionKeys();
// Returns: ['bundle_definitions', 'field_definitions', 'field_group_definitions', ...]
```

### OperationBuilder

**Service ID:** `eb.operation_builder`

**Purpose:** Create operation plugin instances from operation data arrays.

```php
$operationBuilder = \Drupal::service('eb.operation_builder');

// Build a single operation instance
$operation = $operationBuilder->build([
    'operation' => 'create_field',
    'entity_type' => 'node',
    'bundle' => 'article',
    'field_name' => 'field_body',
    'field_type' => 'text_long',
]);

// Build multiple operation instances
$operations = $operationBuilder->buildBatch($operationDataArray);
```

### ValidationManager

**Service ID:** `eb.validation_manager`

**Purpose:** Coordinate validation using two-stage validation pattern.

```php
$validationManager = \Drupal::service('eb.validation_manager');

// Validate a single operation
$result = $validationManager->validateOperation($operation);

// Validate a batch of operations with context
$result = $validationManager->validateBatch($operations);

if (!$result->isValid()) {
    foreach ($result->getErrors() as $error) {
        \Drupal::messenger()->addError($error['message']);
    }
}
```

### OperationProcessor

**Service ID:** `eb.operation_processor`

**Purpose:** Execute operations with events and rollback support.

```php
$operationProcessor = \Drupal::service('eb.operation_processor');

// Execute a single operation
$result = $operationProcessor->execute($operation);

// Execute a batch with rollback tracking
$results = $operationProcessor->executeBatch($operations, TRUE, [
    'definition_id' => 'my_definition',
]);
```

### RollbackManager

**Service ID:** `eb.rollback_manager`

**Purpose:** Store and execute rollback operations.

```php
$rollbackManager = \Drupal::service('eb.rollback_manager');

// Start a rollback session
$rollback = $rollbackManager->startRollback('my_definition', 'Apply: my_definition');

// Store rollback data for an operation
$rollbackManager->storeRollbackData($operation, $result, 'my_definition');

// Finalize the rollback session
$rollbackManager->finalizeRollback();

// Execute a rollback
$result = $rollbackManager->executeRollback($rollbackId);

// List rollbacks for a definition
$rollbacks = $rollbackManager->listRollbacksByDefinition('my_definition', 'pending');

// Purge old rollbacks
$count = $rollbackManager->purgeOldRollbacks(30); // Days
```

### DiscoveryService

**Service ID:** `eb.discovery_service`

**Purpose:** Runtime discovery of field types, widgets, formatters, and entity types.

```php
$discoveryService = \Drupal::service('eb.discovery_service');

// Field Types
$fieldTypes = $discoveryService->getAllFieldTypes();
$exists = $discoveryService->fieldTypeExists('text_long');
$info = $discoveryService->getFieldTypeInfo('text_long');

// Widgets
$widgets = $discoveryService->getAllWidgets();
$exists = $discoveryService->widgetExists('text_textarea');
$compatibleWidgets = $discoveryService->getWidgetsForFieldType('text_long');

// Formatters
$formatters = $discoveryService->getAllFormatters();
$exists = $discoveryService->formatterExists('text_default');
$compatibleFormatters = $discoveryService->getFormattersForFieldType('text_long');

// Entity Types
$entityTypes = $discoveryService->getFieldableEntityTypes();
$exists = $discoveryService->entityTypeExists('node');
$isBundleable = $discoveryService->isBundleable('node');
$bundleExists = $discoveryService->bundleExists('node', 'article');
$bundles = $discoveryService->getBundlesForEntityType('node');

// Validation
$errors = $discoveryService->validateFieldConfiguration('node', 'article', 'text_long');
```

### FieldManagementService

**Service ID:** `eb.field_management`

**Purpose:** Centralized field CRUD operations.

```php
$fieldManagement = \Drupal::service('eb.field_management');

// Check existence
$hasStorage = $fieldManagement->fieldStorageExists('node', 'field_body');
$hasConfig = $fieldManagement->fieldConfigExists('node', 'article', 'field_body');

// Load entities
$storage = $fieldManagement->loadFieldStorage('node', 'field_body');
$config = $fieldManagement->loadFieldConfig('node', 'article', 'field_body');

// Create entities
$storage = $fieldManagement->createFieldStorage([
    'entity_type' => 'node',
    'field_name' => 'field_body',
    'type' => 'text_long',
]);

$config = $fieldManagement->createFieldConfig([
    'entity_type' => 'node',
    'bundle' => 'article',
    'field_name' => 'field_body',
    'label' => 'Body',
]);
```

### YamlParser

**Service ID:** `eb.yaml_parser`

**Purpose:** Parse and export YAML definitions.

```php
$yamlParser = \Drupal::service('eb.yaml_parser');

// Parse YAML string
$data = $yamlParser->parse($yamlContent);

// Parse YAML file
$data = $yamlParser->parseFile('/path/to/definition.yml');

// Export to YAML
$yaml = $yamlParser->export($data);

// Validate file extension
$isValid = $yamlParser->validateExtension('definition.yml');
```

### DependencyResolver

**Service ID:** `eb.dependency_resolver`

**Purpose:** Resolve operation dependencies using topological sort.

```php
$dependencyResolver = \Drupal::service('eb.dependency_resolver');

// Resolve and sort operations
$sortedOperations = $dependencyResolver->resolve($operations);

// Get dependencies for a single operation
$dependencies = $dependencyResolver->findDependencies($operation, $allOperations);
```

### ChangeDetector

**Service ID:** `eb.change_detector`

**Purpose:** Smart sync mode change detection.

```php
$changeDetector = \Drupal::service('eb.change_detector');

// Detect changes and modify operation types
$modifiedOperations = $changeDetector->detectChanges($operations, 'sync');
```

### EbLogManager

**Service ID:** `eb.eb_log_manager`

**Purpose:** Audit trail management.

```php
$logManager = \Drupal::service('eb.eb_log_manager');

// Create log entry
$log = $logManager->log([
    'label' => 'Apply: my_definition',
    'definition_id' => 'my_definition',
    'action' => 'apply',
    'operation_count' => 10,
]);

// Complete log entry
$logManager->complete($log, 'success', 10, 0);

// Query logs
$logs = $logManager->getByDefinitionId('my_definition');
$logs = $logManager->loadLogs($account, ['limit' => 50]);

// Purge old logs
$count = $logManager->purge(30);
```

### ContentSanitizer

**Service ID:** `eb.content_sanitizer`

**Purpose:** XSS prevention for imported content.

```php
$sanitizer = \Drupal::service('eb.content_sanitizer');

// Sanitize definition data
$cleanData = $sanitizer->sanitize($data);
```

### ExportSecurityService

**Service ID:** `eb.export_security`

**Purpose:** Export sanitization and HMAC signing.

```php
$exportSecurity = \Drupal::service('eb.export_security');

// Sanitize export data
$cleanData = $exportSecurity->sanitizeForExport($data);

// Sign export (if signing key configured)
$signedYaml = $exportSecurity->signExport($yamlContent);

// Verify signature
$result = $exportSecurity->verifySignature($yamlContent);
// Returns: ['valid' => true|false, 'message' => '...']
```

### DefinitionFactory

**Service ID:** `eb.definition_factory`

**Purpose:** Create EbDefinition entities from YAML data.

```php
$definitionFactory = \Drupal::service('eb.definition_factory');

// Create from YAML data
$definition = $definitionFactory->createFromYaml($data);

// Create or update
$definition = $definitionFactory->createOrUpdate($id, $data);
```

### DefinitionGenerator

**Service ID:** `eb.definition_generator`

**Purpose:** Reverse-engineer Drupal entities to definition format.

```php
$definitionGenerator = \Drupal::service('eb.definition_generator');

// Generate from multiple bundles
$data = $definitionGenerator->generate([
    'node' => ['article', 'page'],
    'taxonomy_term' => ['tags'],
], [
    'include_fields' => TRUE,
    'include_displays' => TRUE,
    'include_extensions' => TRUE,
    'normalize_settings' => TRUE,
]);

// Generate from single bundle
$data = $definitionGenerator->generateBundle('node', 'article');
```

## Plugin Managers

### EbOperationPluginManager

**Service ID:** `plugin.manager.eb_operation`

```php
$operationManager = \Drupal::service('plugin.manager.eb_operation');

// Get all definitions
$definitions = $operationManager->getDefinitions();

// Create instance
$operation = $operationManager->createInstance('create_field', $configuration);
```

### EbValidatorPluginManager

**Service ID:** `plugin.manager.eb_validator`

```php
$validatorManager = \Drupal::service('plugin.manager.eb_validator');

// Get all validators
$definitions = $validatorManager->getDefinitions();

// Create instance
$validator = $validatorManager->createInstance('dependency_validator');
```

### EbExtensionPluginManager

**Service ID:** `plugin.manager.eb_extension`

```php
$extensionManager = \Drupal::service('plugin.manager.eb_extension');

// Get all extensions
$extensions = $extensionManager->getExtensions();

// Get extensions for operation type
$extensions = $extensionManager->getExtensionsForOperation('create_field_group');

// Get extensions for YAML key
$extensions = $extensionManager->getExtensionsForYamlKey('field_group_definitions');

// Get all definition keys from extensions
$keys = $extensionManager->getAllDefinitionKeys();
```

## Interface Aliases

For autowiring support:

```php
// These interfaces resolve to their implementations
Drupal\eb\Service\DiscoveryServiceInterface
Drupal\eb\Service\EbLogManagerInterface
Drupal\eb\Service\FieldManagementServiceInterface
Drupal\eb\Service\OperationBuilderInterface
Drupal\eb\Service\ValidationManagerInterface
Drupal\eb\Service\OperationProcessorInterface
Drupal\eb\Service\RollbackManagerInterface
Drupal\eb\Service\OperationDataBuilderInterface
Drupal\eb\Service\DefinitionGeneratorInterface
```
