Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
86.36% covered (warning)
86.36%
19 / 22
0.00% covered (danger)
0.00%
0 / 2
CRAP
0.00% covered (danger)
0.00%
0 / 1
UploadedFileInteractor
86.36% covered (warning)
86.36%
19 / 22
0.00% covered (danger)
0.00%
0 / 2
9.21
0.00% covered (danger)
0.00%
0 / 1
 supports
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
3.14
 interactWith
88.89% covered (warning)
88.89%
16 / 18
0.00% covered (danger)
0.00%
0 / 1
6.05
1<?php
2namespace Apie\Console\Helpers;
3
4use Apie\Core\Context\ApieContext;
5use Apie\Core\Metadata\MetadataInterface;
6use Psr\Http\Message\UploadedFileInterface;
7use RuntimeException;
8use Symfony\Component\Console\Helper\HelperSet;
9use Symfony\Component\Console\Helper\QuestionHelper;
10use Symfony\Component\Console\Input\InputInterface;
11use Symfony\Component\Console\Output\OutputInterface;
12use Symfony\Component\Console\Question\Question;
13use Symfony\Component\Mime\MimeTypes;
14
15final class UploadedFileInteractor implements InputInteractorInterface
16{
17    public function supports(MetadataInterface $metadata): bool
18    {
19        $class = $metadata->toClass();
20        if ($class?->name === UploadedFileInterface::class) {
21            return true;
22        }
23        return $class && in_array(UploadedFileInterface::class, $class->getInterfaceNames());
24    }
25    public function interactWith(
26        MetadataInterface $metadata,
27        HelperSet $helperSet,
28        InputInterface $input,
29        OutputInterface $output,
30        ApieContext $context
31    ): mixed {
32        $helper = $helperSet->get('question');
33        assert($helper instanceof QuestionHelper);
34        $question = new Question('Please enter a local file system file:');
35        $question->setValidator(function ($input) {
36            if ($input && file_exists($input) && is_readable($input) && is_file($input)) {
37                return $input;
38            }
39            throw new RuntimeException('File "' . $input . '" is not a readable file or does not exist!');
40        });
41        $autocomplete = function (string $userInput): array {
42            return glob($userInput . '*') ? : [];
43        };
44        $question->setAutocompleterCallback($autocomplete);
45        $file = (string) $helper->ask($input, $output, $question);
46        return [
47            'contents' => file_get_contents($file),
48            'mime' => MimeTypes::getDefault()->guessMimeType($file),
49            'originalFilename' => basename($file),
50        ];
51    }
52}