diff --git a/src/libraries/ArrayFlattener.php b/src/libraries/ArrayFlattener.php new file mode 100644 index 0000000..7b17330 --- /dev/null +++ b/src/libraries/ArrayFlattener.php @@ -0,0 +1,99 @@ + $value ) { + self::__flatten( $buffer, $key, $value, 0 ); + } + + return $buffer; + } + + /** + * __flatten() + * Does the grunt work of flatten(). + * + * @param &$buffer The string buffer that will be returned by flatten(). + * @param &$key The name of the current key being processed. + * @param &$value The key's value, can be anything. + * @param $depth The current depth level, not to exceed MAX_DEPTH. + * + * @return void + */ + private static function __flatten( &$buffer, &$key, &$value, $depth ) { + if ( $depth >= self::MAX_DEPTH ) { + // exceeded maximum recursion depth + $buffer .= $key . PHP_EOL; + return; + } + + if ( is_null( $value ) ) { + $buffer .= $key . ' null' . PHP_EOL; + return; + } + + if ( is_bool( $value ) ) { + $buffer .= $key . ' ' . ( $value ? 'true' : 'false' ) . PHP_EOL; + return; + } + + if ( is_scalar( $value ) ) { + $buffer .= $key . ' ' . (string) $value . PHP_EOL; + return; + } + + if ( $value instanceof DateTime ) { + $buffer .= $key . '_iso ' . $value->format( 'r' ) . PHP_EOL; + $buffer .= $key . '_unix ' . $value->format( 'U' ) . PHP_EOL; + return; + } + + if ( is_object( $value ) ) { + $keys = get_object_vars( $value ); + } else { + $keys = &$value; + } + + if ( empty( $keys ) ) { + $buffer .= $key . PHP_EOL; + return; + } + + foreach ( $keys as $_key => $_value ) { + $__key = $key . self::DELIMITER . $_key; + self::__flatten( $buffer, $__key, $_value, $depth++ ); + } + } + +}