UpdateCdnStatusCommand::execute()   B
last analyzed

Complexity

Conditions 9
Paths 33

Size

Total Lines 66

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 66
rs 7.1862
c 0
b 0
f 0
cc 9
nc 33
nop 2

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Sonata Project package.
7
 *
8
 * (c) Thomas Rabaix <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Sonata\MediaBundle\Command;
15
16
use Sonata\MediaBundle\CDN\CDNInterface;
17
use Sonata\MediaBundle\Provider\MediaProviderInterface;
18
use Symfony\Component\Console\Helper\QuestionHelper;
19
use Symfony\Component\Console\Input\InputArgument;
20
use Symfony\Component\Console\Input\InputInterface;
21
use Symfony\Component\Console\Output\OutputInterface;
22
use Symfony\Component\Console\Question\ChoiceQuestion;
23
24
/**
25
 * This command can be used to update CDN status for medias that are currently
26
 * in status flushing.
27
 *
28
 * @final since sonata-project/media-bundle 3.21.0
29
 *
30
 * @author Javier Spagnoletti <[email protected]>
31
 */
32
class UpdateCdnStatusCommand extends BaseCommand
0 ignored issues
show
Deprecated Code introduced by
The class Sonata\MediaBundle\Command\BaseCommand has been deprecated with message: since sonata-project/media-bundle 3.26, to be removed in 4.0.

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
33
{
34
    /**
35
     * @var bool
36
     */
37
    protected $quiet = false;
38
39
    /**
40
     * @var OutputInterface
41
     */
42
    protected $output;
43
44
    /**
45
     * @var InputInterface
46
     */
47
    private $input;
48
49
    public function configure(): void
50
    {
51
        $this->setName('sonata:media:update-cdn-status')
52
            ->setDescription('Refresh CDN status for medias that are in status flushing')
53
            ->setDefinition(
54
                [
55
                new InputArgument('providerName', InputArgument::OPTIONAL, 'The provider'),
56
                new InputArgument('context', InputArgument::OPTIONAL, 'The context'),
57
            ]
58
            );
59
    }
60
61
    public function execute(InputInterface $input, OutputInterface $output): int
62
    {
63
        $this->quiet = $input->getOption('quiet');
0 ignored issues
show
Documentation Bug introduced by
It seems like $input->getOption('quiet') can also be of type string or array<integer,string>. However, the property $quiet is declared as type boolean. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
64
65
        $this->input = $input;
66
        $this->output = $output;
67
68
        $provider = $this->getProvider();
69
        $context = $this->getContext();
70
71
        $medias = $this->getMediaManager()->findBy([
72
            'providerName' => $provider->getName(),
73
            'context' => $context,
74
            'cdnIsFlushable' => true,
75
        ]);
76
77
        $this->log(sprintf('Loaded %s medias for updating CDN status (provider: %s, context: %s)', \count($medias), $provider->getName(), $context));
78
79
        foreach ($medias as $media) {
80
            $cdn = $provider->getCdn();
0 ignored issues
show
Bug introduced by
The method getCdn() does not exist on Sonata\MediaBundle\Provider\MediaProviderInterface. Did you maybe mean getCdnPath()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
81
82
            $this->log(sprintf('Refresh CDN status for media "%s" (%d) ', $media->getName(), $media->getId()), false);
83
84
            if (!$media->getCdnFlushIdentifier()) {
85
                $this->log('<error>Skiping while empty flush identifier</error>');
86
87
                continue;
88
            }
89
90
            try {
91
                $previousStatus = $media->getCdnStatus();
92
                if (CDNInterface::STATUS_OK === ($cdnStatus = $cdn->getFlushStatus($media->getCdnFlushIdentifier()))) {
93
                    $media->setCdnIsFlushable(false);
94
                    $media->setCdnFlushIdentifier(null);
95
                    $media->setCdnFlushAt(new \DateTime());
96
                }
97
                $media->setCdnStatus($cdnStatus);
98
99
                if (OutputInterface::VERBOSITY_VERBOSE <= $this->output->getVerbosity()) {
100
                    if ($previousStatus === $cdnStatus) {
101
                        $this->log(sprintf('No changes (%d)', $cdnStatus));
102
                    } elseif (CDNInterface::STATUS_OK === $cdnStatus) {
103
                        $this->log(sprintf('<info>Flush completed</info> (%d => %d)', $previousStatus, $cdnStatus));
104
                    } else {
105
                        $this->log(sprintf('Updated status (%d => %d)', $previousStatus, $cdnStatus));
106
                    }
107
                }
108
            } catch (\Exception $e) {
109
                $this->log(sprintf('<error>Unable update CDN status, media: %s - %s </error>', $media->getId(), $e->getMessage()));
110
111
                continue;
112
            }
113
114
            try {
115
                $this->getMediaManager()->save($media);
116
            } catch (\Exception $e) {
117
                $this->log(sprintf('<error>Unable saving media, media: %s - %s </error>', $media->getId(), $e->getMessage()));
118
119
                continue;
120
            }
121
        }
122
123
        $this->log('Done!');
124
125
        return 0;
126
    }
127
128
    /**
129
     * Write a message to the output.
130
     *
131
     * @param string    $message
132
     * @param bool|true $newLine
133
     */
134
    protected function log($message, $newLine = true): void
135
    {
136
        if (false === $this->quiet) {
137
            if ($newLine) {
138
                $this->output->writeln($message);
139
            } else {
140
                $this->output->write($message);
141
            }
142
        }
143
    }
144
145
    private function getProvider(): MediaProviderInterface
146
    {
147
        $providerName = $this->input->getArgument('providerName');
148
149
        if (null === $providerName) {
150
            $providerName = $this->getQuestionHelper()->ask(
151
                $this->input,
152
                $this->output,
153
                new ChoiceQuestion('Please select the provider', array_keys($this->getMediaPool()->getProviders()))
154
            );
155
        }
156
157
        return $this->getMediaPool()->getProvider($providerName);
158
    }
159
160
    private function getContext(): string
161
    {
162
        $context = $this->input->getArgument('context');
163
164
        if (null === $context) {
165
            $context = $this->getQuestionHelper()->ask(
166
                $this->input,
167
                $this->output,
168
                new ChoiceQuestion('Please select the context', array_keys($this->getMediaPool()->getContexts()))
169
            );
170
        }
171
172
        return $context;
173
    }
174
175
    private function getQuestionHelper(): QuestionHelper
176
    {
177
        return $this->getHelper('question');
178
    }
179
}
180