Пример #1
0
 /**
  * @param Request $request
  * @param Response $response
  * @param callable|null $out
  * @return null|Response
  */
 public function dispatch(Request $request, Response $response, callable $out = null)
 {
     $postData = $request->getParsedBody();
     if (!isset($postData['longUrl'])) {
         return new JsonResponse(['error' => RestUtils::INVALID_ARGUMENT_ERROR, 'message' => $this->translator->translate('A URL was not provided')], 400);
     }
     $longUrl = $postData['longUrl'];
     $tags = isset($postData['tags']) && is_array($postData['tags']) ? $postData['tags'] : [];
     try {
         $shortCode = $this->urlShortener->urlToShortCode(new Uri($longUrl), $tags);
         $shortUrl = (new Uri())->withPath($shortCode)->withScheme($this->domainConfig['schema'])->withHost($this->domainConfig['hostname']);
         return new JsonResponse(['longUrl' => $longUrl, 'shortUrl' => $shortUrl->__toString(), 'shortCode' => $shortCode]);
     } catch (InvalidUrlException $e) {
         $this->logger->warning('Provided Invalid URL.' . PHP_EOL . $e);
         return new JsonResponse(['error' => RestUtils::getRestErrorCodeFromException($e), 'message' => sprintf($this->translator->translate('Provided URL %s is invalid. Try with a different one.'), $longUrl)], 400);
     } catch (\Exception $e) {
         $this->logger->error('Unexpected error creating shortcode.' . PHP_EOL . $e);
         return new JsonResponse(['error' => RestUtils::UNKNOWN_ERROR, 'message' => $this->translator->translate('Unexpected error occurred')], 500);
     }
 }
Пример #2
0
 public function execute(InputInterface $input, OutputInterface $output)
 {
     $longUrl = $input->getArgument('longUrl');
     $tags = $input->getOption('tags');
     $processedTags = [];
     foreach ($tags as $key => $tag) {
         $explodedTags = explode(',', $tag);
         $processedTags = array_merge($processedTags, $explodedTags);
     }
     $tags = $processedTags;
     try {
         if (!isset($longUrl)) {
             $output->writeln(sprintf('<error>%s</error>', $this->translator->translate('A URL was not provided!')));
             return;
         }
         $shortCode = $this->urlShortener->urlToShortCode(new Uri($longUrl), $tags);
         $shortUrl = (new Uri())->withPath($shortCode)->withScheme($this->domainConfig['schema'])->withHost($this->domainConfig['hostname']);
         $output->writeln([sprintf('%s <info>%s</info>', $this->translator->translate('Processed URL:'), $longUrl), sprintf('%s <info>%s</info>', $this->translator->translate('Generated URL:'), $shortUrl)]);
     } catch (InvalidUrlException $e) {
         $output->writeln(sprintf('<error>' . $this->translator->translate('Provided URL "%s" is invalid. Try with a different one.') . '</error>', $longUrl));
     }
 }