Skip to content

Instantly share code, notes, and snippets.

@MacDada

MacDada/index.php

Last active Aug 29, 2015
Embed
What would you like to do?
<?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