<commit_before>{#
    This file is part of the CloudStack Client Generator.

    (c) <NAME> <<EMAIL>>
    (c) <NAME> <<EMAIL>>
    (c) <NAME> <<EMAIL>>
    (c) <NAME> <<EMAIL>>
    (c) <NAME> <<EMAIL>>

    For the full copyright and license information, please view the LICENSE
    file that was distributed with this source code.
#}
{% autoescape false %}
<?php{% if config.namespace != '' %} namespace {{ config.namespace }};{% endif %}

/*
 * This file was autogenerated as part of the CloudStack PHP Client.
 *
 * Date Generated: {{ config.now.format('Y-m-d') }}
 * API Version: {{ capabilities.capability.cloudstackversion }}
 *
 * (c) <NAME> {{ '<<EMAIL>>'|raw }}
 * (c) <NAME> {{ '<<EMAIL>>'|raw }}
 * (c) <NAME> {{ '<<EMAIL>>'|raw }}
 * (c) <NAME> {{ '<<EMAIL>>'|raw }}
 * (c) <NAME> {{ '<<EMAIL>>'|raw }}
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Uri;
use GuzzleHttp\RequestOptions;
use Psr\Http\Message\ResponseInterface;

/**
 * CloudStackClient class
 * @package \{% if config.namespace != '' %}{{ config.namespace }}{% endif %}
 */
class CloudStackClient {

    /** @var CloudStackConfiguration */
    protected $configuration;

    /**
     * CloudStackClient constructor
     *
     * @param CloudStackConfiguration $configuration
     */
    public function __construct(CloudStackConfiguration $configuration) {
        $this->configuration = $configuration;
    }

{% for api in apis %}
{% include "method.php.twig" with {'api' : api, 'config' : config} %}

{% endfor %}

    /**
     * @param string $vmId
     * @return \{% if config.namespace != '' %}{{ config.namespace }}\{% endif %}CloudStackResponse\AccessVmConsoleProxyResponse
     */
    public function accessVmConsoleProxy($vmId) {
        $response = $this->doRequest(new CloudStackRequest\AccessVmConsoleProxyRequest($vmId), false);

        $body = $response->getBody();

        $model = new CloudStackResponse\AccessVmConsoleProxyResponse();
        $data = '';
        while (!$body->eof() && $b = $body->read(8192)) {
            $data .= $b;
        }

        $model->iframe = $data;

        return $model;
    }

    /**
     * Will wait until either $tries threshold is met or async job completes, successful or otherwise.
     *
     * @param \{% if config.namespace != '' %}{{ config.namespace }}\{% endif %}CloudStackResponse\AsyncJobStartResponse $startResponse
     * @param int $sleep
     * @param int $tries
     * @return \{% if config.namespace != '' %}{{ config.namespace }}\{% endif %}CloudStackResponse\QueryAsyncJobResultResponse|null
     * @throws \InvalidArgumentException
     */
    public function waitForAsync(CloudStackResponse\AsyncJobStartResponse $startResponse, $sleep = 2, $tries = 120) {
        // Some basic validation
        if (!is_int($sleep) || 0 >= $sleep) {
            throw new \InvalidArgumentException(sprintf(
                '%s::waitForAsyncResponse - $sleep must be positive integer, %s seen.',
                get_class($this),
                is_int($sleep) ? $sleep : gettype($sleep)
            ));
        }

        if (!is_int($tries) || (-1 > $tries || 0 === $tries)) {
            throw new \InvalidArgumentException(sprintf(
                '%s:waitForAsyncResponse - $tries must be positive integer or -1 for infinite, %s seen.',
                get_class($this),
                is_int($tries) ? $tries : gettype($tries)
            ));
        }

        $attempts = 0;
        while(true) {
            $result = $this->queryAsyncJobResult($startResponse->jobid);

            if (2 === $result->jobstatus || 2 === $result->jobprocstatus) {
                throw new \RuntimeException($result->jobresult['errortext'], $result->jobresult['errorcode']);
            }

            if (0 === $result->jobstatus) {
                if (-1 !== $tries && $attempts > $tries) {
                    return null;
                }
                sleep($sleep);
            } else {
                if (isset($result->jobresult) && is_array($result->jobresult) && 0 < count($result->jobresult)) {
                    $class = $startResponse->getResponseClassName();

                    // check for simple async responses (i.e.: ["success" => true])
                    $first = reset($result->jobresult);

                    if (is_array($first)) {
                        $result->jobresult = new $class($first);
                    } else {
                        $result->jobresult = new $class($result->jobresult);
                    }
                }
                return $result;
            }
        }

        return null;
    }

    /**
     * Execute Request against CloudStack
     * @param \{% if config.namespace != '' %}{{ config.namespace }}\{% endif %}CloudStackRequest\CloudStackRequestInterface
     * @param bool $decode
     * @return mixed
     */
    public function doRequest(CloudStackRequest\CloudStackRequestInterface $request, $decode = true) {
        $resp = $this->configuration->getHttpClient()->send($this->createPsr7Request($request), [
            RequestOptions::HTTP_ERRORS => false,
            RequestOptions::DECODE_CONTENT => false,
        ]);

        // Check for 200..
        if (200 !== $resp->getStatusCode()) {
            // attempt to decode response...
            $data = $resp->getBody()->getContents();
            $decoded = @json_decode($data, true);
            if (JSON_ERROR_NONE === json_last_error()) {
                if (1 === count($decoded)) {
                    $decoded = reset($decoded);
                }
                if (isset($decoded['errortext'])) {
                    throw new CloudStackAPIException($decoded);
                }
            }
            throw new \RuntimeException(sprintf('Received non-200 response: %d %s.  Body: %s', $resp->getStatusCode(), $resp->getReasonPhrase(), $bodyContents), NO_VALID_JSON_RECEIVED);
        }

        if ($decode) {
            $responseModel = $request->getCloudStackResponseModel();

            $decoded = $this->decodeBody($resp, $request->getCloudStackCommandName());

            if ($request instanceof CloudStackRequest\CloudStackAsynchronousRequest) {
                return new CloudStackResponse\AsyncJobStartResponse($decoded, $responseModel);
            }

            if ($request instanceof CloudStackRequest\CloudStackListRequest) {
                $ret = [];
                if ($decoded) {
                    unset($decoded['count']);
                    foreach(reset($decoded) as $item) {
                        $ret[] = new $responseModel($item);
                    }
                }
                return $ret;
            }<commit_msg>Fixing incorrect reference to $bodyContents<commit_after>{#
    This file is part of the CloudStack Client Generator.

    (c) <NAME> <<EMAIL>>
    (c) <NAME> <<EMAIL>>
    (c) <NAME> <<EMAIL>>
    (c) <NAME> <<EMAIL>>
    (c) <NAME> <<EMAIL>>

    For the full copyright and license information, please view the LICENSE
    file that was distributed with this source code.
#}
{% autoescape false %}
<?php{% if config.namespace != '' %} namespace {{ config.namespace }};{% endif %}

/*
 * This file was autogenerated as part of the CloudStack PHP Client.
 *
 * Date Generated: {{ config.now.format('Y-m-d') }}
 * API Version: {{ capabilities.capability.cloudstackversion }}
 *
 * (c) <NAME> {{ '<<EMAIL>>'|raw }}
 * (c) <NAME> {{ '<<EMAIL>>'|raw }}
 * (c) <NAME> {{ '<<EMAIL>>'|raw }}
 * (c) <NAME> {{ '<<EMAIL>>'|raw }}
 * (c) <NAME> {{ '<<EMAIL>>'|raw }}
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Uri;
use GuzzleHttp\RequestOptions;
use Psr\Http\Message\ResponseInterface;

/**
 * CloudStackClient class
 * @package \{% if config.namespace != '' %}{{ config.namespace }}{% endif %}
 */
class CloudStackClient {

    /** @var CloudStackConfiguration */
    protected $configuration;

    /**
     * CloudStackClient constructor
     *
     * @param CloudStackConfiguration $configuration
     */
    public function __construct(CloudStackConfiguration $configuration) {
        $this->configuration = $configuration;
    }

{% for api in apis %}
{% include "method.php.twig" with {'api' : api, 'config' : config} %}

{% endfor %}

    /**
     * @param string $vmId
     * @return \{% if config.namespace != '' %}{{ config.namespace }}\{% endif %}CloudStackResponse\AccessVmConsoleProxyResponse
     */
    public function accessVmConsoleProxy($vmId) {
        $response = $this->doRequest(new CloudStackRequest\AccessVmConsoleProxyRequest($vmId), false);

        $body = $response->getBody();

        $model = new CloudStackResponse\AccessVmConsoleProxyResponse();
        $data = '';
        while (!$body->eof() && $b = $body->read(8192)) {
            $data .= $b;
        }

        $model->iframe = $data;

        return $model;
    }

    /**
     * Will wait until either $tries threshold is met or async job completes, successful or otherwise.
     *
     * @param \{% if config.namespace != '' %}{{ config.namespace }}\{% endif %}CloudStackResponse\AsyncJobStartResponse $startResponse
     * @param int $sleep
     * @param int $tries
     * @return \{% if config.namespace != '' %}{{ config.namespace }}\{% endif %}CloudStackResponse\QueryAsyncJobResultResponse|null
     * @throws \InvalidArgumentException
     */
    public function waitForAsync(CloudStackResponse\AsyncJobStartResponse $startResponse, $sleep = 2, $tries = 120) {
        // Some basic validation
        if (!is_int($sleep) || 0 >= $sleep) {
            throw new \InvalidArgumentException(sprintf(
                '%s::waitForAsyncResponse - $sleep must be positive integer, %s seen.',
                get_class($this),
                is_int($sleep) ? $sleep : gettype($sleep)
            ));
        }

        if (!is_int($tries) || (-1 > $tries || 0 === $tries)) {
            throw new \InvalidArgumentException(sprintf(
                '%s:waitForAsyncResponse - $tries must be positive integer or -1 for infinite, %s seen.',
                get_class($this),
                is_int($tries) ? $tries : gettype($tries)
            ));
        }

        $attempts = 0;
        while(true) {
            $result = $this->queryAsyncJobResult($startResponse->jobid);

            if (2 === $result->jobstatus || 2 === $result->jobprocstatus) {
                throw new \RuntimeException($result->jobresult['errortext'], $result->jobresult['errorcode']);
            }

            if (0 === $result->jobstatus) {
                if (-1 !== $tries && $attempts > $tries) {
                    return null;
                }
                sleep($sleep);
            } else {
                if (isset($result->jobresult) && is_array($result->jobresult) && 0 < count($result->jobresult)) {
                    $class = $startResponse->getResponseClassName();

                    // check for simple async responses (i.e.: ["success" => true])
                    $first = reset($result->jobresult);

                    if (is_array($first)) {
                        $result->jobresult = new $class($first);
                    } else {
                        $result->jobresult = new $class($result->jobresult);
                    }
                }
                return $result;
            }
        }

        return null;
    }

    /**
     * Execute Request against CloudStack
     * @param \{% if config.namespace != '' %}{{ config.namespace }}\{% endif %}CloudStackRequest\CloudStackRequestInterface
     * @param bool $decode
     * @return mixed
     */
    public function doRequest(CloudStackRequest\CloudStackRequestInterface $request, $decode = true) {
        $resp = $this->configuration->getHttpClient()->send($this->createPsr7Request($request), [
            RequestOptions::HTTP_ERRORS => false,
            RequestOptions::DECODE_CONTENT => false,
        ]);

        // Check for 200..
        if (200 !== $resp->getStatusCode()) {
            // attempt to decode response...
            $data = $resp->getBody()->getContents();
            $decoded = @json_decode($data, true);
            if (JSON_ERROR_NONE === json_last_error()) {
                if (1 === count($decoded)) {
                    $decoded = reset($decoded);
                }
                if (isset($decoded['errortext'])) {
                    throw new CloudStackAPIException($decoded);
                }
            }
            throw new \RuntimeException(sprintf('Received non-200 response: %d %s.  Body: %s', $resp->getStatusCode(), $resp->getReasonPhrase(), $data), NO_VALID_JSON_RECEIVED);
        }

        if ($decode) {
            $responseModel = $request->getCloudStackResponseModel();

            $decoded = $this->decodeBody($resp, $request->getCloudStackCommandName());

            if ($request instanceof CloudStackRequest\CloudStackAsynchronousRequest) {
                return new CloudStackResponse\AsyncJobStartResponse($decoded, $responseModel);
            }

            if ($request instanceof CloudStackRequest\CloudStackListRequest) {
                $ret = [];
                if ($decoded) {
                    unset($decoded['count']);
                    foreach(reset($decoded) as $item) {
                        $ret[] = new $responseModel($item);
                    }
                }
                return $ret;
            }
{'fraction_non_alphanumeric': 0.14707180694526192, 'fraction_numerical': 0.004561506768687463, 'mean_word_length': 2.153096729297147, 'pattern_counts': {'":': 0, '<': 67, '<?xml version=': 0, '>': 141, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5293183', 'n_tokens_mistral': 3861, 'n_tokens_neox': 3641, 'n_words': 854}