Created
March 28, 2019 13:22
-
-
Save rikmeijer/7099915c7bc7508b5e6dcb04470dbf71 to your computer and use it in GitHub Desktop.
Functional console IO
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function console() : Closure { | |
$prompt = function(string $line) : Closure { | |
$genericDefault = function(string $default = null) { | |
return function(string $answer) use ($default) { | |
if (empty($answer)) { | |
return $default; | |
} else { | |
return $answer; | |
} | |
}; | |
}; | |
return function(Closure $default = null) use ($genericDefault, $line) { | |
if ($default === null) { | |
$default = $genericDefault(null); | |
} | |
$defaultValueFile = sys_get_temp_dir() . DIRECTORY_SEPARATOR . md5($line); | |
if (file_exists($defaultValueFile)) { | |
$default = $genericDefault(file_get_contents($defaultValueFile)); | |
} | |
print ($default('') ? ' [' . $default('') . ']' : '') . ': '; | |
while (true) { | |
$answer = $default(Seld\CliPrompt\CliPrompt::prompt()); | |
if ($answer !== null) { | |
file_put_contents($defaultValueFile, $answer); | |
break; | |
} | |
print '↳ '; | |
} | |
return $answer; | |
}; | |
}; | |
return function(string $line, bool $new_line = true) use ($prompt) : Closure { | |
print ($new_line ? PHP_EOL : '') . $line; | |
return $prompt($line); | |
}; | |
} |
Author
rikmeijer
commented
Mar 28, 2019
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment