<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Model;

use Hyperf\Context\Context;
use Hyperf\Coroutine\Coroutine;
use Hyperf\Database\Model\Builder;
use Hyperf\DbConnection\Model\Model as BaseModel;
use Hyperf\ModelCache\Cacheable;
use Hyperf\ModelCache\CacheableInterface;

abstract class Model extends BaseModel implements CacheableInterface
{
    use Cacheable;
    protected ?string $dateFormat = 'U';

    const ENABLED_FORMATTER = __CLASS__ . 'ENABLED_FORMATTER';

    public static function formatQuery(array $formatFields = []): Builder
    {
        Context::set(self::ENABLED_FORMATTER, $formatFields);
        return (new static())->newQuery();
    }

    public static function query(): Builder
    {
        Context::set(self::ENABLED_FORMATTER, []);
        return (new static())->newQuery();
    }

    protected function format(string $keyName, \Closure $callable)
    {
        $formatFields = Context::get(self::ENABLED_FORMATTER);
        return $callable(in_array($keyName, $formatFields ?: []));
    }
}
