ai_upgrade_assistant-0.2.0-alpha2/src/Service/MachineLearning/PatternLearningManager.php
src/Service/MachineLearning/PatternLearningManager.php
<?php
namespace Drupal\ai_upgrade_assistant\Service\MachineLearning;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Drupal\ai_upgrade_assistant\Service\OpenAIService;
/**
* Manages pattern learning for upgrade paths.
*/
class PatternLearningManager {
/**
* The OpenAI service.
*
* @var \Drupal\ai_upgrade_assistant\Service\OpenAIService
*/
protected $openai;
/**
* The config factory.
*
* @var \Drupal\Core\Config\ConfigFactoryInterface
*/
protected $configFactory;
/**
* The logger factory.
*
* @var \Drupal\Core\Logger\LoggerChannelFactoryInterface
*/
protected $loggerFactory;
/**
* Constructs a new PatternLearningManager.
*
* @param \Drupal\ai_upgrade_assistant\Service\OpenAIService $openai
* The OpenAI service.
* @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
* The config factory.
* @param \Drupal\Core\Logger\LoggerChannelFactoryInterface $logger_factory
* The logger factory.
*/
public function __construct(
OpenAIService $openai,
ConfigFactoryInterface $config_factory,
LoggerChannelFactoryInterface $logger_factory
) {
$this->openai = $openai;
$this->configFactory = $config_factory;
$this->loggerFactory = $logger_factory;
}
/**
* Learns patterns from code changes.
*
* @param array $changes
* Array of code changes to analyze.
*
* @return array
* Array of learned patterns.
*/
public function learnPatterns(array $changes) {
$patterns = [];
$logger = $this->loggerFactory->get('ai_upgrade_assistant');
try {
foreach ($changes as $change) {
$pattern = $this->analyzeChange($change);
if ($pattern) {
$patterns[] = $pattern;
}
}
}
catch (\Exception $e) {
$logger->error('Error learning patterns: @message', ['@message' => $e->getMessage()]);
}
return $patterns;
}
/**
* Analyzes a single code change to extract patterns.
*
* @param array $change
* The code change to analyze.
*
* @return array|null
* The extracted pattern or null if no pattern could be found.
*/
protected function analyzeChange(array $change) {
try {
$prompt = $this->buildAnalysisPrompt($change);
$response = $this->openai->generateCompletion($prompt);
return $this->parseResponse($response);
}
catch (\Exception $e) {
$this->loggerFactory->get('ai_upgrade_assistant')
->error('Error analyzing change: @message', ['@message' => $e->getMessage()]);
return NULL;
}
}
/**
* Builds a prompt for analyzing a code change.
*
* @param array $change
* The code change to analyze.
*
* @return string
* The analysis prompt.
*/
protected function buildAnalysisPrompt(array $change) {
$before = $change['before'] ?? '';
$after = $change['after'] ?? '';
$context = $change['context'] ?? '';
return <<<EOT
Analyze the following Drupal code change and identify the upgrade pattern:
Context:
$context
Before:
$before
After:
$after
Please identify:
1. The type of change (API update, deprecation, breaking change, etc.)
2. The pattern that can be applied to similar code
3. Any conditions or constraints for applying this pattern
4. Risk level and potential side effects
EOT;
}
/**
* Parses the OpenAI response into a structured pattern.
*
* @param string $response
* The OpenAI response.
*
* @return array
* The structured pattern.
*/
protected function parseResponse($response) {
// Basic pattern structure
$pattern = [
'type' => '',
'before_pattern' => '',
'after_pattern' => '',
'conditions' => [],
'risk_level' => 'medium',
'side_effects' => [],
'confidence' => 0.0,
];
// Parse the response and populate the pattern
// This is a simplified implementation
if (preg_match('/Type:\s*(.+?)[\n\r]/i', $response, $matches)) {
$pattern['type'] = trim($matches[1]);
}
if (preg_match('/Risk Level:\s*(.+?)[\n\r]/i', $response, $matches)) {
$pattern['risk_level'] = strtolower(trim($matches[1]));
}
// Extract patterns using more sophisticated regex or parsing
// This would need to be enhanced based on the actual response format
return $pattern;
}
}
