<?php
/**
 * Created by PhpStorm.
 * User: boyer
 * Date: 2020/8/21
 * Time: 17:35
 */
namespace Customs\Dg\Hmzb\Delivery;
use Customs\Dg\Hmzb\Delivery\Decl;
use Customs\Dg\Hmzb\Delivery\Ve;
use Customs\Dg\Hmzb\Delivery\Base;
class Xml{
    protected $base;
    protected $decl =[];
    protected $ve =[];
    public function setBase(Base $base){
        $this->base = $base;
    }

    public function addVe(Ve $ve){
        $this->ve[]=$ve;
    }

    public function addDecl(Decl $decl){
        $this->decl[]=$decl;
    }
    /**
     * Note:生成报文
     * User: Yao
     * Date: 2020/8/21
     * Time: 18:14
     * @return mixed
     */
    public function toXml(){
        $xml = [
            'DELIVERY_BASE'=>$this->base,
        ];
        if($this->decl){
            $xml['DECL_INFO_LIST']['DECL_INFO'] = $this->decl;
        }
        if($this->ve){
            $xml['VE_INFO_LIST']['VE_INFO'] = $this->ve;
        }
        $xmlArray = $this->arrayToData($xml);
        /*echo "xmlarr";
        var_dump($xmlArray);
        exit;*/
        return  \Common_ArrayToXml::convert($xmlArray,array(
            'rootElementName'=>'DELIVERY',
            '_attributes'=>array(
                'xmlns'=>'http://www.chinaport.gov.cn/nfha'
            ),
        ),
            true,
            'UTF-8',
            '1.0',
            [
                'formatOutput' => false,
                'encoding'=>'UTF-8'
            ]
        );
    }
    private function arrayToData($data){
        $return = array();
        foreach ($data as $key=>$value){
            if(is_array($value)){
                $return[$key] = $this->arrayToData($value);
            }elseif(is_object($value)){
                $return[$key] = $value->toArray();
            }else{
                $return[$key] = $value;
            }
        }
        return $return;
    }
}