<?php

namespace App\libs;

use Illuminate\Support\Env;
use Illuminate\Support\Facades\Config;
use Symfony\Component\HttpFoundation\File\Exception\FileException;

/**
 * @desc    预设文件加载
 */
class PreInstall
{
    private static $data = [];

    /**
     * @desc    获得配置
     *
     * @param string $type 扩展名称
     *
     * @return array|mixed
     */
    public static function config(string $type)
    {
        $id = Env::get($type . '.id', Config::get('lc.' . $type . '.id'));
        if (!$id) {
            return [];
        }

        return self::get($type, $id);
    }

    /**
     * @desc    获取指定配置
     *
     * @param string      $type 扩展名称
     * @param string|null $id   指定id
     *
     * @return array|mixed
     */
    public static function get(string $type, string $id = null)
    {
        if (!isset($data[$type])) {
            self::load($type);
        }
        if (!isset(self::$data[$type])) {
            return [];
        }
        $data = self::$data[$type];
        if ($id) {
            return $data[$id] ?? [];
        }

        return $data;
    }

    private static function load($type): void
    {
        $file = __DIR__ . '/preinstall/' . $type . '.php';
        if (!file_exists($file)) {
            throw new FileException('SWDZ预设文件不存在：' . $file);
        }
        self::$data[$type] = include $file;
    }
}
