Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improved handling of @ format mask #3344

Merged
merged 1 commit into from
Feb 4, 2023
Merged
Show file tree
Hide file tree
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
13 changes: 11 additions & 2 deletions src/PhpSpreadsheet/Style/NumberFormat/Formatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@

class Formatter
{
private const SYMBOL_AT = '/@(?=(?:[^"]*"[^"]*")*[^"]*\Z)/miu';
private const SECTION_SPLIT = '/;(?=(?:[^"]*"[^"]*")*[^"]*\Z)/miu';

/**
* @param mixed $value
* @param mixed $val
Expand Down Expand Up @@ -112,7 +115,13 @@ public static function toFormattedString($value, $format, $callBack = null)
if (is_bool($value)) {
return $value ? Calculation::getTRUE() : Calculation::getFALSE();
}
// For now we do not treat strings although section 4 of a format code affects strings
// For now we do not treat strings in sections, although section 4 of a format code affects strings
// Process a single block format code containing @ for text substitution
if (preg_match(self::SECTION_SPLIT, $format) === 0 && preg_match(self::SYMBOL_AT, $format) === 1) {
return str_replace('"', '', preg_replace(self::SYMBOL_AT, (string) $value, $format) ?? '');
}

// If we have a text value, return it "as is"
if (!is_numeric($value)) {
return (string) $value;
}
Expand All @@ -138,7 +147,7 @@ function ($matches) {
$format = (string) preg_replace('/(\\\(((.)(?!((AM\/PM)|(A\/P))))|([^ ])))(?=(?:[^"]|"[^"]*")*$)/ui', '"${2}"', $format);

// Get the sections, there can be up to four sections, separated with a semi-colon (but only if not a quoted literal)
$sections = preg_split('/(;)(?=(?:[^"]|"[^"]*")*$)/u', $format) ?: [];
$sections = preg_split(self::SECTION_SPLIT, $format) ?: [];

[$colors, $format, $value] = self::splitFormat($sections, $value);

Expand Down
21 changes: 21 additions & 0 deletions tests/data/Style/NumberFormat.php
Original file line number Diff line number Diff line change
Expand Up @@ -373,6 +373,27 @@
'test',
'_-€* #,##0.00_-;"-€"* #,##0.00_-;_-€* -??_-;_-@_-',
],
// String masks (ie. @)
[
'World',
'World',
'@',
],
[
'Hello World',
'World',
'Hello @',
],
[
'Hello World',
'World',
'"Hello "@',
],
[
'Meet me @ The Boathouse @ 16:30',
'The Boathouse',
'"Meet me @ "@" @ 16:30"',
],
// Named colours
// Simple color
[
Expand Down