Skip to content
This repository was archived by the owner on Mar 22, 2020. It is now read-only.
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 23 additions & 15 deletions src/Formatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,9 @@ public function format(Address $address, $options = [])
//
// 'abbreviate', if supplied common abbreviations are applied
// to the resulting output.
//
// 'allownull', if the template matched is empty, allow a null
// result rather than returning everything available
public function formatArray($addressArray, $options = [])
{
$countryCode = (isset($options['country'])) ? $options['country'] : $this->determineCountryCode($addressArray);
Expand Down Expand Up @@ -155,7 +158,7 @@ public function formatArray($addressArray, $options = [])
}

//Render the template
$text = $this->render($tplText, $addressArray);
$text = $this->render($tplText, $addressArray, $options);

//Post render cleanup
if (isset($tpl['postformat_replace'])) {
Expand Down Expand Up @@ -248,40 +251,45 @@ private function postFormatReplace($text, $replacements)
return $text;
}

private function render($tplText, $addressArray)
private function render($tplText, $addressArray, $options)
{
$m = new \Mustache_Engine;

$context = $addressArray;
$context['first'] = function($text) use (&$m, &$addressArray) {
$newText = $m->render($text, $addressArray);
$context['first'] = function($text) use (&$m, &$addressArray, $options) {
$newText = $m->render($text, $addressArray, $options);
$matched = preg_split("/\s*\|\|\s*/", $newText);
$first = current(array_filter($matched));

return $first;
};

$text = $m->render($tplText, $context);
$text = $m->render($tplText, $context, $options);

//Cleanup the output
$text = $this->cleanupRendered($text);

//Make sure we have at least something
if (preg_match('/\w/u', $text) == 0) {
$backupParts = [];

foreach ($addressArray as $key => $val) {
if (strlen($val) > 0) {
$backupParts[] = $val;
if (!isset($options['allownull']) || $options['allownull'] != true) {
$backupParts = [];

foreach ($addressArray as $key => $val) {
if (strlen($val) > 0) {
$backupParts[] = $val;
}
}

$text = implode(', ', $backupParts);
}
else {
$text = ' ';
}

$text = implode(', ', $backupParts);

//Cleanup the output again
$text = $this->cleanupRendered($text);
}

//Cleanup the output again
$text = $this->cleanupRendered($text);

return $text;
}

Expand Down