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

namespace Sales\Validator;

use Laminas\Validator\AbstractValidator;
use Sales\Entity\OrderGoods;

class ShipOneOrderGoodsValidator extends AbstractValidator
{
    const NOT_SCALAR    = 'notScalar';
    const GOODS_ERROR   = 'goodsError';

    protected $messageTemplates = [
        self::NOT_SCALAR        => "这不是一个标准输入值",
        self::GOODS_ERROR       => "部分商品信息无效"
    ];

    private $entityManager;
    private $orderId;

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

        parent::__construct($options);
    }

    public function isValid($value)
    {
        $isValid = true;

        if (!is_array($value) && !empty($value)) {
            $this->error(self::NOT_SCALAR);
            return false;
        }

        foreach ($value as $item) {
            if(empty($item) || intval($item) <= 0) {
                $this->error(self::GOODS_ERROR);
                return false;
            }
            $orderGoodsInfo = $this->entityManager->getRepository(OrderGoods::class)->findOneBy(['goodsId' => $item, 'orderId' => $this->orderId]);
            if($orderGoodsInfo == null) {
                $this->error(self::GOODS_ERROR);
                return false;
            }
        }

        return $isValid;
    }
}