Skip to content

Instantly share code, notes, and snippets.

@tylerodonnell
Forked from adamwathan/Marge.php
Created April 20, 2017 14:26
Show Gist options
  • Save tylerodonnell/3ffce1e38915eb7be42c285544c7e6fd to your computer and use it in GitHub Desktop.
Save tylerodonnell/3ffce1e38915eb7be42c285544c7e6fd to your computer and use it in GitHub Desktop.
<?php
$marge = new Marge();
$marge->setData([
'first_name' => 'David',
'last_name' => 'Hemphill',
]);
$marge->replace("Thanks, [FIRST_NAME] [LAST_NAME] for doing yer thang!");
// Desired result
"Thanks David Hemphill for doing yer thang!";
<?php
namespace App\Merge;
class Marge
{
protected $data = [];
public function setData($data)
{
$this->data = $data;
return $this;
}
public function getData()
{
return $this->data;
}
protected function addDelimiters($token)
{
return '[' . $token . ']';
}
protected function formatToken($token)
{
return $this->addDelimiters(strtoupper($token));
}
public function replace($text)
{
return collect($this->getData())->map(function ($item, $key) {
return [$this->formatToken($key), $item];
})->reduce(function ($text, $replacement) {
list($search, $replace) = $replacement;
return str_replace($search, $replace, $text);
}, $text);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment