I have a small package manager in the terminal of own use and that manages my Framework, and I'm giving an improvement in it, and it falls into a problem where I can not loop without using goto, as in the code below:
$stdin = fopen('php://stdin', 'r');
$rs_add_deps = fgetc($stdin);
$requires = [];
if ($rs_add_deps == 's') {
add_req:
echo "Digite o pacote completo:";
$stdin = fopen('php://stdin', 'r');
$countReq = count($requires);
$requires[$countReq] = fgetc($stdin);
goto test_add_req;
} else {
end_add_req:
var_dump($requires);
}
test_add_req:
echo "Adicionar outro pacote?";
$stdin = fopen('php://stdin', 'r');
$add_n_pack = fgetc($stdin);
if ($add_n_pack == 's') {
goto add_req;
} else {
goto end_add_req;
}
This script is adding the possible packages to array $requires[]
according to what the user defines it wants, works perfectly, knowing that the interaction is via terminal and that I will never know how many packages are and (it does some tests to know if the package is valid but cleaned to make the example simpler), is there a less crooked way of capturing those values and adding them to the array?
Another second solution I have is this, but I found it much more complex than using goto:
$stdin = fopen('php://stdin', 'r');
$rs_add_deps = fgetc($stdin);
$requires = [];
$countReq = 0;
$ask = false;
if ($rs_add_deps == 's') {
while (true) {
if (is_numeric($countReq) === 0) {
echo "Digite o pacote completo EX: 'gm/bv4fphp':";
$stdin = fopen('php://stdin', 'r');
$requires[$countReq] = fgetc($stdin);
$ask = true;
$countReq += 1;
} elseif (is_numeric($countReq) > 0) {
if ($ask == true) {
echo "Adicionar outro pacote?";
$stdin = fopen('php://stdin', 'r');
$add_n_pack = fgetc($stdin);
if ($add_n_pack == 's') {
$ask = false;
} else {
$countReq = 'get-out';
}
} else {
echo "Digite o pacote completo:";
$stdin = fopen('php://stdin', 'r');
$requires[$countReq] = fgetc($stdin);
$ask = true;
$countReq += 1;
}
} else {
var_dump($requires);
break;
}
}
}
NOTE: This project is structured, 0 orientation, did not want to leave this context in this project.