Use named regex groups and constants for regex strings

This commit is contained in:
Nathan Dench 2021-05-07 13:00:43 +10:00 committed by Mark Baker
parent df01db58ad
commit f28eea7341
2 changed files with 9 additions and 7 deletions

View File

@ -102,20 +102,20 @@ class AddressHelper
?int $currentRowNumber = null, ?int $currentRowNumber = null,
?int $currentColumnNumber = null ?int $currentColumnNumber = null
): string { ): string {
$validityCheck = preg_match('/^(\$?)([A-Z]{1,3})(\$?)(\d{1,7})$/i', $address, $cellReference); $validityCheck = preg_match(Coordinate::A1_COORDINATE_REGEX, $address, $cellReference);
if ($validityCheck === 0) { if ($validityCheck === 0) {
throw new Exception('Invalid A1-format Cell Reference'); throw new Exception('Invalid A1-format Cell Reference');
} }
$columnId = Coordinate::columnIndexFromString($cellReference[2]); $columnId = Coordinate::columnIndexFromString($cellReference['col_ref']);
if ($cellReference[1] === '$') { if ($cellReference['absolute_col'] === '$') {
// Column must be absolute address // Column must be absolute address
$currentColumnNumber = null; $currentColumnNumber = null;
} }
$rowId = (int) $cellReference[4]; $rowId = (int) $cellReference['row_ref'];
if ($cellReference[3] === '$') { if ($cellReference['absolute_row'] === '$') {
// Row must be absolute address // Row must be absolute address
$currentRowNumber = null; $currentRowNumber = null;
} }

View File

@ -13,6 +13,8 @@ use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
*/ */
abstract class Coordinate abstract class Coordinate
{ {
public const A1_COORDINATE_REGEX = '/^(?<absolute_col>\$?)(?<col_ref>[A-Z]{1,3})(?<absolute_row>\$?)(?<row_ref>\d{1,7})$/i';
/** /**
* Default range variable constant. * Default range variable constant.
* *
@ -29,8 +31,8 @@ abstract class Coordinate
*/ */
public static function coordinateFromString($pCoordinateString) public static function coordinateFromString($pCoordinateString)
{ {
if (preg_match('/^([$]?[A-Z]{1,3})([$]?\\d{1,7})$/', $pCoordinateString, $matches)) { if (preg_match(self::A1_COORDINATE_REGEX, $pCoordinateString, $matches)) {
return [$matches[1], $matches[2]]; return [$matches['absolute_col'] . $matches['col_ref'], $matches['absolute_row'] . $matches['row_ref']];
} elseif (self::coordinateIsRange($pCoordinateString)) { } elseif (self::coordinateIsRange($pCoordinateString)) {
throw new Exception('Cell coordinate string can not be a range of cells'); throw new Exception('Cell coordinate string can not be a range of cells');
} elseif ($pCoordinateString == '') { } elseif ($pCoordinateString == '') {