<?php

use Illuminate\Contracts\Support\Arrayable;

if (!function_exists('must_get_namespace')) {
    function must_get_namespace ($file) {
        $namespace = null;

        if (preg_match('#^namespace\s+(.+?);$#sm', file_get_contents($file), $m)) {
            $namespace = $m[1];
        }
        if (!$namespace) {
            throw new RuntimeException(sprintf("get namespace fail from %s", $file));
        }

        return $namespace;
    }
}

if (!function_exists('path_join')) {
    function path_join (...$args) {
        $path = "";
        foreach ($args as $arg) {
            if (!$arg) continue;

            $path .= $path ? (DIRECTORY_SEPARATOR.trim($arg, DIRECTORY_SEPARATOR)) : rtrim($arg, DIRECTORY_SEPARATOR);
        }

        return $path;
    }
}

if (!function_exists('remove_all')) {
    function remove_all ($dir) {
        $files = array_diff(scandir($dir), ['.', '..']);
        foreach ($files as $file) {
            (is_dir("$dir/$file")) ? remove_all("$dir/$file") : unlink("$dir/$file");
        }
        return rmdir($dir);
    }
}

if (!function_exists('get_object_public_vars')) {
    function get_object_public_vars ($object): array {
        return get_object_vars($object);
    }
}

if (!function_exists('to_array')) {
    function to_array (array $var): array {
        return array_map(function ($value) {
            if ($value instanceof Arrayable) {
                return $value->toArray();
            } elseif (is_array($value)) {
                return to_array($value);
            } else {
                return $value;
            }
        }, $var);
    }
}

if (!function_exists('get_files')) {
    /**
     * Get files
     * @param $dir
     * @return array
     */
    function get_files ($dir) {
        $files = [];
        $scan = scandir($dir);
        foreach ($scan as $item) {
            if ($item == '.' || $item == '..') continue;
            if (is_dir($dir.'/'.$item)) {
                $files = array_merge($files, get_files($dir.'/'.$item));
            } else {
                $files[] = $dir.'/'.$item;
            }
        }
        return $files;
    }
}

if (!function_exists('get_git_branch_version')) {
    /**
     * Format the relative path as an absolute path with the current working directory as the reference
     *
     * @param string $base_path
     * @return string
     */
    function get_git_branch_version ($base_path = "") {
        if (!$version = env('CI_COMMIT_REF_SLUG')) {

            $git_file = $base_path ? $base_path.'/.git/HEAD' : base_path('/.git/HEAD');

            if (!file_exists($git_file)) {
                throw new \RuntimeException('get version fail');
            }

            $version = trim(str_replace(['ref: refs/heads/'], '', file_get_contents($git_file)));
            if (!$version) throw new \RuntimeException('get version fail');
        }
        return $version;
    }
}