1<?php 2// (c) Copyright by authors of the Tiki Wiki CMS Groupware Project 3// 4// All Rights Reserved. See copyright.txt for details and a complete list of authors. 5// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details. 6// $Id$ 7 8class TikiFilter_PrepareInput 9{ 10 private $delimiter; 11 12 function __construct($delimiter) 13 { 14 $this->delimiter = $delimiter; 15 } 16 17 static function delimiter($delimiter) 18 { 19 $me = new self($delimiter); 20 return $me; 21 } 22 23 function prepare(array $input) 24 { 25 $output = []; 26 27 foreach ($input as $key => $value) { 28 if (strpos($key, $this->delimiter) === false) { 29 $output[$key] = $value; 30 } else { 31 list ($base, $remain) = explode($this->delimiter, $key, 2); 32 33 if (! isset($output[$base]) || ! is_array($output[$base])) { 34 $output[$base] = []; 35 } 36 37 $output[$base][$remain] = $value; 38 } 39 } 40 41 foreach ($output as $key => & $value) { 42 if (is_array($value)) { 43 $value = $this->prepare($value); 44 } 45 } 46 47 return $output; 48 } 49 50 function flatten($values, &$newValues = [], $prefix = '') 51 { 52 foreach ($values as $key => $value) { 53 if (is_array($value) || is_object($value)) { 54 $newPrefix = $prefix . $key . $this->delimiter; 55 $newValue = $this->flatten($value, $newValues, $newPrefix, $this->delimiter); 56 $newValues =& $newValue; 57 } else { 58 $newValues[$prefix . $key] = $value; 59 } 60 } 61 62 return $newValues; 63 } 64 65 function toString($values, &$newValues = [], $prefex = '') 66 { 67 $flatArray = self::flatten($values, $newValues, $prefex); 68 69 $output = ''; 70 71 foreach ($flatArray as $key => $value) { 72 $output .= urlencode($key) . ':' . urlencode($value) . "\n"; 73 } 74 75 return $output; 76 } 77 78 function prepareFromString($input = '') 79 { 80 $stringArray = explode("\n", $input); 81 82 $flatArray = []; 83 84 foreach ($stringArray as $string) { 85 $string = explode(":", $string); 86 if (isset($string[0], $string[1])) { 87 $flatArray[urldecode($string[0])] = urldecode($string[1]); 88 } 89 } 90 91 return self::prepare($flatArray); 92 } 93} 94