Completed
Push — master ( eb9ee0...7c81ae )
by
unknown
02:37 queued 12s
created

src/Command/RemoveThumbsCommand.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
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\Model\MediaInterface;
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\Input\InputOption;
22
use Symfony\Component\Console\Output\OutputInterface;
23
use Symfony\Component\Console\Question\ChoiceQuestion;
24
25
/**
26
 * This command can be used to re-generate the thumbnails for all uploaded medias.
27
 *
28
 * Useful if you have existing media content and added new formats.
29
 *
30
 * @final since sonata-project/media-bundle 3.21.0
31
 */
32
class RemoveThumbsCommand 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.x, 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 InputInterface
41
     */
42
    protected $input;
43
44
    /**
45
     * @var OutputInterface
46
     */
47
    protected $output;
48
49
    public function configure(): void
50
    {
51
        $this->setName('sonata:media:remove-thumbnails')
52
            ->setDescription('Remove uploaded image thumbs')
53
            ->setDefinition(
54
                [
55
                new InputArgument('providerName', InputArgument::OPTIONAL, 'The provider'),
56
                new InputArgument('context', InputArgument::OPTIONAL, 'The context'),
57
                new InputArgument('format', InputArgument::OPTIONAL, 'The format (pass `all` to delete all thumbs)'),
58
                new InputOption('batchSize', null, InputOption::VALUE_REQUIRED, 'Media batch size (100 by default)', 100),
59
                new InputOption('batchesLimit', null, InputOption::VALUE_REQUIRED, 'Media batches limit (0 by default)', 0),
60
                new InputOption('startOffset', null, InputOption::VALUE_REQUIRED, 'Medias start offset (0 by default)', 0),
61
            ]
62
            );
63
    }
64
65
    public function execute(InputInterface $input, OutputInterface $output): int
66
    {
67
        $this->input = $input;
68
        $this->output = $output;
69
70
        $this->quiet = $this->input->getOption('quiet');
71
72
        $provider = $this->getProvider();
73
        $context = $this->getContext();
74
        $format = $this->getFormat($provider, $context);
75
76
        $batchCounter = 0;
77
        $batchSize = (int) ($this->input->getOption('batchSize'));
78
        $batchesLimit = (int) ($this->input->getOption('batchesLimit'));
79
        $startOffset = (int) ($this->input->getOption('startOffset'));
80
        $totalMediasCount = 0;
81
        do {
82
            ++$batchCounter;
83
84
            try {
85
                $batchOffset = $startOffset + ($batchCounter - 1) * $batchSize;
86
                $medias = $this->getMediaManager()->findBy(
87
                    [
88
                        'providerName' => $provider->getName(),
89
                        'context' => $context,
90
                    ],
91
                    [
92
                        'id' => 'ASC',
93
                    ],
94
                    $batchSize,
95
                    $batchOffset
96
                );
97
            } catch (\Exception $e) {
98
                $this->log('Error: '.$e->getMessage());
99
100
                break;
101
            }
102
103
            $batchMediasCount = \count($medias);
104
            if (0 === $batchMediasCount) {
105
                break;
106
            }
107
108
            $totalMediasCount += $batchMediasCount;
109
            $this->log(
110
                sprintf(
111
                    'Loaded %s medias (batch #%d, offset %d) for removing thumbs (provider: %s, format: %s)',
112
                    $batchMediasCount,
113
                    $batchCounter,
114
                    $batchOffset,
115
                    $provider->getName(),
116
                    $format
117
                )
118
            );
119
120
            foreach ($medias as $media) {
121
                if (!$this->processMedia($media, $provider, $context, $format)) {
122
                    continue;
123
                }
124
                //clean filesystem registry for saving memory
125
                $provider->getFilesystem()->clearFileRegister();
126
            }
127
128
            if ($batchesLimit > 0 && $batchCounter === $batchesLimit) {
129
                break;
130
            }
131
        } while (true);
132
133
        $this->log("Done (total medias processed: {$totalMediasCount}).");
134
135
        return 0;
136
    }
137
138
    public function getProvider(): MediaProviderInterface
139
    {
140
        $providerName = $this->input->getArgument('providerName');
141
142
        if (null === $providerName) {
143
            $providerName = $this->getQuestionHelper()->ask(
144
                $this->input,
145
                $this->output,
146
                new ChoiceQuestion('Please select the provider', array_keys($this->getMediaPool()->getProviders()))
147
            );
148
        }
149
150
        return $this->getMediaPool()->getProvider($providerName);
151
    }
152
153
    public function getContext(): string
154
    {
155
        $context = $this->input->getArgument('context');
156
157
        if (null === $context) {
158
            $context = $this->getQuestionHelper()->ask(
159
                $this->input,
160
                $this->output,
161
                new ChoiceQuestion('Please select the context', array_keys($this->getMediaPool()->getContexts()))
162
            );
163
        }
164
165
        return $context;
166
    }
167
168
    /**
169
     * @param string $context
170
     */
171
    public function getFormat(MediaProviderInterface $provider, $context): string
172
    {
173
        $format = $this->input->getArgument('format');
174
175
        if (null === $format) {
176
            $formats = array_keys($provider->getFormats());
177
            $formats[] = '<ALL THUMBNAILS>';
178
179
            $format = $this->getQuestionHelper()->ask(
180
                $this->input,
181
                $this->output,
182
                new ChoiceQuestion('Please select the format', $formats)
183
            );
184
185
            if ('<ALL THUMBNAILS>' === $format) {
186
                $format = $context.'_all';
187
            }
188
        } else {
189
            $format = $context.'_'.$format;
190
        }
191
192
        return $format;
193
    }
194
195
    /**
196
     * @param string $context
197
     * @param string $format
198
     */
199
    protected function processMedia(MediaInterface $media, MediaProviderInterface $provider, $context, $format): bool
200
    {
201
        $this->log('Deleting thumbs for '.$media->getName().' - '.$media->getId());
202
203
        try {
204
            if ($format === $context.'_all') {
205
                $format = null;
206
            }
207
208
            $provider->removeThumbnails($media, $format);
209
        } catch (\Exception $e) {
210
            $this->log(sprintf(
211
                '<error>Unable to remove thumbnails, media: %s - %s </error>',
212
                $media->getId(),
213
                $e->getMessage()
214
            ));
215
216
            return false;
217
        }
218
219
        return true;
220
    }
221
222
    /**
223
     * Write a message to the output.
224
     *
225
     * @param string $message
226
     */
227
    protected function log($message): void
228
    {
229
        if (false === $this->quiet) {
230
            $this->output->writeln($message);
231
        }
232
    }
233
234
    private function getQuestionHelper(): QuestionHelper
235
    {
236
        return $this->getHelper('question');
237
    }
238
}
239