<?php

namespace Application\Service\Extension\Validator\customer;

use Application\Service\DB\AbstractDb;
use Application\Service\Extension\Validator\BaseCustomValidator;
use Laminas\Db\Sql\Predicate\Expression;
use Laminas\Db\Sql\Predicate\IsNotNull;
use Laminas\Db\Sql\Predicate\Predicate;
use Laminas\Db\Sql\Select;
use Laminas\Db\Sql\Sql;

class ExistValidator extends BaseCustomValidator
{
    /**
     * @var AbstractDb
     */
    public $targetClass;

    public $targetAttribute;

    public function __construct(array $config = [])
    {
        parent::__construct($config);
        if (!$this->targetClass) {
            throw new \Exception('请指定targetClass的值');
        }
    }

    public function isValid($value, $attribute)
    {
        if (is_string($this->targetAttribute)) {
            $this->targetAttribute = [$this->targetAttribute => $value];
        }elseif (is_array($this->targetAttribute)) {
            foreach ($this->targetAttribute as $key => $item) {
                if (is_numeric($key)) {
                    $this->targetAttribute[$item] = $value;
                    unset($this->targetAttribute[$key]);
                }
            }
        }

        if (!$this->fetch($this->targetAttribute)) {
            return $this->formatMessage('{attribute} 不存在.', [
                'attribute' => $this->getAttributeLabel($attribute)
            ]);
        }

        return null;
    }

    private function fetch(array $condition)
    {
        $sql = new Sql($this->targetClass->getAdapter());

        $select = new Select();

        $select->columns(['id'], false)->from($this->targetClass->getTableName())->where($condition);

        $childSelectSql = $sql->buildSqlString($select);

        return $this->targetClass->fetchOne([
            'where' => [
                new Expression('EXISTS (' . $childSelectSql . ')')
            ]
        ]);
    }
}