<?php

/**
 * 数组核心类
 *
 * @author     呼吸二氧化碳 <jonwang@myqee.com>
 * @category   MyQEE
 * @package    System
 * @subpackage Core
 * @copyright  Copyright (c) 2008-2016 myqee.com
 * @license    http://www.myqee.com/license.html
 */
class Core_Arr extends ArrayIterator
{
    public function is_empty()
    {
        return empty($this->data);
    }

    /**
     * 获取数组
     *
     * @param  string $key column for associative keys
     * @param  string $value column for values
     * @return array
     */
    public function as_array($key = null, $value = null)
    {
        $results = array();

        $data = $this->getArrayCopy();

        if (null === $key && null === $value)
        {
            return $data;
        }
        elseif (null === $key)
        {
            foreach ($data as $row)
            {
                $results[] = $row[$value];
            }
        }
        elseif (null === $value)
        {
            foreach ($data as $row)
            {
                $results[$row[$key]] = $row;
            }
        }
        else
        {
            foreach ($data as $row)
            {
                $results[$row[$key]] = $row[$value];
            }
        }

        return $results;
    }

    /**
     * @var  string  default delimiter for path()
     */
    public static $delimiter = '.';

    /**
     * 判断一个数组是否递增key的数组
     *
     *     // Returns TRUE
     *     Arr::is_assoc(array('username' => 'john.doe'));
     *
     *     // Returns FALSE
     *     Arr::is_assoc('foo', 'bar');
     *
     * @param   array   array to check
     * @return  boolean
     */
    public static function is_assoc(array $array)
    {
        // Keys of the array
        $keys = array_keys($array);

        // If the array keys of the keys match the keys, then the array must
        // not be associative (e.g. the keys array looked like {0:0, 1:1...}).
        return array_keys($keys) !== $keys;
    }

    /**
     * 判断是否数组或对象型数组
     *
     *     // Returns TRUE
     *     Arr::is_array(array());
     *     Arr::is_array(new ArrayObject);
     *
     *     // Returns FALSE
     *     Arr::is_array(FALSE);
     *     Arr::is_array('not an array!');
     *     Arr::is_array(Database::instance());
     *
     * @param   mixed    value to check
     * @return  boolean
     */
    public static function is_array($value)
    {
        if (is_array($value))
        {
            // Definitely an array
            return true;
        }
        else
        {
            // Possibly a Traversable object, functionally the same as an array
            return (is_object($value) && $value instanceof Traversable);
        }
    }

    /**
     * Gets a value from an array using a dot separated path.
     *
     *     // Get the value of $array['foo']['bar']
     *     $value = Arr::path($array, 'foo.bar');
     *
     * Using a wildcard "*" will search intermediate arrays and return an array.
     *
     *     // Get the values of "color" in theme
     *     $colors = Arr::path($array, 'theme.*.color');
     *
     *     // Using an array of keys
     *     $colors = Arr::path($array, array('theme', '*', 'color'));
     *
     * @param   array  $array array to search
     * @param   mixed  $path key path string (delimiter separated) or array of keys
     * @param   mixed  $default default value if the path is not set
     * @param   string $delimiter key path delimiter
     * @return  mixed
     */
    public static function path($array, $path, $default = null, $delimiter = null)
    {
        if (!Arr::is_array($array))
        {
            // This is not an array!
            return $default;
        }

        if (is_array($path))
        {
            // The path has already been separated into keys
            $keys = $path;
        }
        else
        {
            if (array_key_exists($path, $array))
            {
                // No need to do extra processing
                return $array[$path];
            }

            if ($delimiter === null)
            {
                // Use the default delimiter
                $delimiter = Arr::$delimiter;
            }

            // Remove starting delimiters and spaces
            $path = ltrim($path, "{$delimiter} ");

            // Remove ending delimiters, spaces, and wildcards
            $path = rtrim($path, "{$delimiter} *");

            // Split the keys by delimiter
            $keys = explode($delimiter, $path);
        }

        do
        {
            $key = array_shift($keys);

            if (ctype_digit($key))
            {
                // Make the key an integer
                $key = (int)$key;
            }

            if (isset($array[$key]))
            {
                if ($keys)
                {
                    if (Arr::is_array($array[$key]))
                    {
                        // Dig down into the next part of the path
                        $array = $array[$key];
                    }
                    else
                    {
                        // Unable to dig deeper
                        break;
                    }
                }
                else
                {
                    // Found the path requested
                    return $array[$key];
                }
            }
            elseif ($key === '*')
            {
                // Handle wildcards

                $values = array();
                foreach ($array as $arr)
                {
                    if ($value = Arr::path($arr, implode('.', $keys)))
                    {
                        $values[] = $value;
                    }
                }

                if ($values)
                {
                    // Found the values requested
                    return $values;
                }
                else
                {
                    // Unable to dig deeper
                    break;
                }
            }
            else
            {
                // Unable to dig deeper
                break;
            }
        }
        while ($keys);

        // Unable to find the value requested
        return $default;
    }

    /**
    * Set a value on an array by path.
    *
    * @see Arr::path()
    * @param array   $array     Array to update
    * @param string  $path      Path
    * @param mixed   $value     Value to set
    * @param string  $delimiter Path delimiter
    */
    public static function set_path(&$array, $path, $value, $delimiter = null)
    {
        if (!$delimiter)
        {
            // Use the default delimiter
            $delimiter = Arr::$delimiter;
        }

        // Split the keys by delimiter
        $keys = explode($delimiter, $path);

        // Set current $array to inner-most array path
        while (count($keys) > 1)
        {
            $key = array_shift($keys);

            if (ctype_digit($key))
            {
                // Make the key an integer
                $key = (int) $key;
            }

            if (!isset($array[$key]))
            {
                $array[$key] = array();
            }

            $array = & $array[$key];
        }

        // Set key on inner-most array
        $array[array_shift($keys)] = $value;
    }

    /**
     * Fill an array with a range of numbers.
     *
     *     // Fill an array with values 5, 10, 15, 20
     *     $values = Arr::range(5, 20);
     *
     * @param   integer $step stepping
     * @param   integer $max ending number
     * @return  array
     */
    public static function range($step = 10, $max = 100)
    {
        if ($step < 1)
            return array();

        $array = array();
        for ($i = $step; $i <= $max; $i += $step)
        {
            $array[$i] = $i;
        }

        return $array;
    }

    /**
     * Retrieve a single key from an array. If the key does not exist in the
     * array, the default value will be returned instead.
     *
     *     // Get the value "username" from $_POST, if it exists
     *     $username = Arr::get($_POST, 'username');
     *
     *     // Get the value "sorting" from $_GET, if it exists
     *     $sorting = Arr::get($_GET, 'sorting');
     *
     * @param   array  $array array to extract from
     * @param   string $key key name
     * @param   mixed  $default default value
     * @return  mixed
     */
    public static function get($array, $key, $default = null)
    {
        return isset($array[$key]) ? $array[$key] : $default;
    }

    /**
     * Retrieves multiple keys from an array. If the key does not exist in the
     * array, the default value will be added instead.
     *
     *     // Get the values "username", "password" from $_POST
     *     $auth = Arr::extract($_POST, array('username', 'password'));
     *
     * @param   array $array  array to extract keys from
     * @param   array $keys  list of key names
     * @param   mixed $default  default value
     * @return  array
     */
    public static function extract($array, array $keys, $default = null)
    {
        $found = array();
        foreach ($keys as $key)
        {
            $found[$key] = isset($array[$key]) ? $array[$key] : $default;
        }

        return $found;
    }

    /**
     * Retrieves muliple single-key values from a list of arrays.
     *
     *     // Get all of the "id" values from a result
     *     $ids = Arr::pluck($result, 'id');
     *
     * [!!] A list of arrays is an array that contains arrays, eg: array(array $a, array $b, array $c, ...)
     *
     * @param   array  $array list of arrays to check
     * @param   string $key key to pluck
     * @return  array
     */
    public static function pluck($array, $key)
    {
        $values = array();

        foreach ($array as $row)
        {
            if (isset($row[$key]))
            {
                // Found a value in this row
                $values[] = $row[$key];
            }
        }

        return $values;
    }

    /**
     * Adds a value to the beginning of an associative array.
     *
     *     // Add an empty value to the start of a select list
     *     Arr::unshift($array, 'none', 'Select a value');
     *
     * @param   array   array to modify
     * @param   string  array key name
     * @param   mixed   array value
     * @return  array
     */
    public static function unshift( array & $array, $key, $val)
    {
        $array = array_reverse($array, TRUE);
        $array[$key] = $val;
        $array = array_reverse($array, TRUE);

        return $array;
    }

    /**
     * Recursive version of [array_map](http://php.net/array_map), applies the
     * same callback to all elements in an array, including sub-arrays.
     *
     *     // Apply "strip_tags" to every element in the array
     *     $array = Arr::map('strip_tags', $array);
     *
     * [!!] Unlike `array_map`, this method requires a callback and will only map
     * a single array.
     *
     * @param   mixed   callback applied to every element in the array
     * @param   array   array to map
     * @return  array
     */
    public static function map($callback, $array)
    {
        foreach ($array as $key => $val)
        {
            if (is_array($val))
            {
                $array[$key] = Arr::map($callback, $val);
            }
            else
            {
                $array[$key] = call_user_func($callback, $val);
            }
        }

        return $array;
    }

    /**
     * Merges one or more arrays recursively and preserves all keys.
     * Note that this does not work the same as [array_merge_recursive](http://php.net/array_merge_recursive)!
     *
     *     $john = array('name' => 'john', 'children' => array('fred', 'paul', 'sally', 'jane'));
     *     $mary = array('name' => 'mary', 'children' => array('jane'));
     *
     *     // John and Mary are married, merge them together
     *     $john = Arr::merge($john, $mary);
     *
     *     // The output of $john will now be:
     *     array('name' => 'mary', 'children' => array('fred', 'paul', 'sally', 'jane'))
     *
     * @param   array $a1 initial array
     * @param   array $a2 array to merge
     * @param   array  ...
     * @return  array
     */
    public static function merge(array $a1, array $a2)
    {
        $result = array();
        for ($i = 0, $total = func_num_args(); $i < $total; $i++)
        {
            // Get the next array
            $arr = func_get_arg($i);

            // Is the array associative?
            $assoc = Arr::is_assoc($arr);

            foreach ($arr as $key => $val)
            {
                if (isset($result[$key]))
                {
                    if (is_array($val) && is_array($result[$key]))
                    {
                        if (Arr::is_assoc($val))
                        {
                            // Associative arrays are merged recursively
                            $result[$key] = Arr::merge($result[$key], $val);
                        }
                        else
                        {
                            // Find the values that are not already present
                            $diff = array_diff($val, $result[$key]);

                            // Indexed arrays are merged to prevent duplicates
                            $result[$key] = array_merge($result[$key], $diff);
                        }
                    }
                    else
                    {
                        if ($assoc)
                        {
                            // Associative values are replaced
                            $result[$key] = $val;
                        }
                        elseif (!in_array($val, $result, true))
                        {
                            // Indexed values are added only if they do not yet exist
                            $result[] = $val;
                        }
                    }
                }
                else
                {
                    // New values are added
                    $result[$key] = $val;
                }
            }
        }

        return $result;
    }

    /**
     * Overwrites an array with values from input arrays.
     * Keys that do not exist in the first array will not be added!
     *
     *     $a1 = array('name' => 'john', 'mood' => 'happy', 'food' => 'bacon');
     *     $a2 = array('name' => 'jack', 'food' => 'tacos', 'drink' => 'beer');
     *
     *     // Overwrite the values of $a1 with $a2
     *     $array = Arr::overwrite($a1, $a2);
     *
     *     // The output of $array will now be:
     *     array('name' => 'jack', 'mood' => 'happy', 'food' => 'tacos')
     *
     * @param   array $array1  master array
     * @param   array $array2  input arrays that will overwrite existing values
     * @return  array
     */
    public static function overwrite($array1, $array2)
    {
        foreach (array_intersect_key($array2, $array1) as $key => $value)
        {
            $array1[$key] = $value;
        }

        if (func_num_args() > 2)
        {
            foreach (array_slice(func_get_args(), 2) as $array2)
            {
                foreach (array_intersect_key($array2, $array1) as $key => $value)
                {
                    $array1[$key] = $value;
                }
            }
        }

        return $array1;
    }


    /**
     * Creates a callable function and parameter list from a string representation.
     * Note that this function does not validate the callback string.
     *
     *     // Get the callback function and parameters
     *     list($func, $params) = Arr::callback('Foo::bar(apple,orange)');
     *
     *     // Get the result of the callback
     *     $result = call_user_func_array($func, $params);
     *
     * @param   string  callback string
     * @return  array   function, params
     */
    public static function callback($str)
    {
        // Overloaded as parts are found
        $command = $params = null;

        // command[param,param]
        if (preg_match('/^([^\(]*+)\((.*)\)$/', $str, $match))
        {
            // command
            $command = $match[1];

            if ($match[2] !== '')
            {
                // param,param
                $params = preg_split('/(?<!\\\\),/', $match[2]);
                $params = str_replace('\,', ',', $params);
            }
        }
        else
        {
            // command
            $command = $str;
        }

        if (strpos($command, '::') !== FALSE)
        {
            // Create a static method callable command
            $command = explode('::', $command, 2);
        }

        return array($command, $params);
    }

    /**
     * Convert a multi-dimensional array into a single-dimensional array.
     *
     *     $array = array('set' => array('one' => 'something'), 'two' => 'other');
     *
     *     // Flatten the array
     *     $array = Arr::flatten($array);
     *
     *     // The array will now be
     *     array('one' => 'something', 'two' => 'other');
     *
     * [!!] The keys of array values will be discarded.
     *
     * @param   array   array to flatten
     * @return  array
     */
    public static function flatten($array)
    {
        $flat = array();
        foreach ($array as $key => $value)
        {
            if (is_array($value))
            {
                $flat += Arr::flatten($value);
            }
            else
            {
                $flat[$key] = $value;
            }
        }
        return $flat;
    }

    /**
     * 从XML字符串解析获取一个数组
     *
     * 具体使用方法请参考 `Text::xml_to_array()` 方法
     *
     * @since 3.0
     * @use Text::xml_to_array
     * @param string|SimpleXMLElement $xml_string XML字符串，支持http的XML路径，接受 SimpleXMLElement 对象
     * @param string $attribute_key attributes所使用的key，默认 @attributes，设置成 true 则和内容自动合并
     * @param int $max_recursion_depth 解析最高层次，默认25
     * @param int|array $url_xml_setting 如果传入的 `$xml_string` 是URL，则允许缓存的时间或者是缓存配置的array，默认不缓存
     * @return array | false 失败则返回false
     */
    public static function from_xml($xml_string, $attribute_key = '@attributes', $max_recursion_depth = 25, $url_xml_setting = 0)
    {
        return Text::xml_to_array($xml_string, $attribute_key, $max_recursion_depth, $url_xml_setting);
    }

    /**
     * 将数组转换成XML字符串
     *
     * 本方法的反向方法为 `Text::xml_to_array($xml_string)`
     *
     *     // 返回格式化好的XML字符串
     *     Arr::to_xml($arr);
     *
     *     // XML缩进使用4个空格
     *     Arr::to_xml($arr, '    ');
     *
     *     // 返回不带任何换行符、空格的XML
     *     Arr::to_xml($arr, '', '');
     *
     * @param array $array 数组
     * @param string $tab 缩进字符，默认 tab 符
     * @param string $crlf 换行符，默认window换行符
     * @param string $attribute_key XML的attributes所在key，默认 `@attributes`
     * @param string $xml_header_string XML第一行声明的字符串
     * @return string
     */
    public static function to_xml(array $array, $tab = "\t", $crlf = CRLF, $attribute_key = '@attributes', $xml_header_string = null)
    {
        if (!$xml_header_string)
        {
            $w = '?';
            $xml_header_string = '<'. $w . 'xml version="1.0" encoding="UTF-8"'. $w .'>';
        }

        return $xml_header_string . Arr::_format_to_xml_string($array, $attribute_key, $crlf, $tab, '');
    }
    
    protected static function _format_to_xml_string($array, $attribute_key, $crlf, $tab, $left_str = '')
    {
        $str = '';

        if (isset($array['@name']))
        {
            $str .= "{$crlf}{$left_str}<{$array['@name']}";

            if (isset($array[$attribute_key]))
            {
                foreach($array[$attribute_key] as $k=>$v)
                {
                    Arr::_format_attribute_value($v);
                    $str .= " $k=\"{$v}\"";
                }
            }

            $str .= ">";

            $close_str = "{$crlf}{$left_str}</{$array['@name']}>";

            $left_str .= $tab;
        }
        else
        {
            $close_str = '';
        }

        if (isset($array['@tdata']))
        {
            $str .= "<![CDATA[{$array['@tdata']}]]>";
        }
        else
        {
            $have_str = false;
            foreach($array as $key => $value)
            {
                if ($key === '@name' || $key === $attribute_key || $key === '@data' || $key === '@tdata')continue;

                $have_str = true;

                if (is_array($value))
                {
                    if (!is_numeric($key))
                    {
                        $str .= "{$crlf}{$left_str}<{$key}";

                        if (isset($value[$attribute_key]))
                        {
                            foreach($value[$attribute_key] as $k=>$v)
                            {
                                $str .= " $k=\"{$v}\"";
                            }
                        }
                        $str .= ">";

                        if (isset($value['@data']))
                        {
                            Arr::_format_attribute_value($value['@data']);
                            $str .= "{$value['@data']}";
                        }
                        elseif (isset($value['@tdata']))
                        {
                            $str .= "<![CDATA[{$value['@tdata']}]]>";
                        }
                        else
                        {
                            $tmp_str = Arr::_format_to_xml_string($value, $attribute_key, $crlf, $tab, $left_str . $tab);
                            if (''!==$tmp_str)
                            {
                                $str .= $tmp_str."{$crlf}{$left_str}";
                            }
                            unset($tmp_str);
                        }
                        $str .= "</{$key}>";
                    }
                    else
                    {
                        $str .= Arr::_format_to_xml_string($value, $attribute_key, $crlf, $tab, $left_str);
                    }
                }
                else
                {
                    Arr::_format_attribute_value($value);
                    $str .= "{$crlf}{$left_str}<{$key}>{$value}</{$key}>";
                }
            }

            if ($have_str)
            {
                if ($close_str)
                {
                    $str .= $close_str;
                }
            }
            else
            {
                $str .= "</{$array['@name']}>";
            }
        }

        return $str;
    }


    protected static function _format_attribute_value(& $value)
    {
        if (true === $value)
        {
            $value = 'true';
        }
        elseif (false === $value)
        {
            $value = 'false';
        }
        elseif (null === $value)
        {
            $value = 'null';
        }
    }
}