-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUploadCommand.php
More file actions
104 lines (90 loc) · 3.19 KB
/
UploadCommand.php
File metadata and controls
104 lines (90 loc) · 3.19 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
<?php
declare(strict_types=1);
namespace Speicher210\CloudinaryBundle\Command;
use Cloudinary\Api\ApiResponse;
use Override;
use Psl\Filesystem;
use Psl\Type;
use Speicher210\CloudinaryBundle\Cloudinary\Uploader;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Finder\SplFileInfo;
use Throwable;
final class UploadCommand extends Command
{
private readonly Uploader $uploader;
public function __construct(Uploader $uploader)
{
$this->uploader = $uploader;
parent::__construct();
}
#[Override]
protected function configure(): void
{
$this
->setName('sp210:cloudinary:upload')
->setDescription(
'Upload files from a directory to Cloudinary. The public ID will be the name of the file. It will overwrite the existing files automatically.',
)
->addArgument('directory', InputArgument::REQUIRED, 'The directory from where to upload the files.')
->addOption(
'prefix',
null,
InputOption::VALUE_REQUIRED,
'Add prefix to uploaded files.',
)
->addOption(
'filter',
null,
InputOption::VALUE_REQUIRED,
'Filter to apply when scanning the directory (ex: "*.jpg").',
);
}
#[Override]
protected function execute(InputInterface $input, OutputInterface $output): int
{
$symfonyStyle = new SymfonyStyle($input, $output);
$files = Finder::create()->files()->in($input->getArgument('directory'));
$prefix = Type\string()->coerce($input->getOption('prefix'));
if ($input->getOption('filter') !== null) {
$files->name($input->getOption('filter'));
}
$table = $symfonyStyle->createTable();
$table->setHeaders(['Local file', 'Public ID', 'Error']);
$table->render();
foreach ($files as $file) {
try {
$publicId = $prefix . Filesystem\get_filename($file->getFilename());
$response = $this->uploadFileToCloudinary($file, $publicId);
$table->appendRow(
[
$file->getRealPath(),
$response['public_id'],
null,
],
);
} catch (Throwable $e) {
$table->appendRow(
[
$file->getRealPath(),
$response['public_id'] ?? null,
$e->getMessage(),
],
);
}
}
return Command::SUCCESS;
}
private function uploadFileToCloudinary(SplFileInfo $file, string $publicId): ApiResponse
{
return $this->uploader->upload(
$file->getRealPath(),
['public_id' => $publicId],
);
}
}