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

namespace Shop\Validator;

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

class CheckoutAddressValidator extends AbstractValidator
{
    const NOT_SCALAR        = 'notScalar';
    const ADDRESS_NOT_EXISTS= 'addressNotExists';

    protected $messageTemplates = [
        self::NOT_SCALAR        => '这不是一个标准输入值',
        self::ADDRESS_NOT_EXISTS=> '您的收货地址不存在，请重新选择'
    ];

    protected $entityManager;
    protected $userId;

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

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

        $isValid = true;

        $addressInfo = $this->entityManager->getRepository(UserAddress::class)->findOneBy(['userId' => $this->userId, 'addressId' => $value]);
        if($addressInfo == null) {
            $isValid = false;
            $this->error(self::ADDRESS_NOT_EXISTS);
        }

        return $isValid;
    }
}