Subversion-Projekte lars-tiefland.laravel_shop

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
148 lars 1
<?php
2
 
3
declare(strict_types=1);
4
 
5
namespace Termwind;
6
 
7
use ReflectionClass;
8
use Symfony\Component\Console\Helper\SymfonyQuestionHelper;
9
use Symfony\Component\Console\Input\ArgvInput;
10
use Symfony\Component\Console\Input\StreamableInputInterface;
11
use Symfony\Component\Console\Question\Question as SymfonyQuestion;
12
use Symfony\Component\Console\Style\SymfonyStyle;
13
use Termwind\Helpers\QuestionHelper;
14
 
15
/**
16
 * @internal
17
 */
18
final class Question
19
{
20
    /**
21
     * The streamable input to receive the input from the user.
22
     */
23
    private static StreamableInputInterface|null $streamableInput;
24
 
25
    /**
26
     * An instance of Symfony's question helper.
27
     */
28
    private SymfonyQuestionHelper $helper;
29
 
30
    public function __construct(SymfonyQuestionHelper $helper = null)
31
    {
32
        $this->helper = $helper ?? new QuestionHelper();
33
    }
34
 
35
    /**
36
     * Sets the streamable input implementation.
37
     */
38
    public static function setStreamableInput(StreamableInputInterface|null $streamableInput): void
39
    {
40
        self::$streamableInput = $streamableInput ?? new ArgvInput();
41
    }
42
 
43
    /**
44
     * Gets the streamable input implementation.
45
     */
46
    public static function getStreamableInput(): StreamableInputInterface
47
    {
48
        return self::$streamableInput ??= new ArgvInput();
49
    }
50
 
51
    /**
52
     * Renders a prompt to the user.
53
     *
54
     * @param  iterable<array-key, string>|null  $autocomplete
55
     */
56
    public function ask(string $question, iterable $autocomplete = null): mixed
57
    {
58
        $html = (new HtmlRenderer)->parse($question)->toString();
59
 
60
        $question = new SymfonyQuestion($html);
61
 
62
        if ($autocomplete !== null) {
63
            $question->setAutocompleterValues($autocomplete);
64
        }
65
 
66
        $output = Termwind::getRenderer();
67
 
68
        if ($output instanceof SymfonyStyle) {
69
            $property = (new ReflectionClass(SymfonyStyle::class))
70
                ->getProperty('questionHelper');
71
 
72
            $property->setAccessible(true);
73
 
74
            $currentHelper = $property->isInitialized($output)
75
                ? $property->getValue($output)
76
                : new SymfonyQuestionHelper();
77
 
78
            $property->setValue($output, new QuestionHelper);
79
 
80
            try {
81
                return $output->askQuestion($question);
82
            } finally {
83
                $property->setValue($output, $currentHelper);
84
            }
85
        }
86
 
87
        return $this->helper->ask(
88
            self::getStreamableInput(),
89
            Termwind::getRenderer(),
90
            $question,
91
        );
92
    }
93
}