<?php

namespace Atom\runtime_7456b800;

/**
 * 通用的工具函数集
 *
 * @package Atom\runtime_7456b800
 * @auther lvsheng
 */
class Atom_Util_Shared {

    /**
     * 是否以某个字符串开头
     * @param $string string
     * @param $prefix string
     * @return bool
     */
    public static function startsWith($string, $prefix) {
        return substr_compare($string, $prefix, 0, strlen($prefix)) === 0;
    }

    /**
     * 是否数字或字符串
     * @param $val mixed
     * @return bool
     */
    public static function isPrimitive($val) {
        return is_string($val) || is_numeric($val);
    }

    /**
     * 是否索引数组
     * @param $arr mixed
     * @return bool
     */
    public static function isPlainArray($arr) {
        if (is_array($arr)) {
            $i = 0;
            foreach ($arr as $k => $v) {
                if ($k !== $i++) {
                    return false;
                }
            }
            return true;
        }
        return false;
    }

    /**
     * 驼峰化
     * @param $str string
     * @return mixed
     */
    public static function camelize($str) {
        static $cache = array();
        if (isset($cache[$str])) {
            return $cache[$str];
        }
        $origin = $str;
        preg_match_all('/-(\w)/', $str, $match);
        foreach ($match[0] as $i => $e) {
            $str = str_replace($e, strtoupper($match[1][$i]), $str);
        }
        $cache[$origin] = $str;
        return $str;
    }

    /**
     * Pascal化
     * todo: cache
     * @param $str string
     * @return string
     */
    public static function capitalize($str) {
        $arr = str_split($str);
        $arr[0] = strtoupper($arr[0]);
        return join('', $arr);
    }


    /**
     * 反camelize化
     * @param $str string
     * @return mixed
     */
    public static function inCamelize($str) {

        static $cache = array();

        if (isset($cache[$str])) {
            return $cache[$str];
        }

        $result = $str;
        preg_match_all('/([A-Z])/', $str, $match);
        foreach ($match[0] as $i => $e) {
            $result = str_replace($e, '-' . strtolower($match[1][$i]), $result);
        }
        $cache[$str] = $result;
        return $result;
    }

    /**
     * 数据混合
     * @param $to array|object
     * @param $from array|object
     * @return mixed
     */
    public static function extendData($to, $from) {
        foreach ($from as $k => $v) {
            $to[$k] = $v;
        }
        return $to;
    }
}
