Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
82.35% |
14 / 17 |
|
50.00% |
1 / 2 |
CRAP | |
0.00% |
0 / 1 |
| NumberInteractor | |
82.35% |
14 / 17 |
|
50.00% |
1 / 2 |
8.35 | |
0.00% |
0 / 1 |
| supports | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
4 | |||
| interactWith | |
80.00% |
12 / 15 |
|
0.00% |
0 / 1 |
4.13 | |||
| 1 | <?php |
| 2 | namespace Apie\Console\Helpers; |
| 3 | |
| 4 | use Apie\Core\Context\ApieContext; |
| 5 | use Apie\Core\Enums\ScalarType; |
| 6 | use Apie\Core\Metadata\MetadataInterface; |
| 7 | use Apie\Core\Metadata\ScalarMetadata; |
| 8 | use Apie\Core\Metadata\ValueObjectMetadata; |
| 9 | use Apie\Core\ValueObjects\Utils; |
| 10 | use Symfony\Component\Console\Helper\HelperSet; |
| 11 | use Symfony\Component\Console\Helper\QuestionHelper; |
| 12 | use Symfony\Component\Console\Input\InputInterface; |
| 13 | use Symfony\Component\Console\Output\OutputInterface; |
| 14 | use Symfony\Component\Console\Question\Question; |
| 15 | |
| 16 | final class NumberInteractor implements InputInteractorInterface |
| 17 | { |
| 18 | public function supports(MetadataInterface $metadata): bool |
| 19 | { |
| 20 | return ($metadata instanceof ScalarMetadata || $metadata instanceof ValueObjectMetadata) |
| 21 | && ($metadata->toScalarType() === ScalarType::INTEGER || $metadata->toScalarType() === ScalarType::FLOAT); |
| 22 | } |
| 23 | public function interactWith( |
| 24 | MetadataInterface $metadata, |
| 25 | HelperSet $helperSet, |
| 26 | InputInterface $input, |
| 27 | OutputInterface $output, |
| 28 | ApieContext $context |
| 29 | ): mixed { |
| 30 | $helper = $helperSet->get('question'); |
| 31 | assert($helper instanceof QuestionHelper); |
| 32 | $question = new Question('Fill in a number: '); |
| 33 | if ($metadata->toScalarType() === ScalarType::INTEGER) { |
| 34 | $question->setNormalizer(function ($input) { |
| 35 | return (int) $input; |
| 36 | }); |
| 37 | } |
| 38 | if ($metadata instanceof ValueObjectMetadata) { |
| 39 | $question->setValidator(function ($input) use ($metadata) { |
| 40 | return $metadata->toClass()->getMethod('fromNative')->invoke(null, $input)->toNative(); |
| 41 | }); |
| 42 | } else { |
| 43 | $question->setValidator(function ($input) use ($metadata) { |
| 44 | return $metadata->toScalarType() === ScalarType::INTEGER ? Utils::toInt($input) : Utils::toFloat($input); |
| 45 | }); |
| 46 | } |
| 47 | return $helper->ask($input, $output, $question); |
| 48 | } |
| 49 | } |