1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace Shlinkio\Shlink\CLI\Command\ShortUrl; |
5
|
|
|
|
6
|
|
|
use Shlinkio\Shlink\Common\Exception\PreviewGenerationException; |
7
|
|
|
use Shlinkio\Shlink\Common\Service\PreviewGeneratorInterface; |
8
|
|
|
use Shlinkio\Shlink\Core\Service\ShortUrlServiceInterface; |
9
|
|
|
use Symfony\Component\Console\Command\Command; |
10
|
|
|
use Symfony\Component\Console\Input\InputInterface; |
11
|
|
|
use Symfony\Component\Console\Output\OutputInterface; |
12
|
|
|
use Symfony\Component\Console\Style\SymfonyStyle; |
13
|
|
|
use function sprintf; |
14
|
|
|
|
15
|
|
|
class GeneratePreviewCommand extends Command |
16
|
|
|
{ |
17
|
|
|
public const NAME = 'short-url:process-previews'; |
18
|
|
|
private const ALIASES = ['shortcode:process-previews', 'short-code:process-previews']; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @var PreviewGeneratorInterface |
22
|
|
|
*/ |
23
|
|
|
private $previewGenerator; |
24
|
|
|
/** |
25
|
|
|
* @var ShortUrlServiceInterface |
26
|
|
|
*/ |
27
|
|
|
private $shortUrlService; |
28
|
|
|
|
29
|
2 |
|
public function __construct(ShortUrlServiceInterface $shortUrlService, PreviewGeneratorInterface $previewGenerator) |
30
|
|
|
{ |
31
|
2 |
|
parent::__construct(); |
32
|
2 |
|
$this->shortUrlService = $shortUrlService; |
33
|
2 |
|
$this->previewGenerator = $previewGenerator; |
34
|
|
|
} |
35
|
|
|
|
36
|
2 |
|
protected function configure(): void |
37
|
|
|
{ |
38
|
|
|
$this |
39
|
2 |
|
->setName(self::NAME) |
40
|
2 |
|
->setAliases(self::ALIASES) |
41
|
2 |
|
->setDescription( |
42
|
2 |
|
'Processes and generates the previews for every URL, improving performance for later web requests.' |
43
|
|
|
); |
44
|
|
|
} |
45
|
|
|
|
46
|
2 |
|
protected function execute(InputInterface $input, OutputInterface $output): void |
47
|
|
|
{ |
48
|
2 |
|
$page = 1; |
49
|
|
|
do { |
50
|
2 |
|
$shortUrls = $this->shortUrlService->listShortUrls($page); |
51
|
2 |
|
$page += 1; |
52
|
|
|
|
53
|
2 |
|
foreach ($shortUrls as $shortUrl) { |
54
|
2 |
|
$this->processUrl($shortUrl->getLongUrl(), $output); |
55
|
|
|
} |
56
|
2 |
|
} while ($page <= $shortUrls->count()); |
57
|
|
|
|
58
|
2 |
|
(new SymfonyStyle($input, $output))->success('Finished processing all URLs'); |
59
|
|
|
} |
60
|
|
|
|
61
|
2 |
|
private function processUrl($url, OutputInterface $output): void |
62
|
|
|
{ |
63
|
|
|
try { |
64
|
2 |
|
$output->write(sprintf('Processing URL %s...', $url)); |
65
|
2 |
|
$this->previewGenerator->generatePreview($url); |
66
|
1 |
|
$output->writeln(' <info>Success!</info>'); |
67
|
1 |
|
} catch (PreviewGenerationException $e) { |
68
|
1 |
|
$output->writeln(' <error>Error</error>'); |
69
|
1 |
|
if ($output->isVerbose()) { |
70
|
|
|
$this->getApplication()->renderException($e, $output); |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|