<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace User\Validator;

use User\Entity\User;
use Laminas\Validator\AbstractValidator;

class UserEmailExistsValidator extends AbstractValidator
{
    const NOT_SCALAR    = 'notScalar';
    const EMAIL_EXISTS  = 'emailExists';

    protected $options = [
        'entityManager',
        'userInfo'
    ];

    protected $messageTemplates = [
        self::NOT_SCALAR    => "这不是一个标准输入值",
        self::EMAIL_EXISTS  => "该电子邮箱已经存在"
    ];

    public function __construct($options = null)
    {
        if(is_array($options)) {
            if(isset($options['entityManager']))    $this->options['entityManager'] = $options['entityManager'];
            if(isset($options['userInfo']))         $this->options['userInfo']      = $options['userInfo'];
        }

        parent::__construct($options);
    }

    public function isValid($value)
    {
        if(!is_scalar($value)) {
            $this->error(self::NOT_SCALAR);
            return false;
        }

        $entityManager  = $this->options['entityManager'];
        $user           = $entityManager->getRepository(User::class)->findOneByUserEmail($value);

        if($this->options['userInfo'] == null) {
            $isValid = ($user==null);
        } else {
            if($this->options['userInfo']->getUserEmail() != $value && $user != null)
                $isValid = false;
            else
                $isValid = true;
        }

        if(!$isValid) $this->error(self::EMAIL_EXISTS);

        return $isValid;
    }
}