<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/27
 * Time: 17:44
 */
namespace Modules\Share\Transformers;

use League\Fractal\TransformerAbstract;

class BaseTransformer extends TransformerAbstract
{
    protected static $extraIncludes = [];
    protected static $extraDefaultIncludes = [];

    public function __construct()
    {
        if (!isset(static::$extraIncludes[static::class])) {
            static::$extraIncludes[static::class] = [];
        }
        if (!isset(static::$extraDefaultIncludes[static::class])) {
            static::$extraDefaultIncludes[static::class] = [];
        }

        $this->availableIncludes = array_merge($this->availableIncludes, static::$extraIncludes[static::class]);
        $this->defaultIncludes = array_merge($this->defaultIncludes, static::$extraDefaultIncludes[static::class]);
    }

    public static function addIncludes($name)
    {
        if (!isset(static::$extraIncludes[static::class])) {
            static::$extraIncludes[static::class] = [];
        }
        $name = (array) $name;
        $temp = [];
        foreach ($name as $key => $value) {
            if (is_string($key) && $value instanceof \Closure) {
                static::macro('include'.ucfirst($key), $value);
                $value = $key;
            }
            $temp[] = $value;
        }
        static::$extraIncludes[static::class] = array_merge(static::$extraIncludes[static::class], $temp);
    }

    public static function addDefaultIncludes($name)
    {
        if (!isset(static::$extraDefaultIncludes[static::class])) {
            static::$extraDefaultIncludes[static::class] = [];
        }
        static::$extraDefaultIncludes[static::class] += (array) $name;
    }

    /**
     * 修改返回
     *
     * @param $arr
     *
     * @return mixed
     */
    public function alter($arr)
    {
        return $arr;
    }

    public static function checkExtraInclude($key)
    {
        static $extra_includes;

        if ($extra_includes == null) {
            $extra_includes = array_map('trim', explode(',', request('extra_include', '')));
        }

        return array_search($key, $extra_includes) === false ? false : true;
    }

    public function single($value, $transformer)
    {
        return $value ? $this->item($value, $transformer) : null;
    }
}
