You need to sign in or sign up before continuing.
ServiceUrl.php 2.35 KB
Newer Older
Ketan's avatar
Ketan committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Magento\Store\Model\Argument\Interpreter;

use Magento\Framework\Data\Argument\InterpreterInterface;
use Magento\Store\Model\StoreRepository;
use Magento\Store\Model\StoreManagerInterface;

/**
 * Interpreter that builds Service URL by input path and optional parameters
 */
class ServiceUrl implements InterpreterInterface
{
    /**
     * @var \Magento\Framework\Url
     */
    private $url;

    /**
     * @var string
     */
    private $service;

    /**
     * @var StoreManagerInterface
     */
    private $storeManager;

    /**
     * @var string
     */
    private $version;

    /**
     * @var StoreRepository
     */
    private $storeRepository;

    /**
     * @param \Magento\Framework\Url $url
     * @param StoreManagerInterface $storeManager
     * @param StoreRepository $storeRepository
     * @param string $service
     * @param string $version
     */
    public function __construct(
        \Magento\Framework\Url $url,
        StoreManagerInterface $storeManager,
        StoreRepository $storeRepository,
        $service = "rest",
        $version = "V1"
    ) {
        $this->url = $url;
        $this->service = $service;
        $this->storeManager = $storeManager;
        $this->version = $version;
        $this->storeRepository = $storeRepository;
    }

    /**
     * Prepare rest suffix for url. For example rest/default/V1
     *
     * @return string
     */
    private function getServiceUrl()
    {
        $store = $this->storeRepository->getById($this->storeManager->getStore()->getId());
        return $this->url->getUrl(
            $this->service . "/" . $store->getCode() . "/" . $this->version
        );
    }

    /**
     * Compute and return effective value of an argument
     *
     * @param array $data
     * @return string
     * @throws \InvalidArgumentException
     */
    public function evaluate(array $data)
    {
        if (!isset($data['path']) || empty($data['path'])) {
            throw new \InvalidArgumentException('URL path is missing.');
        }

        if (isset($data['service'])) {
            $this->service = "rest";
        }

        if (isset($data["version"])) {
            $this->version = $data["version"];
        }

        return $this->getServiceUrl() . ltrim($data["path"], "/");
    }
}