Completed
Push — master ( ffab2e...6e7748 )
by Patrick
01:23
created

Command/UpdateRefreshTokenCommand.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
namespace Mailxpert\APIBundle\Command;
4
5
6
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
7
use Symfony\Component\Console\Input\InputInterface;
8
use Symfony\Component\Console\Input\InputOption;
9
use Symfony\Component\Console\Output\OutputInterface;
10
11
class UpdateRefreshTokenCommand extends ContainerAwareCommand
12
{
13
    protected function configure()
14
    {
15
        $this
16
            ->setName('mailxpert:api:access_token:refresh')
17
            ->setDescription('Refresh access tokens before the refresh token is expired')
18
            ->addOption('force', 'f', InputOption::VALUE_NONE, 'Execute the refreshment of access tokens')
19
        ;
20
    }
21
22
    protected function execute(InputInterface $input, OutputInterface $output)
23
    {
24
        $accessTokens = $this->getContainer()->get('mailxpert_api.access_token_manager')->findAlmostExpiredTokens();
25
26
        if (0 === count($accessTokens)) {
27
            $output->writeln('<comment>No access token is due to being refreshed.</comment>');
28
29
            exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method execute() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
30
        }
31
32
        foreach ($accessTokens as $accessToken) {
33
            $date = new \DateTime();
34
            $date->setTimestamp($accessToken->getRefreshTokenExpireAt());
35
36
            $output->writeln(sprintf('<info>Token %s is almost expired (%s)</info>', $accessToken->getAccessToken(), $date->format('d-m-Y H:i:s')));
37
38
            if ($input->getOption('force')) {
39
                $newAccessToken = $this->getContainer()->get('mailxpert_api.manager')->refreshAccessToken($accessToken);
40
                $date->setTimestamp($newAccessToken->getRefreshTokenExpireAt());
41
                $output->writeln(sprintf('<comment>Token %s refreshed and valid until %s</comment>', $newAccessToken->getAccessToken(), $date->format('d-m-Y H:i:s')));
42
            }
43
        }
44
45
        if (!$input->getOption('force')) {
46
            $output->writeln('');
47
            $output->writeln('<comment>To proceed with the update, use the --force</comment>');
48
        }
49
    }
50
}