<?php

namespace FiloBlu\Esb\Converter;

use Magento\Framework\DataObject;
use Magento\Framework\DataObjectFactory;
use Magento\Framework\Webapi\ServiceOutputProcessor;

/**
 * Class ObjectToDataObjectConverter
 * @package FiloBlu\Esb\Converter
 */
class ObjectToDataObjectConverter implements ConverterInterface
{

    /**
     * @var ServiceOutputProcessor
     */
    private $serviceOutputProcessor;
    /**
     * @var DataObjectFactory
     */
    private $dataObjectFactory;
    /**
     * @var string
     */
    private $type;

    /**
     * ObjectToDataObjectConverter constructor.
     * @param ServiceOutputProcessor $serviceOutputProcessor
     * @param DataObjectFactory $dataObjectFactory
     * @param string $type
     */
    public function __construct(
        ServiceOutputProcessor $serviceOutputProcessor,
        DataObjectFactory $dataObjectFactory,
        string $type
    ) {
        $this->serviceOutputProcessor = $serviceOutputProcessor;
        $this->dataObjectFactory = $dataObjectFactory;
        $this->type = $type;
    }

    /**
     * @param mixed $object
     * @return DataObject
     */
    public function convert($object): DataObject
    {
        return $this->dataObjectFactory->create([
            'data' => $this->serviceOutputProcessor->convertValue($object, $this->type)
        ]);
    }

    /**
     * @inheritDoc
     */
    public function canConvert($object): bool
    {
        return is_a($object, $this->type);
    }
}
