1

I would like to do this request :

curl -i -X OPTIONS my/url/path

in Magento 2.

This code works :

$ch = curl_init();
curl_setopt_array($ch, array(
    CURLOPT_URL => 'my/url/path',
    CURLOPT_CUSTOMREQUEST => 'OPTIONS',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HEADER => true,
    CURLOPT_NOBODY => true,
    CURLOPT_VERBOSE => true,
));
$r = curl_exec($ch);
print_r($r);
curl_close($ch);

But it's ugly code. I would like use dependency injection to clean my code.

Something like :

/**
 * @var \Magento\Framework\HTTP\Client\Curl
 */
protected $_curl;

/**
 * @param Context                             $context
 * @param \Magento\Framework\HTTP\Client\Curl $curl
 */
public function __construct(
    Context $context,
    \Magento\Framework\HTTP\Client\Curl $curl
) {
    $this->_curl = $curl;
    parent::__construct($context);
}

public function execute()
{
    //if the method is get
    $this->_curl->get($url);
    //if the method is post
    $this->_curl->post($url, $params);
    //response will contain the output in form of JSON string
    $response = $this->_curl->getBody();
}

But there is no OPTIONS method. So do you have any idea how to do?

2

1 Answer 1

1

Disclaimer: I've not actually tried this, so I'm mainly going based off an initial look over the code.

I guess you have 2 options, extend or workaround:

You could extend the Curl client class and use your own class from it. Then you'd be able to make your own options method that does something like $this->makeRequest("OPTIONS", $uri); to call the parent's makeRequest method. Instead of bringing in the Magento Curl client via DI, you'd just bring in your own.

Second option: Magento allows you to set _curlUserOptions values with a public method setOption($name, $value) on the curl client object. In the makeRequest($method, $uri, $params = []) method, these are set after the GET/POST options. I guess it could be possible that you can unset the CURLOPT_HTTPGET option for a get request and set your own CURLOPT_CUSTOMREQUEST there. Have a read through the file at vendor/magento/framework/HTTP/Client/Curl.php and look for the method makeRequest to see what it's doing properly.

Personally I'd make my own class extending the client but that's just me.

3
  • 1
    Thank you for your propostions. I'll try this if there is no other option
    – Kozame
    Commented Sep 3, 2019 at 15:23
  • @Kozame let me know which you go for, I'd like to know if it works as predicted myself. Good luck Commented Sep 3, 2019 at 16:11
  • 1
    I use your first solution : $this->makeRequest("OPTIONS", $uri); It's work well ! :)
    – Kozame
    Commented Sep 4, 2019 at 9:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.