|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace CSlant\GitHubProject\Actions; |
| 4 | + |
| 5 | +use CSlant\GitHubProject\Services\GithubService; |
| 6 | +use CSlant\GitHubProject\Services\WebhookService; |
| 7 | +use Illuminate\Http\JsonResponse; |
| 8 | +use Throwable; |
| 9 | + |
| 10 | +class GenerateCommentAction |
| 11 | +{ |
| 12 | + protected WebhookService $webhookService; |
| 13 | + |
| 14 | + protected GithubService $githubService; |
| 15 | + |
| 16 | + public function __construct(WebhookService $webhookService, GithubService $githubService) |
| 17 | + { |
| 18 | + $this->webhookService = $webhookService; |
| 19 | + $this->githubService = $githubService; |
| 20 | + } |
| 21 | + |
| 22 | + /** |
| 23 | + * Generate a comment message from the webhook payload |
| 24 | + * |
| 25 | + * @param array<string, mixed> $payload The GitHub webhook payload |
| 26 | + * @param bool $validate Whether to validate the payload (default: true) |
| 27 | + * |
| 28 | + * @return JsonResponse |
| 29 | + * @throws Throwable |
| 30 | + */ |
| 31 | + public function __invoke(array $payload, bool $validate = true): JsonResponse |
| 32 | + { |
| 33 | + try { |
| 34 | + if ($validate) { |
| 35 | + $validationResponse = $this->webhookService->validatePayload($payload); |
| 36 | + if ($validationResponse !== null) { |
| 37 | + return $validationResponse; |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + $comment = $this->githubService->generateCommentMessage($payload); |
| 42 | + |
| 43 | + return response()->json([ |
| 44 | + 'success' => true, |
| 45 | + 'message' => __('github-project::github-project.success.message'), |
| 46 | + 'comment' => $comment, |
| 47 | + 'payload' => $payload, |
| 48 | + ]); |
| 49 | + } catch (\Exception $e) { |
| 50 | + return response()->json([ |
| 51 | + 'success' => false, |
| 52 | + 'message' => __('github-project::github-project.error.message', ['error' => $e->getMessage()]), |
| 53 | + 'comment' => '', |
| 54 | + 'payload' => $payload, |
| 55 | + ], 500); |
| 56 | + } |
| 57 | + } |
| 58 | +} |
0 commit comments