SymfonyComponentTranslationUtilArrayConverter

ArrayConverter generates tree like structure from a message catalogue.

Defined (1)

The class is defined in the following location(s).

/vendor/symfony/translation/Util/ArrayConverter.php  
  1. class ArrayConverter 
  2. /** 
  3. * Converts linear messages array to tree-like array. 
  4. * For example this rray('foo.bar' => 'value') will be converted to array('foo' => array('bar' => 'value')). 
  5. * @param array $messages Linear messages array 
  6. * @return array Tree-like messages array 
  7. */ 
  8. public static function expandToTree(array $messages) 
  9. $tree = array(); 
  10.  
  11. foreach ($messages as $id => $value) { 
  12. $referenceToElement = &self::getElementByPath($tree, explode('.', $id)); 
  13.  
  14. $referenceToElement = $value; 
  15.  
  16. unset($referenceToElement); 
  17.  
  18. return $tree; 
  19.  
  20. private static function &getElementByPath(array &$tree, array $parts) 
  21. $elem = &$tree; 
  22. $parentOfElem = null; 
  23.  
  24. foreach ($parts as $i => $part) { 
  25. if (isset($elem[$part]) && is_string($elem[$part])) { 
  26. /** Process next case: 
  27. * 'foo': 'test1',  
  28. * 'foo.bar': 'test2' 
  29. * $tree['foo'] was string before we found array {bar: test2}. 
  30. * Treat new element as string too, e.g. add $tree['foo.bar'] = 'test2'; 
  31. */ 
  32. $elem = &$elem[ implode('.', array_slice($parts, $i)) ]; 
  33. break; 
  34. $parentOfElem = &$elem; 
  35. $elem = &$elem[$part]; 
  36.  
  37. if (is_array($elem) && count($elem) > 0 && $parentOfElem) { 
  38. /** Process next case: 
  39. * 'foo.bar': 'test1' 
  40. * 'foo': 'test2' 
  41. * $tree['foo'] was array = {bar: 'test1'} before we found string constant `foo`. 
  42. * Cancel treating $tree['foo'] as array and cancel back it expansion,  
  43. * e.g. make it $tree['foo.bar'] = 'test1' again. 
  44. */ 
  45. self::cancelExpand($parentOfElem, $part, $elem); 
  46.  
  47. return $elem; 
  48.  
  49. private static function cancelExpand(array &$tree, $prefix, array $node) 
  50. $prefix .= '.'; 
  51.  
  52. foreach ($node as $id => $value) { 
  53. if (is_string($value)) { 
  54. $tree[$prefix.$id] = $value; 
  55. } else { 
  56. self::cancelExpand($tree, $prefix.$id, $value);