public function formatNsnUsingPattern($nationalNumber, NumberFormat $formattingPattern, $numberFormat, $carrierCode = null)
{
$numberFormatRule = $formattingPattern->getFormat();
$m = new Matcher($formattingPattern->getPattern(), $nationalNumber);
if ($numberFormat == PhoneNumberFormat::NATIONAL && $carrierCode !== null && mb_strlen($carrierCode) > 0 && mb_strlen($formattingPattern->getDomesticCarrierCodeFormattingRule()) > 0) {
// Replace the $CC in the formatting rule with the desired carrier code.
$carrierCodeFormattingRule = $formattingPattern->getDomesticCarrierCodeFormattingRule();
$ccPatternMatcher = new Matcher(self::CC_PATTERN, $carrierCodeFormattingRule);
$carrierCodeFormattingRule = $ccPatternMatcher->replaceFirst($carrierCode);
// Now replace the $FG in the formatting rule with the first group and the carrier code
// combined in the appropriate way.
$firstGroupMatcher = new Matcher(self::FIRST_GROUP_PATTERN, $numberFormatRule);
$numberFormatRule = $firstGroupMatcher->replaceFirst($carrierCodeFormattingRule);
$formattedNationalNumber = $m->replaceAll($numberFormatRule);
} else {
// Use the national prefix formatting rule instead.
$nationalPrefixFormattingRule = $formattingPattern->getNationalPrefixFormattingRule();
if ($numberFormat == PhoneNumberFormat::NATIONAL && $nationalPrefixFormattingRule !== null && mb_strlen($nationalPrefixFormattingRule) > 0) {
$firstGroupMatcher = new Matcher(self::FIRST_GROUP_PATTERN, $numberFormatRule);
$formattedNationalNumber = $m->replaceAll($firstGroupMatcher->replaceFirst($nationalPrefixFormattingRule));
} else {
$formattedNationalNumber = $m->replaceAll($numberFormatRule);
}
}
if ($numberFormat == PhoneNumberFormat::RFC3966) {
// Strip any leading punctuation.
$matcher = new Matcher(self::$SEPARATOR_PATTERN, $formattedNationalNumber);
if ($matcher->lookingAt()) {
$formattedNationalNumber = $matcher->replaceFirst("");
}
// Replace the rest with a dash between each number group.
$formattedNationalNumber = $matcher->reset($formattedNationalNumber)->replaceAll("-");
}
return $formattedNationalNumber;
}