Skip to content

Instantly share code, notes, and snippets.

@MacDada
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MacDada/8341716f03edc97811d7 to your computer and use it in GitHub Desktop.
Save MacDada/8341716f03edc97811d7 to your computer and use it in GitHub Desktop.
<?php
function run()
{
try {
if ('POST' === $_SERVER['REQUEST_METHOD']) {
echo template_action();
} else {
echo form_action();
}
} catch (Exception $e) {
echo $e->getMessage();
}
}
function form_action()
{
return '
<form method="POST">
<p>Szablon: <input type="text" name="template_filename" value="template" required />.txt
<p>Plik wynikowy: <input type="text" name="output_filename" required />.txt</p>
<p>Imię: <input type="text" name="name" required /></p>
<p>Zawód: <input type="text" name="profession" required /></p>
<p><input type="submit" />
</form>
';
}
function template_action()
{
$template_path = __DIR__.'/'.$_POST['template_filename'].'.txt';
$output_path = __DIR__.'/'.$_POST['output_filename'].'.txt';
$values = array(
'imie' => $_POST['name'],
'zawod' => $_POST['profession'],
);
$content = file_from_template($template_path, $output_path, $values);
return sprintf(
'
Utworzono plik %s o zawartości:
<pre>%s</pre>
<a href="">Utwórz nowy</a>
',
$output_path,
$content
);
}
function file_from_template($template_path, $output_path, array $values)
{
if (!is_file($template_path)) {
throw new RuntimeException('Szablon nie istnieje: '.$template_path);
}
if (!is_readable($template_path)) {
throw new RuntimeException('Szablon jest nie do odczytu: '.$template_path);
}
$template = file_get_contents($template_path);
$content = template($template, $values);
file_put_contents($output_path, $content);
return $content;
}
function template($string, array $values) {
$keys = array_map(
function($key) {
return '{'.$key.'}';
},
array_keys($values)
);
$vals = array_values($values);
return str_replace($keys, $vals, $string);
}
run();
Imię: {imie}
Zawód: {zawod}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment