urlShortener = $urlShortener;
$this->domainConfig = $domainConfig;
}
public function configure()
{
$this->setName('shortcode:generate')
->setDescription('Generates a shortcode for provided URL and returns the short URL')
->addArgument('longUrl', InputArgument::REQUIRED, '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(
'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('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('Processed URL %s', $longUrl),
sprintf('Generated URL %s', $shortUrl),
]);
} catch (InvalidUrlException $e) {
$output->writeln(
sprintf('Provided URL "%s" is invalid. Try with a different one.', $longUrl)
);
}
}
}