-
-
Save tylerodonnell/3ffce1e38915eb7be42c285544c7e6fd to your computer and use it in GitHub Desktop.
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 | |
$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!"; |
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 | |
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