urlShortener = $urlShortener; $this->translator = $translator; $this->domainConfig = $domainConfig; parent::__construct(null); } public function configure() { $this->setName('shortcode:generate') ->setDescription( $this->translator->translate('Generates a short code for provided URL and returns the short URL') ) ->addArgument('longUrl', InputArgument::REQUIRED, $this->translator->translate('The long URL to parse')); } public function interact(InputInterface $input, OutputInterface $output) { $longUrl = $input->getArgument('longUrl'); if (! empty($longUrl)) { return; } /** @var QuestionHelper $helper */ $helper = $this->getHelper('question'); $question = new Question(sprintf( '%s ', $this->translator->translate('A long URL was not provided. Which URL do you want to shorten?:') )); $longUrl = $helper->ask($input, $output, $question); if (! empty($longUrl)) { $input->setArgument('longUrl', $longUrl); } } public function execute(InputInterface $input, OutputInterface $output) { $longUrl = $input->getArgument('longUrl'); try { if (! isset($longUrl)) { $output->writeln(sprintf('%s', $this->translator->translate('A URL was not provided!'))); return; } $shortCode = $this->urlShortener->urlToShortCode(new Uri($longUrl)); $shortUrl = (new Uri())->withPath($shortCode) ->withScheme($this->domainConfig['schema']) ->withHost($this->domainConfig['hostname']); $output->writeln([ sprintf('%s %s', $this->translator->translate('Processed URL:'), $longUrl), sprintf('%s %s', $this->translator->translate('Generated URL:'), $shortUrl), ]); } catch (InvalidUrlException $e) { $output->writeln(sprintf( '' . $this->translator->translate( 'Provided URL "%s" is invalid. Try with a different one.' ) . '', $longUrl )); } } }