Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
45.83% |
11 / 24 |
|
50.00% |
1 / 2 |
CRAP | |
0.00% |
0 / 1 |
| StringInteractor | |
45.83% |
11 / 24 |
|
50.00% |
1 / 2 |
18.17 | |
0.00% |
0 / 1 |
| supports | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
3 | |||
| interactWith | |
40.91% |
9 / 22 |
|
0.00% |
0 / 1 |
10.16 | |||
| 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\IsPasswordValueObject; |
| 10 | use Exception; |
| 11 | use LogicException; |
| 12 | use Symfony\Component\Console\Helper\HelperSet; |
| 13 | use Symfony\Component\Console\Helper\QuestionHelper; |
| 14 | use Symfony\Component\Console\Input\InputInterface; |
| 15 | use Symfony\Component\Console\Output\OutputInterface; |
| 16 | use Symfony\Component\Console\Question\Question; |
| 17 | |
| 18 | final class StringInteractor implements InputInteractorInterface |
| 19 | { |
| 20 | public function supports(MetadataInterface $metadata): bool |
| 21 | { |
| 22 | return ($metadata instanceof ScalarMetadata || $metadata instanceof ValueObjectMetadata) |
| 23 | && $metadata->toScalarType() === ScalarType::STRING; |
| 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 the value of this field: '); |
| 35 | if ($metadata instanceof ValueObjectMetadata) { |
| 36 | $question->setValidator(function ($input) use ($metadata) { |
| 37 | return $metadata->toClass()->getMethod('fromNative')->invoke(null, $input)->toNative(); |
| 38 | }); |
| 39 | if (in_array(IsPasswordValueObject::class, $metadata->toClass()->getTraitNames())) { |
| 40 | $question->setHidden(true); |
| 41 | $firstEnteredPassword = (string) $helper->ask($input, $output, $question); |
| 42 | $question = new Question('Please type again: '); |
| 43 | $question->setHidden(true); |
| 44 | $question->setMaxAttempts(1); |
| 45 | $question->setValidator(function ($input) use ($metadata, $firstEnteredPassword) { |
| 46 | try { |
| 47 | $result = $metadata->toClass()->getMethod('fromNative')->invoke(null, $input)->toNative(); |
| 48 | } catch (Exception $error) { |
| 49 | $result = $input; |
| 50 | } |
| 51 | if ($result !== $firstEnteredPassword) { |
| 52 | throw new LogicException('You did not enter the same password twice!'); |
| 53 | } |
| 54 | return $result; |
| 55 | }); |
| 56 | } |
| 57 | } |
| 58 | return (string) $helper->ask($input, $output, $question); |
| 59 | } |
| 60 | } |