Skip to content

Instantly share code, notes, and snippets.

@aambrozkiewicz
Created July 20, 2015 10:17
Show Gist options
  • Save aambrozkiewicz/f77440e83dbf3c194b8d to your computer and use it in GitHub Desktop.
Save aambrozkiewicz/f77440e83dbf3c194b8d to your computer and use it in GitHub Desktop.
<?php
interface StringSignatureStorage
{
function save(string $resourceId, array $keys);
}
interface StringStorageInterface
{
function fetch(string $resourceId);
}
interface StringCompiler
{
function compile(string $content, array $values);
}
class StringSignatureFileStorage implements StringSignatureStorage
{
public function save(string $resourceId, array $keys) {
file_put_contents('./resources/' . $resourceId,
'<?php return ' . var_export($keys, true) . ';');
}
}
class SimpleStringCompiler implements StringCompiler
{
public function compile(string $content, array $values)
{
return preg_replace_callback('/%([\w]+)%/', function($matches) use ($values) {
return !empty($values[$matches[1]]) ? $values[$matches[1]] : null;
}, $content);
}
}
class DummyStringRepository implements StringStorageInterface
{
public function fetch(string $resourceId)
{
return $resourceId;
}
}
class StringRepository
{
private $signatureStorage;
private $stringCompiler;
private $stringStorage;
public function __construct(StringSignatureStorage $signatureStorage,
StringStorageInterface $stringStorage, StringCompiler $stringCompiler) {
$this->signatureStorage = $signatureStorage;
$this->stringStorage = $stringStorage;
$this->stringCompiler = $stringCompiler;
}
public function render(string $resourceId, array $values = []): string {
$this->signatureStorage->save($resourceId, array_keys($values));
return $this->stringCompiler->compile($this->stringStorage->fetch($resourceId),
$values);
}
}
$stringRepository = new StringRepository(new StringSignatureFileStorage,
new DummyStringRepository, new SimpleStringCompiler);
var_dump($stringRepository->render('witam %name%!', [
'name' => 'aleks'
]));
var_dump($stringRepository->render('hello.world.resourceId', [
'name' => 'aleks'
]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment