<?php
// +----------------------------------------------------------------------
// | onezan-admin 快速开发的管理平台
// +----------------------------------------------------------------------
// | 官方网址：https://www.onezan.cn
// +----------------------------------------------------------------------
// | onezan团队 版权所有 开源版本可自由商用
// +----------------------------------------------------------------------
// | Author: 543885307@qq.com
// +----------------------------------------------------------------------
namespace Applications\sample\plugins\notice\validate\domain;

use app\validate\domain\DomainValidatorInterface;
use Applications\sample\plugins\notice\repository\NoticeRepository;

/**
 * Notice Domain Validator
 * @package Applications\sample\plugins\notice\validate\domain
 */
class NoticeDomainValidator implements DomainValidatorInterface
{
    /**
     * @var NoticeRepository
     */
    private $repository;

    public function __construct(\think\App $app)
    {
        $this->repository = $app->make(NoticeRepository::class);
    }


    /**
     * 验证公告数据
     * @param array $data 待验证数据
     * @param string $scene 验证场景
     * @return array
     */
    public function validate(array $data, string $scene = ''): array
    {
        $errors = [];

        if ($scene === 'save') {
            $id = isset($data['id']) && is_numeric($data['id']) ? (int)$data['id'] : 0;
            $code = trim((string)($data['code'] ?? ''));
            if ($code !== '' && $this->repository->existsCode($code, $id)) {
                $errors['code'] = '公告编码已存在';
            }
        }

        if ($scene === 'delete') {
            $id = isset($data['id']) && is_numeric($data['id']) ? (int)$data['id'] : 0;
            if ($id <= 0 || $this->repository->findById($id) === null) {
                $errors['id'] = '记录不存在';
            }
        }

        return ['ok' => empty($errors), 'errors' => $errors];
    }
}
