-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGetJokeCommand.php
More file actions
68 lines (55 loc) · 2.1 KB
/
GetJokeCommand.php
File metadata and controls
68 lines (55 loc) · 2.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<?php
namespace App\Command;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\Cache\ItemInterface;
use Symfony\Contracts\Cache\CacheInterface;
use Psr\Log\LoggerInterface;
#[AsCommand(
name: 'app:get-joke',
description: 'Get a joke',
)]
class GetJokeCommand extends Command
{
public function __construct(private HttpClientInterface $client, private CacheInterface $pool, private LoggerInterface $logger)
{
parent::__construct();
}
protected function configure(): void
{
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$io->progressStart(100);
try {
$startTime = microtime(true);
$client = $this->client;
//si l'élement n'existe pas : appel api + mise en cache
$this->pool->get('joke', function (ItemInterface $item) use ($client): string {
$item->expiresAfter(new \DateInterval('P1D'));
$response = $client->request(
'GET',
'http://official-joke-api.appspot.com/random_joke'
);
$content = $response->toArray();
return $content['setup'] . ' : ' . $content['punchline'];
});
$io->progressAdvance(100);
$io->progressFinish();
$endTime = microtime(true);
$executionTime = date('H:i:s', $endTime - $startTime);
$output->writeln('Temps d\'exécution : ' . $executionTime);
$io->success('Success');
} catch (\Exception $e) {
$this->logger->debug('Command GetJoke : ' . $e->getMessage());
$io->error('Error : ' . $e->getMessage());
return Command::FAILURE;
}
return Command::SUCCESS;
}
}