|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace SensioLabs\Insight\Cli\EventListener; |
| 4 | + |
| 5 | +use SensioLabs\Insight\Sdk\Exception\ApiClientException; |
| 6 | +use SensioLabs\Insight\Sdk\Exception\ApiParserException; |
| 7 | +use SensioLabs\Insight\Sdk\Exception\ApiServerException; |
| 8 | +use Symfony\Component\Console\ConsoleEvents; |
| 9 | +use Symfony\Component\Console\Event\ConsoleErrorEvent; |
| 10 | +use Symfony\Component\EventDispatcher\EventSubscriberInterface; |
| 11 | +use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface; |
| 12 | + |
| 13 | +class ApiErrorListener implements EventSubscriberInterface |
| 14 | +{ |
| 15 | + public static function getSubscribedEvents(): array |
| 16 | + { |
| 17 | + return [ |
| 18 | + ConsoleEvents::ERROR => ['onConsoleError', 256], |
| 19 | + ]; |
| 20 | + } |
| 21 | + |
| 22 | + public function onConsoleError(ConsoleErrorEvent $event): void |
| 23 | + { |
| 24 | + $output = $event->getOutput(); |
| 25 | + $error = $event->getError(); |
| 26 | + |
| 27 | + if ($error instanceof ApiClientException) { |
| 28 | + $this->showClientError($error, $output); |
| 29 | + } elseif ($error instanceof ApiServerException) { |
| 30 | + $output->writeln('<error>Server temporarily unavailable. Please try again in a few minutes.</error>'); |
| 31 | + } elseif ($error instanceof ApiParserException) { |
| 32 | + $output->writeln('<error>Unable to process server response. Please try again later.</error>'); |
| 33 | + } elseif ($error instanceof TransportExceptionInterface) { |
| 34 | + $output->writeln('<error>Network connection failed. Check your internet connection.</error>'); |
| 35 | + } else { |
| 36 | + $output->writeln('<error>Something went wrong. Please try again.</error>'); |
| 37 | + } |
| 38 | + |
| 39 | + $event->setExitCode(0); |
| 40 | + } |
| 41 | + |
| 42 | + private function showClientError(ApiClientException $e, $output): void |
| 43 | + { |
| 44 | + $message = $e->getMessage(); |
| 45 | + if (false !== strpos($message, '401') || false !== strpos($message, 'Unauthorized')) { |
| 46 | + $output->writeln('<error>Invalid API credentials. Run "php insight.phar configure" to set up your token.</error>'); |
| 47 | + } elseif (false !== strpos($message, '404') || false !== strpos($message, 'Not Found')) { |
| 48 | + $output->writeln('<error>Project not found. Check the project UUID and try again.</error>'); |
| 49 | + } elseif (false !== strpos($message, '403') || false !== strpos($message, 'Forbidden')) { |
| 50 | + $output->writeln('<error>Access denied. You don\'t have permission for this project.</error>'); |
| 51 | + } else { |
| 52 | + $output->writeln('<error>Request failed. Please check your input and try again.</error>'); |
| 53 | + } |
| 54 | + } |
| 55 | +} |
0 commit comments