r56630 MediaWiki - Code Review archive

Repository:MediaWiki
Revision:r56629‎ | r56630 | r56631 >
Date:08:26, 19 September 2009
Author:nikerabbit
Status:ok
Tags:
Comment:
Flattening and unflattening for multi-dimensional arrays
Modified paths:
  • /trunk/extensions/Translate/FFS.php (modified) (history)

Diff [purge]

Index: trunk/extensions/Translate/FFS.php
@@ -411,6 +411,7 @@
412412
413413 # Then messages
414414 $messages = TranslateSpyc::loadString( $data );
 415+ $messages = $this->flatten( $messages );
415416 $messages = $this->group->getMangler()->mangle( $messages );
416417
417418 return array(
@@ -437,6 +438,9 @@
438439
439440 $messages[$key] = $value;
440441 }
 442+
 443+ $messages = $this->unflatten( $messages );
 444+
441445 $output .= TranslateSpyc::dump( $messages );
442446 return $output;
443447 }
@@ -460,4 +464,73 @@
461465 }
462466 return $output;
463467 }
 468+
 469+ /**
 470+ * Flattens multidimensional array by using the path to the value as key
 471+ * with each individual key separated by a dot.
 472+ */
 473+ protected function flatten( $messages ) {
 474+
 475+ $flat = true;
 476+ foreach ( $messages as $v ) {
 477+ if ( !is_array( $v ) ) continue;
 478+ $flat = false; break;
 479+ }
 480+ if ( $flat ) return $messages;
 481+
 482+ $array = array();
 483+ foreach ( $messages as $key => $value ) {
 484+ if ( !is_array($value) ) {
 485+ $array[$key] = $value;
 486+ } else {
 487+ $newArray = array();
 488+ foreach ( $value as $newKey => $newValue ) {
 489+ $newArray["$key.$newKey"] = $newValue;
 490+ }
 491+ $array += $this->flatten( $newArray );
 492+ }
 493+ // Can as well keep only one copy around
 494+ unset($messages[$key]);
 495+ }
 496+ return $array;
 497+ }
 498+
 499+ /**
 500+ * Performs the reverse operation of flatten. Each dot in the key starts a
 501+ * new subarray in the final array.
 502+ */
 503+ protected function unflatten( $messages ) {
 504+ $array = array();
 505+ foreach ( $messages as $key => &$value ) {
 506+ $path = explode( '.', $key );
 507+ if ( count( $path ) == 1 ) {
 508+ $array[$key] = &$value;
 509+ continue;
 510+ }
 511+
 512+ $pointer = &$array;
 513+ do {
 514+ # Extract the level and make sure it exists
 515+ $level = array_shift( $path );
 516+ if ( !isset($pointer[$level]) ) {
 517+ $pointer[$level] = array();
 518+ }
 519+
 520+ # Update the pointer to the new reference
 521+ $tmpPointer = &$pointer[$level];
 522+ unset( $pointer );
 523+ $pointer = &$tmpPointer;
 524+ unset( $tmpPointer );
 525+
 526+ # If next level is the last, add it into the array
 527+ if ( count( $path ) === 1 ) {
 528+ $lastKey = array_shift( $path );
 529+ $pointer[$lastKey] = &$value;
 530+ }
 531+ } while ( count( $path ) );
 532+
 533+ }
 534+ return $array;
 535+ }
 536+
464537 }

Status & tagging log