Get.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OCA\Files\Command\Object;
  8. use Symfony\Component\Console\Command\Command;
  9. use Symfony\Component\Console\Input\InputArgument;
  10. use Symfony\Component\Console\Input\InputInterface;
  11. use Symfony\Component\Console\Input\InputOption;
  12. use Symfony\Component\Console\Output\OutputInterface;
  13. class Get extends Command {
  14. public function __construct(
  15. private ObjectUtil $objectUtils,
  16. ) {
  17. parent::__construct();
  18. }
  19. protected function configure(): void {
  20. $this
  21. ->setName('files:object:get')
  22. ->setDescription('Get the contents of an object')
  23. ->addArgument('object', InputArgument::REQUIRED, 'Object to get')
  24. ->addArgument('output', InputArgument::REQUIRED, 'Target local file to output to, use - for STDOUT')
  25. ->addOption('bucket', 'b', InputOption::VALUE_REQUIRED, "Bucket to get the object from, only required in cases where it can't be determined from the config");
  26. }
  27. public function execute(InputInterface $input, OutputInterface $output): int {
  28. $object = $input->getArgument('object');
  29. $outputName = $input->getArgument('output');
  30. $objectStore = $this->objectUtils->getObjectStore($input->getOption('bucket'), $output);
  31. if (!$objectStore) {
  32. return self::FAILURE;
  33. }
  34. if (!$objectStore->objectExists($object)) {
  35. $output->writeln("<error>Object $object does not exist</error>");
  36. return self::FAILURE;
  37. }
  38. try {
  39. $source = $objectStore->readObject($object);
  40. } catch (\Exception $e) {
  41. $msg = $e->getMessage();
  42. $output->writeln("<error>Failed to read $object from object store: $msg</error>");
  43. return self::FAILURE;
  44. }
  45. $target = $outputName === '-' ? STDOUT : fopen($outputName, 'w');
  46. if (!$target) {
  47. $output->writeln("<error>Failed to open $outputName for writing</error>");
  48. return self::FAILURE;
  49. }
  50. stream_copy_to_stream($source, $target);
  51. return self::SUCCESS;
  52. }
  53. }