Skip to content

Commit cb48e85

Browse files
Copilotswissspidy
andcommitted
Cache valid alignments map to avoid recreating on every call
Use a static property to cache the valid alignments map, avoiding the overhead of array creation and array_flip() on every setAlignments() call. Co-authored-by: swissspidy <841956+swissspidy@users.noreply.github.com>
1 parent e842497 commit cb48e85

File tree

1 file changed

+13
-2
lines changed

1 file changed

+13
-2
lines changed

lib/cli/Table.php

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,13 @@ class Table {
3030
protected $_rows = array();
3131
protected $_alignments = array();
3232

33+
/**
34+
* Cached map of valid alignment constants.
35+
*
36+
* @var array|null
37+
*/
38+
private static $_valid_alignments_map = null;
39+
3340
/**
3441
* Initializes the `Table` class.
3542
*
@@ -217,10 +224,14 @@ public function setFooters(array $footers) {
217224
* @param array $alignments An array of alignment constants keyed by column name.
218225
*/
219226
public function setAlignments(array $alignments) {
220-
$valid_alignments = array_flip( array( Column::ALIGN_LEFT, Column::ALIGN_RIGHT, Column::ALIGN_CENTER ) );
227+
// Initialize the cached valid alignments map on first use
228+
if ( null === self::$_valid_alignments_map ) {
229+
self::$_valid_alignments_map = array_flip( array( Column::ALIGN_LEFT, Column::ALIGN_RIGHT, Column::ALIGN_CENTER ) );
230+
}
231+
221232
$headers_map = ! empty( $this->_headers ) ? array_flip( $this->_headers ) : null;
222233
foreach ( $alignments as $column => $alignment ) {
223-
if ( ! isset( $valid_alignments[ $alignment ] ) ) {
234+
if ( ! isset( self::$_valid_alignments_map[ $alignment ] ) ) {
224235
throw new \InvalidArgumentException( "Invalid alignment value '$alignment' for column '$column'." );
225236
}
226237
// Only validate column names if headers are already set

0 commit comments

Comments
 (0)