<?php
/**
 * OpenMage
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Open Software License (OSL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * https://opensource.org/licenses/osl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magento.com so we can send you a copy immediately.
 *
 * @category    Tests
 * @package     Tests_Functional
 * @copyright  Copyright (c) 2006-2020 Magento, Inc. (https://www.magento.com)
 * @license    https://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 */

namespace Mage\Tax\Test\Handler\TaxClass;

use Magento\Mtf\Fixture\FixtureInterface;
use Magento\Mtf\Handler\Curl as AbstractCurl;
use Magento\Mtf\Util\Protocol\CurlInterface;
use Magento\Mtf\Util\Protocol\CurlTransport;
use Magento\Mtf\Util\Protocol\CurlTransport\BackendDecorator;

/**
 * Curl handler for creating customer and product tax class.
 */
class Curl extends AbstractCurl implements TaxClassInterface
{
    /**
     * Post request for creating tax class.
     *
     * @param FixtureInterface $fixture [optional]
     * @return array
     * @throws \Exception
     */
    public function persist(FixtureInterface $fixture = null)
    {
        $data = $fixture->getData();

        $url = $_ENV['app_backend_url'] . 'tax_class/save';
        $curl = new BackendDecorator(new CurlTransport(), $this->_configuration);
        $curl->write($url, $data);
        $response = $curl->read();
        $curl->close();

        if (!strpos($response, 'id="messages"')) {
            throw new \Exception('Tax rate creation by curl handler was not successful!');
        }

        $id = $this->getClassId($response);
        return ['id' => $id];
    }

    /**
     * Return saved class id if saved.
     *
     * @param $response
     * @return int|null
     */
    protected function getClassId($response)
    {
        preg_match_all('~tax_class[^\s]*\/id\/(\d+)~', $response, $match);

        return max(empty($match[1]) ? null : $match[1]);
    }
}
