protected function ensureUrlOrFile($input, $type = null)
    {
        if ($input instanceof File) {
            $this->_tmpFiles[] = $input;
            return $input;
        } elseif (preg_match(self::REGEX_URL, $input)) {
            return $input;
        } elseif ($type === self::TYPE_XML || $type === null && preg_match(self::REGEX_XML, $input)) {
            $ext = '.xml';
        } else {
            // First check for obvious HTML content to avoid is_file() as much
            // as possible as it can trigger open_basedir restriction warnings
            // with long strings.
            $isHtml = $type === self::TYPE_HTML || preg_match(self::REGEX_HTML, $input);
            if (!$isHtml) {
                $maxPathLen = defined('PHP_MAXPATHLEN') ?
                    constant('PHP_MAXPATHLEN') : self::MAX_PATHLEN;
                if (strlen($input) <= $maxPathLen && is_file($input)) {
                    return $input;
                }
            }
            $ext = '.html';
        }
        $file = new File($input, $ext, self::TMP_PREFIX, $this->tmpDir);
        $this->_tmpFiles[] = $file;
        return $file;
    }

This method creates a temporary file if the passed argument is neither a
File instance or URL nor contains XML or HTML and is also not a valid
file name.

@param string|File $input the input argument File to check
@param string|null $type a type hint if the input is a string of known
type. This can either be `TYPE_HTML` or `TYPE_XML`. If `null` (default)
the type is auto detected from the string content.
@return \mikehaertl\tmp\File|string a File object if the input is a HTML
or XML string. The unchanged input otherwhise.

This method creates a temporary file if the passed argument is neither a File instance or URL nor contains XML or HTML and is also not a valid file name .


private static function createClient(array $options)
    {
        $verify = true;
        //Disable SSL if proxy has been set, and set the proxy in the client.
        $proxy = getenv('HTTP_PROXY');
        // For testing with Fiddler
        // $proxy = 'localhost:8888';
        // $verify = false;
        if (!empty($proxy)) {
            $options['proxy'] = $proxy;
        }

        if (!empty($options['verify'])) {
            $verify = $options['verify'];
        }

        return (new \GuzzleHttp\Client(
            array_merge(
                $options,
                array(
                    "defaults" => array(
                        "allow_redirects" => true,
                        "exceptions" => true,
                        "decode_content" => true,
                    ),
                    'cookies' => true,
                    'verify' => $verify,
                )
            )
        ));
    }

Create a Guzzle client for future usage.

@param  array $options Optional parameters for the client.

@return Client

Create a Guzzle client for future usage .


protected function createMiddlewareStack(ServiceOptions $serviceOptions)
    {
        //If handler stack is not defined by the user, create a default
        //middleware stack.
        $stack = null;
        if (array_key_exists('stack', $this->options['http'])) {
            $stack = $this->options['http']['stack'];
        } elseif ($serviceOptions->getMiddlewareStack() != null) {
            $stack = $serviceOptions->getMiddlewareStack();
        } else {
            $stack = new MiddlewareStack();
        }

        //Push all the middlewares specified in the $serviceOptions to the
        //handlerstack.
        if ($serviceOptions->getMiddlewares() != array()) {
            foreach ($serviceOptions->getMiddlewares() as $middleware) {
                $stack->push($middleware);
            }
        }

        //Push all the middlewares specified in the $options to the
        //handlerstack.
        if (array_key_exists('middlewares', $this->options)) {
            foreach ($this->options['middlewares'] as $middleware) {
                $stack->push($middleware);
            }
        }

        //Push all the middlewares specified in $this->middlewares to the
        //handlerstack.
        foreach ($this->getMiddlewares() as $middleware) {
            $stack->push($middleware);
        }

        return $stack;
    }

Create a middleware stack with given middleware.

@param  ServiceOptions  $serviceOptions The options user passed in.

@return MiddlewareStack

Create a middleware stack with given middleware .


protected function createRequest(
        $method,
        array $headers,
        array $queryParams,
        array $postParameters,
        $path,
        $locationMode,
        $body = Resources::EMPTY_STRING
    ) {
        if ($locationMode == LocationMode::SECONDARY_ONLY ||
            $locationMode == LocationMode::SECONDARY_THEN_PRIMARY) {
            $uri = $this->psrSecondaryUri;
        } else {
            $uri = $this->psrPrimaryUri;
        }

        //Append the path, not replacing it.
        if ($path != null) {
            $exPath = $uri->getPath();
            if ($exPath != '') {
                //Remove the duplicated slash in the path.
                if ($path != '' && $path[0] == '/') {
                    $path = $exPath . substr($path, 1);
                } else {
                    $path = $exPath . $path;
                }
            }
            $uri = $uri->withPath($path);
        }

        // add query parameters into headers
        if ($queryParams != null) {
            $queryString = Psr7\build_query($queryParams);
            $uri = $uri->withQuery($queryString);
        }

        // add post parameters into bodys
        $actualBody = null;
        if (empty($body)) {
            if (empty($headers['content-type'])) {
                $headers['content-type'] = 'application/x-www-form-urlencoded';
                $actualBody = Psr7\build_query($postParameters);
            }
        } else {
            $actualBody = $body;
        }

        $request = new Request(
            $method,
            $uri,
            $headers,
            $actualBody
        );

        //add content-length to header
        $bodySize = $request->getBody()->getSize();
        if ($bodySize > 0) {
            $request = $request->withHeader('content-length', $bodySize);
        }
        return $request;
    }

Create the request to be sent.

@param  string $method         The method of the HTTP request
@param  array  $headers        The header field of the request
@param  array  $queryParams    The query parameter of the request
@param  array  $postParameters The HTTP POST parameters
@param  string $path           URL path
@param  string $body           Request body

@return \GuzzleHttp\Psr7\Request


protected function sendAsync(
        $method,
        array $headers,
        array $queryParams,
        array $postParameters,
        $path,
        $expected = Resources::STATUS_OK,
        $body = Resources::EMPTY_STRING,
        ServiceOptions $serviceOptions = null
    ) {
        if ($serviceOptions == null) {
            $serviceOptions = new ServiceOptions();
        }
        $this->addOptionalQueryParam(
            $queryParams,
            Resources::QP_TIMEOUT,
            $serviceOptions->getTimeout()
        );

        $request = $this->createRequest(
            $method,
            $headers,
            $queryParams,
            $postParameters,
            $path,
            $serviceOptions->getLocationMode(),
            $body
        );

        $client = $this->client;

        $middlewareStack = $this->createMiddlewareStack($serviceOptions);

        $sendAsync = function ($request, $options) use ($client) {
            return $client->sendAsync($request, $options);
        };

        $handler = $middlewareStack->apply($sendAsync);

        $requestOptions =
            $this->generateRequestOptions($serviceOptions, $handler);

        if ($request->getMethod() == 'HEAD') {
            $requestOptions[Resources::ROS_DECODE_CONTENT] = false;
        }

        $promise = \call_user_func($handler, $request, $requestOptions);

        return $promise->then(
            function ($response) use ($expected, $requestOptions) {
                self::throwIfError(
                    $response,
                    $expected
                );

                return self::addLocationHeaderToResponse(
                    $response,
                    $requestOptions[Resources::ROS_LOCATION_MODE]
                );
            },
            function ($reason) use ($expected) {
                if (!($reason instanceof RequestException)) {
                    throw $reason;
                }
                $response = $reason->getResponse();
                if ($response != null) {
                    self::throwIfError(
                        $response,
                        $expected
                    );
                } else {
                    //if could not get response but promise rejected, throw reason.
                    throw $reason;
                }
                return $response;
            }
        );
    }

Create promise of sending HTTP request with the specified parameters.

@param  string         $method         HTTP method used in the request
@param  array          $headers        HTTP headers.
@param  array          $queryParams    URL query parameters.
@param  array          $postParameters The HTTP POST parameters.
@param  string         $path           URL path
@param  array|int      $expected       Expected Status Codes.
@param  string         $body           Request body
@param  ServiceOptions $serviceOptions Service options

@return \GuzzleHttp\Promise\PromiseInterface

Create promise of sending HTTP request with the specified parameters .


protected function generateRequestOptions(
        ServiceOptions $serviceOptions,
        callable $handler
    ) {
        $result = array();
        $result[Resources::ROS_LOCATION_MODE]  = $serviceOptions->getLocationMode();
        $result[Resources::ROS_STREAM]         = $serviceOptions->getIsStreaming();
        $result[Resources::ROS_DECODE_CONTENT] = $serviceOptions->getDecodeContent();
        $result[Resources::ROS_HANDLER]        = $handler;
        $result[Resources::ROS_SECONDARY_URI]  = $this->getPsrSecondaryUri();
        $result[Resources::ROS_PRIMARY_URI]    = $this->getPsrPrimaryUri();

        return $result;
    }

protected function generateRequestOptions ( ServiceOptions $ serviceOptions , callable $ handler ) { $ result = array ( ) ; $ result [ Resources :: ROS_LOCATION_MODE ] = $ serviceOptions -> getLocationMode ( ) ; $ result [ Resources :: ROS_STREAM ] = $ serviceOptions -> getIsStreaming ( ) ; $ result [ Resources :: ROS_DECODE_CONTENT ] = $ serviceOptions -> getDecodeContent ( ) ; $ result [ Resources :: ROS_HANDLER ] = $ handler ; $ result [ Resources :: ROS_SECONDARY_URI ] = $ this -> getPsrSecondaryUri ( ) ; $ result [ Resources :: ROS_PRIMARY_URI ] = $ this -> getPsrPrimaryUri ( ) ; return $ result ; }

Generate the request options using the given service options and stored
information.

@param  ServiceOptions $serviceOptions The service options used to
generate request options.
@param  callable       $handler        The handler used to send the
request.
@return array

Generate the request options using the given service options and stored information .


protected function sendContextAsync(HttpCallContext $context)
    {
        return $this->sendAsync(
            $context->getMethod(),
            $context->getHeaders(),
            $context->getQueryParameters(),
            $context->getPostParameters(),
            $context->getPath(),
            $context->getStatusCodes(),
            $context->getBody(),
            $context->getServiceOptions()
        );
    }

protected function sendContextAsync ( HttpCallContext $ context ) { return $ this -> sendAsync ( $ context -> getMethod ( ) , $ context -> getHeaders ( ) , $ context -> getQueryParameters ( ) , $ context -> getPostParameters ( ) , $ context -> getPath ( ) , $ context -> getStatusCodes ( ) , $ context -> getBody ( ) , $ context -> getServiceOptions ( ) ) ; }

Creates the promise to send the context.

@param  HttpCallContext $context The context of the request.

@return \GuzzleHttp\Promise\PromiseInterface

Creates the promise to send the context .


public static function throwIfError(ResponseInterface $response, $expected)
    {
        $expectedStatusCodes = is_array($expected) ? $expected : array($expected);

        if (!in_array($response->getStatusCode(), $expectedStatusCodes)) {
            throw new ServiceException($response);
        }
    }

public static function throwIfError ( ResponseInterface $ response , $ expected ) { $ expectedStatusCodes = is_array ( $ expected ) ? $ expected : array ( $ expected ) ; if ( ! in_array ( $ response -> getStatusCode ( ) , $ expectedStatusCodes ) ) { throw new ServiceException ( $ response ) ; } }

Throws ServiceException if the received status code is not expected.

@param ResponseInterface $response The response received
@param array|int         $expected The expected status codes.

@return void

@throws ServiceException

Throws ServiceException if the received status code is not expected .


public function addPostParameter(
        array $postParameters,
        $key,
        $value
    ) {
        Validate::isArray($postParameters, 'postParameters');
        $postParameters[$key] = $value;
        return $postParameters;
    }

public function addPostParameter ( array $ postParameters , $ key , $ value ) { Validate :: isArray ( $ postParameters , 'postParameters' ) ; $ postParameters [ $ key ] = $ value ; return $ postParameters ; }

Adds HTTP POST parameter to the specified

@param array  $postParameters An array of HTTP POST parameters.
@param string $key            The key of a HTTP POST parameter.
@param string $value          the value of a HTTP POST parameter.

@return array


protected function addMetadataHeaders(array $headers, array $metadata = null)
    {
        Utilities::validateMetadata($metadata);

        $metadata = $this->generateMetadataHeaders($metadata);
        $headers  = array_merge($headers, $metadata);

        return $headers;
    }

protected function addMetadataHeaders ( array $ headers , array $ metadata = null ) { Utilities :: validateMetadata ( $ metadata ) ; $ metadata = $ this -> generateMetadataHeaders ( $ metadata ) ; $ headers = array_merge ( $ headers , $ metadata ) ; return $ headers ; }

Adds metadata elements to headers array

@param array $headers  HTTP request headers
@param array $metadata user specified metadata

@return array


private static function addLocationHeaderToResponse(
        ResponseInterface $response,
        $locationMode
    ) {
        //If the response already has this header, return itself.
        if ($response->hasHeader(Resources::X_MS_CONTINUATION_LOCATION_MODE)) {
            return $response;
        }
        //Otherwise, add the header that indicates the endpoint to be used if
        //continuation token is used for subsequent request. Notice that if the
        //response does not have location header set at the moment, it means
        //that the user have not set a retry middleware.
        if ($locationMode == LocationMode::PRIMARY_THEN_SECONDARY) {
            $response = $response->withHeader(
                Resources::X_MS_CONTINUATION_LOCATION_MODE,
                LocationMode::PRIMARY_ONLY
            );
        } elseif ($locationMode == LocationMode::SECONDARY_THEN_PRIMARY) {
            $response = $response->withHeader(
                Resources::X_MS_CONTINUATION_LOCATION_MODE,
                LocationMode::SECONDARY_ONLY
            );
        } elseif ($locationMode == LocationMode::SECONDARY_ONLY  ||
                  $locationMode == LocationMode::PRIMARY_ONLY) {
            $response = $response->withHeader(
                Resources::X_MS_CONTINUATION_LOCATION_MODE,
                $locationMode
            );
        }
        return $response;
    }

Adds the header that indicates the location mode to the response header.

@return  ResponseInterface

Adds the header that indicates the location mode to the response header .


private function _validateProperties($properties)
    {
        Validate::isArray($properties, 'entity properties');

        foreach ($properties as $key => $value) {
            Validate::canCastAsString($key, 'key');
            Validate::isTrue(
                $value instanceof Property,
                Resources::INVALID_PROP_MSG
            );
            Validate::isTrue(
                EdmType::validateEdmValue(
                    $value->getEdmType(),
                    $value->getValue(),
                    $condition
                ),
                sprintf(Resources::INVALID_PROP_VAL_MSG, $key, $condition)
            );
        }
    }

private
function
_validateProperties
(
$
properties
)
{
Validate
::
isArray
(
$
properties
,
'entity properties'
)
;
foreach
(
$
properties
as
$
key
=>
$
value
)
{
Validate
::
canCastAsString
(
$
key
,
'key'
)
;
Validate
::
isTrue
(
$
value
instanceof
Property
,
Resources
::
INVALID_PROP_MSG
)
;
Validate
::
isTrue
(
EdmType
::
validateEdmValue
(
$
value
->
getEdmType
(
)
,
$
value
->
getValue
(
)
,
$
condition
)
,
sprintf
(
Resources
::
INVALID_PROP_VAL_MSG
,
$
key
,
$
condition
)
)
;
}
}

Validates if properties is valid or not.

@param mixed $properties The properties array.

@return void

Validates if properties is valid or not .


public function getPropertyValue($name)
    {
        $p = Utilities::tryGetValue($this->_properties, $name);
        return is_null($p) ? null : $p->getValue();
    }

public function getPropertyValue ( $ name ) { $ p = Utilities :: tryGetValue ( $ this -> _properties , $ name ) ; return is_null ( $ p ) ? null : $ p -> getValue ( ) ; }

Gets property value and if the property name is not found return null.

@param string $name The property name.

@return mixed

Gets property value and if the property name is not found return null .


public function setPropertyValue($name, $value)
    {
        $p = Utilities::tryGetValue($this->_properties, $name);
        if (!is_null($p)) {
            $p->setValue($value);
        }
    }

public function setPropertyValue ( $ name , $ value ) { $ p = Utilities :: tryGetValue ( $ this -> _properties , $ name ) ; if ( ! is_null ( $ p ) ) { $ p -> setValue ( $ value ) ; } }

Sets property value.

Note that if the property doesn't exist, it doesn't add it. Use addProperty
to add new properties.

@param string $name  The property name.
@param mixed  $value The property value.

@return mixed


public function setProperty($name, $property)
    {
        Validate::isTrue($property instanceof Property, Resources::INVALID_PROP_MSG);
        $this->_properties[$name] = $property;
    }

public function setProperty ( $ name , $ property ) { Validate :: isTrue ( $ property instanceof Property , Resources :: INVALID_PROP_MSG ) ; $ this -> _properties [ $ name ] = $ property ; }

Sets entity property.

@param string   $name     The property name.
@param Property $property The property object.

@return void


public function addProperty($name, $edmType, $value, $rawValue = '')
    {
        $p = new Property();
        $p->setEdmType($edmType);
        $p->setValue($value);
        $p->setRawValue($rawValue);
        $this->setProperty($name, $p);
    }

public function addProperty ( $ name , $ edmType , $ value , $ rawValue = '' ) { $ p = new Property ( ) ; $ p -> setEdmType ( $ edmType ) ; $ p -> setValue ( $ value ) ; $ p -> setRawValue ( $ rawValue ) ; $ this -> setProperty ( $ name , $ p ) ; }

Creates new entity property.

@param string $name     The property name.
@param string $edmType  The property edm type.
@param mixed  $value    The property value.
@param string $rawValue The raw value of the property.


public function isValid(&$msg = null)
    {
        try {
            $this->_validateProperties($this->_properties);
        } catch (\Exception $exc) {
            $msg = $exc->getMessage();
            return false;
        }

        if (is_null($this->getPartitionKey())
            || is_null($this->getRowKey())
        ) {
            $msg = Resources::NULL_TABLE_KEY_MSG;
            return false;
        } else {
            return true;
        }
    }

public function isValid ( & $ msg = null ) { try { $ this -> _validateProperties ( $ this -> _properties ) ; } catch ( \ Exception $ exc ) { $ msg = $ exc -> getMessage ( ) ; return false ; } if ( is_null ( $ this -> getPartitionKey ( ) ) || is_null ( $ this -> getRowKey ( ) ) ) { $ msg = Resources :: NULL_TABLE_KEY_MSG ; return false ; } else { return true ; } }

Checks if the entity object is valid or not.
Valid means the partition and row key exists for this entity along with the
timestamp.

@param string &$msg The error message.

@internal

@return boolean

Checks if the entity object is valid or not . Valid means the partition and row key exists for this entity along with the timestamp .


public static function create($body, $odataSerializer)
    {
        $result = new GetTableResult();
        $name = $odataSerializer->parseTable($body);
        $result->setName($name);

        return $result;
    }

public static function create ( $ body , $ odataSerializer ) { $ result = new GetTableResult ( ) ; $ name = $ odataSerializer -> parseTable ( $ body ) ; $ result -> setName ( $ name ) ; return $ result ; }

Creates GetTableResult from HTTP response body.

@param string             $body            The HTTP response body.
@param IODataReaderWriter $odataSerializer The OData reader and writer.

@internal

@return GetTableResult

Creates GetTableResult from HTTP response body .


protected function computeSignature(
        array $headers,
        $url,
        array $queryParams,
        $httpMethod
    ) {
        $canonicalizedHeaders = $this->computeCanonicalizedHeaders($headers);

        $canonicalizedResource = $this->computeCanonicalizedResource(
            $url,
            $queryParams
        );

        $stringToSign   = array();
        $stringToSign[] = strtoupper($httpMethod);

        foreach ($this->includedHeaders as $header) {
            $stringToSign[] = Utilities::tryGetValue($headers, $header);
        }

        if (count($canonicalizedHeaders) > 0) {
            $stringToSign[] = implode("\n", $canonicalizedHeaders);
        }

        $stringToSign[] = $canonicalizedResource;
        $stringToSign   = implode("\n", $stringToSign);

        return $stringToSign;
    }

protected function computeSignature ( array $ headers , $ url , array $ queryParams , $ httpMethod ) { $ canonicalizedHeaders = $ this -> computeCanonicalizedHeaders ( $ headers ) ; $ canonicalizedResource = $ this -> computeCanonicalizedResource ( $ url , $ queryParams ) ; $ stringToSign = array ( ) ; $ stringToSign [ ] = strtoupper ( $ httpMethod ) ; foreach ( $ this -> includedHeaders as $ header ) { $ stringToSign [ ] = Utilities :: tryGetValue ( $ headers , $ header ) ; } if ( count ( $ canonicalizedHeaders ) > 0 ) { $ stringToSign [ ] = implode ( "\n" , $ canonicalizedHeaders ) ; } $ stringToSign [ ] = $ canonicalizedResource ; $ stringToSign = implode ( "\n" , $ stringToSign ) ; return $ stringToSign ; }

Computes the authorization signature for blob and queue shared key.

@param array  $headers     request headers.
@param string $url         reuqest url.
@param array  $queryParams query variables.
@param string $httpMethod  request http method.

@see Blob and Queue Services (Shared Key Authentication) at
http://msdn.microsoft.com/en-us/library/windowsazure/dd179428.aspx

@return string

Computes the authorization signature for blob and queue shared key .


public function getAuthorizationHeader(
        array $headers,
        $url,
        array $queryParams,
        $httpMethod
    ) {
        $signature = $this->computeSignature(
            $headers,
            $url,
            $queryParams,
            $httpMethod
        );

        return 'SharedKey ' . $this->accountName . ':' . base64_encode(
            hash_hmac('sha256', $signature, base64_decode($this->accountKey), true)
        );
    }

public
function
getAuthorizationHeader
(
array
$
headers
,
$
url
,
array
$
queryParams
,
$
httpMethod
)
{
$
signature
=
$
this
->
computeSignature
(
$
headers
,
$
url
,
$
queryParams
,
$
httpMethod
)
;
return
'SharedKey '
.
$
this
->
accountName
.
':'
.
base64_encode
(
hash_hmac
(
'sha256'
,
$
signature
,
base64_decode
(
$
this
->
accountKey
)
,
true
)
)
;
}

Returns authorization header to be included in the request.

@param array  $headers     request headers.
@param string $url         reuqest url.
@param array  $queryParams query variables.
@param string $httpMethod  request http method.

@see Specifying the Authorization Header section at
http://msdn.microsoft.com/en-us/library/windowsazure/dd179428.aspx

@return string

Returns authorization header to be included in the request .


protected function computeCanonicalizedHeaders($headers)
    {
        $canonicalizedHeaders = array();
        $normalizedHeaders    = array();
        $validPrefix          =  Resources::X_MS_HEADER_PREFIX;

        if (is_null($normalizedHeaders)) {
            return $canonicalizedHeaders;
        }

        foreach ($headers as $header => $value) {
            // Convert header to lower case.
            $header = strtolower($header);

            // Retrieve all headers for the resource that begin with x-ms-,
            // including the x-ms-date header.
            if (Utilities::startsWith($header, $validPrefix)) {
                // Unfold the string by replacing any breaking white space
                // (meaning what splits the headers, which is \r\n) with a single
                // space.
                $value = str_replace("\r\n", ' ', $value);

                // Trim any white space around the colon in the header.
                $value  = ltrim($value);
                $header = rtrim($header);

                $normalizedHeaders[$header] = $value;
            }
        }

        // Sort the headers lexicographically by header name, in ascending order.
        // Note that each header may appear only once in the string.
        ksort($normalizedHeaders);

        foreach ($normalizedHeaders as $key => $value) {
            $canonicalizedHeaders[] = $key . ':' . $value;
        }

        return $canonicalizedHeaders;
    }

Computes canonicalized headers for headers array.

@param array $headers request headers.

@see Constructing the Canonicalized Headers String section at
http://msdn.microsoft.com/en-us/library/windowsazure/dd179428.aspx

@return array

Computes canonicalized headers for headers array .


protected function computeCanonicalizedResourceForTable($url, $queryParams)
    {
        $queryParams = array_change_key_case($queryParams);

        // 1. Beginning with an empty string (""), append a forward slash (/),
        //    followed by the name of the account that owns the accessed resource.
        $canonicalizedResource = '/' . $this->accountName;

        // 2. Append the resource's encoded URI path, without any query parameters.
        $canonicalizedResource .= parse_url($url, PHP_URL_PATH);

        // 3. The query string should include the question mark and the comp
        //    parameter (for example, ?comp=metadata). No other parameters should
        //    be included on the query string.
        if (array_key_exists(Resources::QP_COMP, $queryParams)) {
            $canonicalizedResource .= '?' . Resources::QP_COMP . '=';
            $canonicalizedResource .= $queryParams[Resources::QP_COMP];
        }

        return $canonicalizedResource;
    }

Computes canonicalized resources from URL using Table formar

@param string $url         request url.
@param array  $queryParams request query variables.

@see Constructing the Canonicalized Resource String section at
http://msdn.microsoft.com/en-us/library/windowsazure/dd179428.aspx

@return string


protected function computeCanonicalizedResource($url, $queryParams)
    {
        $queryParams = array_change_key_case($queryParams);

        // 1. Beginning with an empty string (""), append a forward slash (/),
        //    followed by the name of the account that owns the accessed resource.
        $canonicalizedResource = '/' . $this->accountName;

        // 2. Append the resource's encoded URI path, without any query parameters.
        $canonicalizedResource .= parse_url($url, PHP_URL_PATH);

        // 3. Retrieve all query parameters on the resource URI, including the comp
        //    parameter if it exists.
        // 4. Sort the query parameters lexicographically by parameter name, in
        //    ascending order.
        if (count($queryParams) > 0) {
            ksort($queryParams);
        }

        // 5. Convert all parameter names to lowercase.
        // 6. URL-decode each query parameter name and value.
        // 7. Append each query parameter name and value to the string in the
        //    following format:
        //      parameter-name:parameter-value
        // 9. Group query parameters
        // 10. Append a new line character (\n) after each name-value pair.
        foreach ($queryParams as $key => $value) {
            // $value must already be ordered lexicographically
            // See: ServiceRestProxy::groupQueryValues
            $canonicalizedResource .= "\n" . $key . ':' . $value;
        }

        return $canonicalizedResource;
    }

Computes canonicalized resources from URL.

@param string $url         request url.
@param array  $queryParams request query variables.

@see Constructing the Canonicalized Resource String section at
http://msdn.microsoft.com/en-us/library/windowsazure/dd179428.aspx

@return string

Computes canonicalized resources from URL .


public function toXml(XmlSerializer $serializer)
    {
        $properties = array(
            XmlSerializer::DEFAULT_TAG => Resources::XTAG_SIGNED_IDENTIFIER,
            XmlSerializer::ROOT_NAME   => Resources::XTAG_SIGNED_IDENTIFIERS
        );

        return $serializer->serialize($this->toArray(), $properties);
    }

public function toXml ( XmlSerializer $ serializer ) { $ properties = array ( XmlSerializer :: DEFAULT_TAG => Resources :: XTAG_SIGNED_IDENTIFIER , XmlSerializer :: ROOT_NAME => Resources :: XTAG_SIGNED_IDENTIFIERS ) ; return $ serializer -> serialize ( $ this -> toArray ( ) , $ properties ) ; }

Converts this signed identifiers to XML representation.

@param  XmlSerializer $xmlSerializer The XML serializer.

@internal

@return string

Converts this signed identifiers to XML representation .


public function fromXmlArray(array $parsed = null)
    {
        $this->setSignedIdentifiers(array());

        // Initialize signed identifiers.
        if (!empty($parsed) &&
                is_array($parsed[Resources::XTAG_SIGNED_IDENTIFIER])
        ) {
            $entries = $parsed[Resources::XTAG_SIGNED_IDENTIFIER];
            $temp    = Utilities::getArray($entries);

            foreach ($temp as $value) {
                $accessPolicy = $value[Resources::XTAG_ACCESS_POLICY];
                $startString  = urldecode(
                    $accessPolicy[Resources::XTAG_SIGNED_START]
                );
                $expiryString = urldecode(
                    $accessPolicy[Resources::XTAG_SIGNED_EXPIRY]
                );
                $start        = Utilities::convertToDateTime($startString);
                $expiry       = Utilities::convertToDateTime($expiryString);
                $permission   = $accessPolicy[Resources::XTAG_SIGNED_PERMISSION];
                $id           = $value[Resources::XTAG_SIGNED_ID];
                $this->addSignedIdentifier($id, $start, $expiry, $permission);
            }
        }
    }

public
function
fromXmlArray
(
array
$
parsed
=
)
{
$
this
->
setSignedIdentifiers
(
array
(
)
)
;
// Initialize signed identifiers.
if
(
!
empty
(
$
parsed
)
&&
is_array
(
$
parsed
[
Resources
::
XTAG_SIGNED_IDENTIFIER
]
)
)
{
$
entries
=
$
parsed
[
Resources
::
XTAG_SIGNED_IDENTIFIER
]
;
$
temp
=
Utilities
::
getArray
(
$
entries
)
;
foreach
(
$
temp
as
$
value
)
{
$
accessPolicy
=
$
value
[
Resources
::
XTAG_ACCESS_POLICY
]
;
$
startString
=
urldecode
(
$
accessPolicy
[
Resources
::
XTAG_SIGNED_START
]
)
;
$
expiryString
=
urldecode
(
$
accessPolicy
[
Resources
::
XTAG_SIGNED_EXPIRY
]
)
;
$
start
=
Utilities
::
convertToDateTime
(
$
startString
)
;
$
expiry
=
Utilities
::
convertToDateTime
(
$
expiryString
)
;
$
permission
=
$
accessPolicy
[
Resources
::
XTAG_SIGNED_PERMISSION
]
;
$
id
=
$
value
[
Resources
::
XTAG_SIGNED_ID
]
;
$
this
->
addSignedIdentifier
(
$
id
,
$
start
,
$
expiry
,
$
permission
)
;
}
}
}

Construct the signed identifiers from a given parsed XML in array
representation.

@param array|null  $parsed The parsed XML into array representation.

@internal

@return void

Construct the signed identifiers from a given parsed XML in array representation .


public function addSignedIdentifier(
        $id,
        \DateTime $start,
        \DateTime $expiry,
        $permissions
    ) {
        Validate::canCastAsString($id, 'id');
        if ($start != null) {
            Validate::isDate($start);
        }
        Validate::isDate($expiry);
        Validate::canCastAsString($permissions, 'permissions');

        $accessPolicy = static::createAccessPolicy();
        $accessPolicy->setStart($start);
        $accessPolicy->setExpiry($expiry);
        $accessPolicy->setPermission($permissions);

        $signedIdentifier = new SignedIdentifier();
        $signedIdentifier->setId($id);
        $signedIdentifier->setAccessPolicy($accessPolicy);

        // Remove the signed identifier with the same ID.
        $this->removeSignedIdentifier($id);

        // There can be no more than 5 signed identifiers at the same time.
        Validate::isTrue(
            count($this->getSignedIdentifiers()) < 5,
            Resources::ERROR_TOO_MANY_SIGNED_IDENTIFIERS
        );

        $this->signedIdentifiers[] = $signedIdentifier;
    }

Add a signed identifier to the ACL.

@param string    $id          A unique id for this signed identifier.
@param \DateTime $start       The time at which the Shared Access
Signature becomes valid. If omitted, start
time for this call is assumed to be the
time when the service receives the
request.
@param \DateTime $expiry      The time at which the Shared Access
Signature becomes invalid.
@param string    $permissions The permissions associated with the Shared
Access Signature. The user is restricted to
operations allowed by the permissions.

@return void

@see https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/establishing-a-stored-access-policy


public function removeSignedIdentifier($id)
    {
        Validate::canCastAsString($id, 'id');
        //var_dump($this->signedIdentifiers);
        for ($i = 0; $i < count($this->signedIdentifiers); ++$i) {
            if ($this->signedIdentifiers[$i]->getId() == $id) {
                array_splice($this->signedIdentifiers, $i, 1);
                return true;
            }
        }

        return false;
    }

public function removeSignedIdentifier ( $ id ) { Validate :: canCastAsString ( $ id , 'id' ) ; //var_dump($this->signedIdentifiers); for ( $ i = 0 ; $ i < count ( $ this -> signedIdentifiers ) ; ++ $ i ) { if ( $ this -> signedIdentifiers [ $ i ] -> getId ( ) == $ id ) { array_splice ( $ this -> signedIdentifiers , $ i , 1 ) ; return true ; } } return false ; }

Remove the signed identifier with given ID.

@param  string $id The ID of the signed identifier to be removed.

@return boolean

Remove the signed identifier with given ID .


public function setOperations(array $operations)
    {
        $this->_operations = array();
        foreach ($operations as $operation) {
            $this->addOperation($operation);
        }
    }

public function setOperations ( array $ operations ) { $ this -> _operations = array ( ) ; foreach ( $ operations as $ operation ) { $ this -> addOperation ( $ operation ) ; } }

Sets the batch operations.

@param array $operations The batch operations.

@return void


public function addOperation($operation)
    {
        Validate::isTrue(
            $operation instanceof BatchOperation,
            Resources::INVALID_BO_TYPE_MSG
        );

        $this->_operations[] = $operation;
    }

public function addOperation ( $ operation ) { Validate :: isTrue ( $ operation instanceof BatchOperation , Resources :: INVALID_BO_TYPE_MSG ) ; $ this -> _operations [ ] = $ operation ; }

Adds operation to the batch operations.

@param mixed $operation The operation to add.

@return void

Adds operation to the batch operations .


public function addInsertEntity($table, Entity $entity)
    {
        Validate::canCastAsString($table, 'table');
        Validate::notNullOrEmpty($entity, 'entity');

        $operation = new BatchOperation();
        $type      = BatchOperationType::INSERT_ENTITY_OPERATION;
        $operation->setType($type);
        $operation->addParameter(BatchOperationParameterName::BP_TABLE, $table);
        $operation->addParameter(BatchOperationParameterName::BP_ENTITY, $entity);
        $this->addOperation($operation);
    }

public function addInsertEntity ( $ table , Entity $ entity ) { Validate :: canCastAsString ( $ table , 'table' ) ; Validate :: notNullOrEmpty ( $ entity , 'entity' ) ; $ operation = new BatchOperation ( ) ; $ type = BatchOperationType :: INSERT_ENTITY_OPERATION ; $ operation -> setType ( $ type ) ; $ operation -> addParameter ( BatchOperationParameterName :: BP_TABLE , $ table ) ; $ operation -> addParameter ( BatchOperationParameterName :: BP_ENTITY , $ entity ) ; $ this -> addOperation ( $ operation ) ; }

Adds insertEntity operation.

@param string $table  The table name.
@param Entity $entity The entity instance.

@return void


public function addDeleteEntity($table, $partitionKey, $rowKey, $etag = null)
    {
        Validate::canCastAsString($table, 'table');
        Validate::isTrue(!is_null($partitionKey), Resources::NULL_TABLE_KEY_MSG);
        Validate::isTrue(!is_null($rowKey), Resources::NULL_TABLE_KEY_MSG);

        $operation = new BatchOperation();
        $type      = BatchOperationType::DELETE_ENTITY_OPERATION;
        $operation->setType($type);
        $operation->addParameter(BatchOperationParameterName::BP_TABLE, $table);
        $operation->addParameter(BatchOperationParameterName::BP_ROW_KEY, $rowKey);
        $operation->addParameter(BatchOperationParameterName::BP_ETAG, $etag);
        $operation->addParameter(
            BatchOperationParameterName::BP_PARTITION_KEY,
            $partitionKey
        );
        $this->addOperation($operation);
    }

public function addDeleteEntity ( $ table , $ partitionKey , $ rowKey , $ etag = null ) { Validate :: canCastAsString ( $ table , 'table' ) ; Validate :: isTrue ( ! is_null ( $ partitionKey ) , Resources :: NULL_TABLE_KEY_MSG ) ; Validate :: isTrue ( ! is_null ( $ rowKey ) , Resources :: NULL_TABLE_KEY_MSG ) ; $ operation = new BatchOperation ( ) ; $ type = BatchOperationType :: DELETE_ENTITY_OPERATION ; $ operation -> setType ( $ type ) ; $ operation -> addParameter ( BatchOperationParameterName :: BP_TABLE , $ table ) ; $ operation -> addParameter ( BatchOperationParameterName :: BP_ROW_KEY , $ rowKey ) ; $ operation -> addParameter ( BatchOperationParameterName :: BP_ETAG , $ etag ) ; $ operation -> addParameter ( BatchOperationParameterName :: BP_PARTITION_KEY , $ partitionKey ) ; $ this -> addOperation ( $ operation ) ; }

Adds deleteEntity operation.

@param string $table        The table name.
@param string $partitionKey The entity partition key.
@param string $rowKey       The entity row key.
@param string $etag         The entity etag.

@return void


public static function create(array $headers)
    {
        $result  = new CopyFileResult();
        $headers = array_change_key_case($headers);

        $date          = $headers[Resources::LAST_MODIFIED];
        $date          = Utilities::rfc1123ToDateTime($date);

        $result->setCopyStatus($headers[Resources::X_MS_COPY_STATUS]);
        $result->setCopyID($headers[Resources::X_MS_COPY_ID]);
        $result->setETag($headers[Resources::ETAG]);
        $result->setLastModified($date);

        return $result;
    }

public static function create ( array $ headers ) { $ result = new CopyFileResult ( ) ; $ headers = array_change_key_case ( $ headers ) ; $ date = $ headers [ Resources :: LAST_MODIFIED ] ; $ date = Utilities :: rfc1123ToDateTime ( $ date ) ; $ result -> setCopyStatus ( $ headers [ Resources :: X_MS_COPY_STATUS ] ) ; $ result -> setCopyID ( $ headers [ Resources :: X_MS_COPY_ID ] ) ; $ result -> setETag ( $ headers [ Resources :: ETAG ] ) ; $ result -> setLastModified ( $ date ) ; return $ result ; }

Creates CopyFileResult object from parsed response header.

@param array $headers HTTP response headers

@internal

@return CopyFileResult

Creates CopyFileResult object from parsed response header .


public static function createFromListMessages(array $parsedResponse)
    {
        $timeNextVisible = $parsedResponse['TimeNextVisible'];

        $msg  = self::createFromPeekMessages($parsedResponse);
        $date = Utilities::rfc1123ToDateTime($timeNextVisible);
        $msg->setTimeNextVisible($date);
        $msg->setPopReceipt($parsedResponse['PopReceipt']);

        return $msg;
    }

public static function createFromListMessages ( array $ parsedResponse ) { $ timeNextVisible = $ parsedResponse [ 'TimeNextVisible' ] ; $ msg = self :: createFromPeekMessages ( $ parsedResponse ) ; $ date = Utilities :: rfc1123ToDateTime ( $ timeNextVisible ) ; $ msg -> setTimeNextVisible ( $ date ) ; $ msg -> setPopReceipt ( $ parsedResponse [ 'PopReceipt' ] ) ; return $ msg ; }

Creates QueueMessage object from parsed XML response of
ListMessages.

@param array $parsedResponse XML response parsed into array.

@internal

@return QueueMessage

Creates QueueMessage object from parsed XML response of ListMessages .


public static function createFromPeekMessages(array $parsedResponse)
    {
        $msg            = new QueueMessage();
        $expirationDate = $parsedResponse['ExpirationTime'];
        $insertionDate  = $parsedResponse['InsertionTime'];

        $msg->setDequeueCount(intval($parsedResponse['DequeueCount']));

        $date = Utilities::rfc1123ToDateTime($expirationDate);
        $msg->setExpirationDate($date);

        $date = Utilities::rfc1123ToDateTime($insertionDate);
        $msg->setInsertionDate($date);

        $msg->setMessageId($parsedResponse['MessageId']);
        $msg->setMessageText($parsedResponse['MessageText']);

        return $msg;
    }

public static function createFromPeekMessages ( array $ parsedResponse ) { $ msg = new QueueMessage ( ) ; $ expirationDate = $ parsedResponse [ 'ExpirationTime' ] ; $ insertionDate = $ parsedResponse [ 'InsertionTime' ] ; $ msg -> setDequeueCount ( intval ( $ parsedResponse [ 'DequeueCount' ] ) ) ; $ date = Utilities :: rfc1123ToDateTime ( $ expirationDate ) ; $ msg -> setExpirationDate ( $ date ) ; $ date = Utilities :: rfc1123ToDateTime ( $ insertionDate ) ; $ msg -> setInsertionDate ( $ date ) ; $ msg -> setMessageId ( $ parsedResponse [ 'MessageId' ] ) ; $ msg -> setMessageText ( $ parsedResponse [ 'MessageText' ] ) ; return $ msg ; }

Creates QueueMessage object from parsed XML response of
PeekMessages.

@param array $parsedResponse XML response parsed into array.

@internal

@return QueueMessage

Creates QueueMessage object from parsed XML response of PeekMessages .


public static function createFromCreateMessage(array $parsedResponse)
    {
        $msg = new QueueMessage();

        $expirationDate  = $parsedResponse['ExpirationTime'];
        $insertionDate   = $parsedResponse['InsertionTime'];
        $timeNextVisible = $parsedResponse['TimeNextVisible'];

        $date = Utilities::rfc1123ToDateTime($expirationDate);
        $msg->setExpirationDate($date);

        $date = Utilities::rfc1123ToDateTime($insertionDate);
        $msg->setInsertionDate($date);

        $date = Utilities::rfc1123ToDateTime($timeNextVisible);
        $msg->setTimeNextVisible($date);

        $msg->setMessageId($parsedResponse['MessageId']);
        $msg->setPopReceipt($parsedResponse['PopReceipt']);

        return $msg;
    }

public static function createFromCreateMessage ( array $ parsedResponse ) { $ msg = new QueueMessage ( ) ; $ expirationDate = $ parsedResponse [ 'ExpirationTime' ] ; $ insertionDate = $ parsedResponse [ 'InsertionTime' ] ; $ timeNextVisible = $ parsedResponse [ 'TimeNextVisible' ] ; $ date = Utilities :: rfc1123ToDateTime ( $ expirationDate ) ; $ msg -> setExpirationDate ( $ date ) ; $ date = Utilities :: rfc1123ToDateTime ( $ insertionDate ) ; $ msg -> setInsertionDate ( $ date ) ; $ date = Utilities :: rfc1123ToDateTime ( $ timeNextVisible ) ; $ msg -> setTimeNextVisible ( $ date ) ; $ msg -> setMessageId ( $ parsedResponse [ 'MessageId' ] ) ; $ msg -> setPopReceipt ( $ parsedResponse [ 'PopReceipt' ] ) ; return $ msg ; }

Creates QueueMessage object from parsed XML response of
createMessage.

@param array $parsedResponse XML response parsed into array.

@internal

@return QueueMessage

Creates QueueMessage object from parsed XML response of createMessage .


protected static function init()
    {
        self::$useDevelopmentStorageSetting = self::setting(
            Resources::USE_DEVELOPMENT_STORAGE_NAME,
            'true'
        );

        self::$developmentStorageProxyUriSetting = self::settingWithFunc(
            Resources::DEVELOPMENT_STORAGE_PROXY_URI_NAME,
            Validate::getIsValidUri()
        );

        self::$defaultEndpointsProtocolSetting = self::setting(
            Resources::DEFAULT_ENDPOINTS_PROTOCOL_NAME,
            'http',
            'https'
        );

        self::$accountNameSetting = self::setting(Resources::ACCOUNT_NAME_NAME);

        self::$accountKeySetting = self::settingWithFunc(
            Resources::ACCOUNT_KEY_NAME,
            // base64_decode will return false if the $key is not in base64 format.
            function ($key) {
                $isValidBase64String = base64_decode($key, true);
                if ($isValidBase64String) {
                    return true;
                } else {
                    throw new \RuntimeException(
                        sprintf(Resources::INVALID_ACCOUNT_KEY_FORMAT, $key)
                    );
                }
            }
        );

        self::$sasTokenSetting = self::setting(Resources::SAS_TOKEN_NAME);

        self::$blobEndpointSetting = self::settingWithFunc(
            Resources::BLOB_ENDPOINT_NAME,
            Validate::getIsValidUri()
        );

        self::$queueEndpointSetting = self::settingWithFunc(
            Resources::QUEUE_ENDPOINT_NAME,
            Validate::getIsValidUri()
        );

        self::$tableEndpointSetting = self::settingWithFunc(
            Resources::TABLE_ENDPOINT_NAME,
            Validate::getIsValidUri()
        );

        self::$fileEndpointSetting = self::settingWithFunc(
            Resources::FILE_ENDPOINT_NAME,
            Validate::getIsValidUri()
        );

        self::$endpointSuffixSetting = self::settingWithFunc(
            Resources::ENDPOINT_SUFFIX_NAME,
            Validate::getIsValidHostname()
        );

        self::$validSettingKeys[] = Resources::USE_DEVELOPMENT_STORAGE_NAME;
        self::$validSettingKeys[] = Resources::DEVELOPMENT_STORAGE_PROXY_URI_NAME;
        self::$validSettingKeys[] = Resources::DEFAULT_ENDPOINTS_PROTOCOL_NAME;
        self::$validSettingKeys[] = Resources::ACCOUNT_NAME_NAME;
        self::$validSettingKeys[] = Resources::ACCOUNT_KEY_NAME;
        self::$validSettingKeys[] = Resources::SAS_TOKEN_NAME;
        self::$validSettingKeys[] = Resources::BLOB_ENDPOINT_NAME;
        self::$validSettingKeys[] = Resources::QUEUE_ENDPOINT_NAME;
        self::$validSettingKeys[] = Resources::TABLE_ENDPOINT_NAME;
        self::$validSettingKeys[] = Resources::FILE_ENDPOINT_NAME;
        self::$validSettingKeys[] = Resources::ENDPOINT_SUFFIX_NAME;
    }

Initializes static members of the class.

@return void

Initializes static members of the class .


private static function getDevelopmentStorageAccount($proxyUri)
    {
        if (is_null($proxyUri)) {
            return self::developmentStorageAccount();
        }

        $scheme = parse_url($proxyUri, PHP_URL_SCHEME);
        $host   = parse_url($proxyUri, PHP_URL_HOST);
        $prefix = $scheme . "://" . $host;

        return new StorageServiceSettings(
            Resources::DEV_STORE_NAME,
            Resources::DEV_STORE_KEY,
            $prefix . ':10000/devstoreaccount1/',
            $prefix . ':10001/devstoreaccount1/',
            $prefix . ':10002/devstoreaccount1/',
            null
        );
    }

private static function getDevelopmentStorageAccount ( $ proxyUri ) { if ( is_null ( $ proxyUri ) ) { return self :: developmentStorageAccount ( ) ; } $ scheme = parse_url ( $ proxyUri , PHP_URL_SCHEME ) ; $ host = parse_url ( $ proxyUri , PHP_URL_HOST ) ; $ prefix = $ scheme . "://" . $ host ; return new StorageServiceSettings ( Resources :: DEV_STORE_NAME , Resources :: DEV_STORE_KEY , $ prefix . ':10000/devstoreaccount1/' , $ prefix . ':10001/devstoreaccount1/' , $ prefix . ':10002/devstoreaccount1/' , null ) ; }

Returns a StorageServiceSettings with development storage credentials using
the specified proxy Uri.

@param string $proxyUri The proxy endpoint to use.

@return StorageServiceSettings

Returns a StorageServiceSettings with development storage credentials using the specified proxy Uri .


public static function developmentStorageAccount()
    {
        if (is_null(self::$devStoreAccount)) {
            self::$devStoreAccount = self::getDevelopmentStorageAccount(
                Resources::DEV_STORE_URI
            );
        }

        return self::$devStoreAccount;
    }

public static function developmentStorageAccount ( ) { if ( is_null ( self :: $ devStoreAccount ) ) { self :: $ devStoreAccount = self :: getDevelopmentStorageAccount ( Resources :: DEV_STORE_URI ) ; } return self :: $ devStoreAccount ; }

Gets a StorageServiceSettings object that references the development storage
account.

@return StorageServiceSettings

Gets a StorageServiceSettings object that references the development storage account .


private static function getServiceEndpoint(
        $scheme,
        $accountName,
        $dnsPrefix,
        $dnsSuffix = null,
        $isSecondary = false
    ) {
        if ($isSecondary) {
            $accountName .= Resources::SECONDARY_STRING;
        }
        if ($dnsSuffix === null) {
            $dnsSuffix = Resources::DEFAULT_ENDPOINT_SUFFIX;
        }
        return sprintf(
            Resources::SERVICE_URI_FORMAT,
            $scheme,
            $accountName,
            $dnsPrefix.$dnsSuffix
        );
    }

private static function getServiceEndpoint ( $ scheme , $ accountName , $ dnsPrefix , $ dnsSuffix = null , $ isSecondary = false ) { if ( $ isSecondary ) { $ accountName .= Resources :: SECONDARY_STRING ; } if ( $ dnsSuffix === null ) { $ dnsSuffix = Resources :: DEFAULT_ENDPOINT_SUFFIX ; } return sprintf ( Resources :: SERVICE_URI_FORMAT , $ scheme , $ accountName , $ dnsPrefix . $ dnsSuffix ) ; }

Gets the default service endpoint using the specified protocol and account
name.

@param string $scheme      The scheme of the service end point.
@param string $accountName The account name of the service.
@param string $dnsPrefix   The service DNS prefix.
@param string $dnsSuffix   The service DNS suffix.
@param bool   $isSecondary If generating secondary endpoint.

@return string

Gets the default service endpoint using the specified protocol and account name .


private static function createStorageServiceSettings(
        array $settings,
        $blobEndpointUri = null,
        $queueEndpointUri = null,
        $tableEndpointUri = null,
        $fileEndpointUri = null,
        $blobSecondaryEndpointUri = null,
        $queueSecondaryEndpointUri = null,
        $tableSecondaryEndpointUri = null,
        $fileSecondaryEndpointUri = null
    ) {
        $blobEndpointUri  = Utilities::tryGetValueInsensitive(
            Resources::BLOB_ENDPOINT_NAME,
            $settings,
            $blobEndpointUri
        );
        $queueEndpointUri = Utilities::tryGetValueInsensitive(
            Resources::QUEUE_ENDPOINT_NAME,
            $settings,
            $queueEndpointUri
        );
        $tableEndpointUri = Utilities::tryGetValueInsensitive(
            Resources::TABLE_ENDPOINT_NAME,
            $settings,
            $tableEndpointUri
        );
        $fileEndpointUri = Utilities::tryGetValueInsensitive(
            Resources::FILE_ENDPOINT_NAME,
            $settings,
            $fileEndpointUri
        );
        $accountName      = Utilities::tryGetValueInsensitive(
            Resources::ACCOUNT_NAME_NAME,
            $settings
        );
        $accountKey       = Utilities::tryGetValueInsensitive(
            Resources::ACCOUNT_KEY_NAME,
            $settings
        );
        $sasToken         = Utilities::tryGetValueInsensitive(
            Resources::SAS_TOKEN_NAME,
            $settings
        );

        return new StorageServiceSettings(
            $accountName,
            $accountKey,
            $blobEndpointUri,
            $queueEndpointUri,
            $tableEndpointUri,
            $fileEndpointUri,
            $blobSecondaryEndpointUri,
            $queueSecondaryEndpointUri,
            $tableSecondaryEndpointUri,
            $fileSecondaryEndpointUri,
            $sasToken
        );
    }

private static function createStorageServiceSettings ( array $ settings , $ blobEndpointUri = null , $ queueEndpointUri = null , $ tableEndpointUri = null , $ fileEndpointUri = null , $ blobSecondaryEndpointUri = null , $ queueSecondaryEndpointUri = null , $ tableSecondaryEndpointUri = null , $ fileSecondaryEndpointUri = null ) { $ blobEndpointUri = Utilities :: tryGetValueInsensitive ( Resources :: BLOB_ENDPOINT_NAME , $ settings , $ blobEndpointUri ) ; $ queueEndpointUri = Utilities :: tryGetValueInsensitive ( Resources :: QUEUE_ENDPOINT_NAME , $ settings , $ queueEndpointUri ) ; $ tableEndpointUri = Utilities :: tryGetValueInsensitive ( Resources :: TABLE_ENDPOINT_NAME , $ settings , $ tableEndpointUri ) ; $ fileEndpointUri = Utilities :: tryGetValueInsensitive ( Resources :: FILE_ENDPOINT_NAME , $ settings , $ fileEndpointUri ) ; $ accountName = Utilities :: tryGetValueInsensitive ( Resources :: ACCOUNT_NAME_NAME , $ settings ) ; $ accountKey = Utilities :: tryGetValueInsensitive ( Resources :: ACCOUNT_KEY_NAME , $ settings ) ; $ sasToken = Utilities :: tryGetValueInsensitive ( Resources :: SAS_TOKEN_NAME , $ settings ) ; return new StorageServiceSettings ( $ accountName , $ accountKey , $ blobEndpointUri , $ queueEndpointUri , $ tableEndpointUri , $ fileEndpointUri , $ blobSecondaryEndpointUri , $ queueSecondaryEndpointUri , $ tableSecondaryEndpointUri , $ fileSecondaryEndpointUri , $ sasToken ) ; }

Creates StorageServiceSettings object given endpoints uri.

@param array  $settings                  The service settings.
@param string $blobEndpointUri           The blob endpoint uri.
@param string $queueEndpointUri          The queue endpoint uri.
@param string $tableEndpointUri          The table endpoint uri.
@param string $fileEndpointUri           The file endpoint uri.
@param string $blobSecondaryEndpointUri  The blob secondary endpoint uri.
@param string $queueSecondaryEndpointUri The queue secondary endpoint uri.
@param string $tableSecondaryEndpointUri The table secondary endpoint uri.
@param string $fileSecondaryEndpointUri  The file secondary endpoint uri.

@return StorageServiceSettings

Creates StorageServiceSettings object given endpoints uri .


public static function createFromConnectionString($connectionString)
    {
        $tokenizedSettings = self::parseAndValidateKeys($connectionString);

        // Devstore case
        $matchedSpecs = self::matchedSpecification(
            $tokenizedSettings,
            self::allRequired(self::$useDevelopmentStorageSetting),
            self::optional(self::$developmentStorageProxyUriSetting)
        );
        if ($matchedSpecs) {
            $proxyUri = Utilities::tryGetValueInsensitive(
                Resources::DEVELOPMENT_STORAGE_PROXY_URI_NAME,
                $tokenizedSettings
            );

            return self::getDevelopmentStorageAccount($proxyUri);
        }

        // Automatic case
        $matchedSpecs = self::matchedSpecification(
            $tokenizedSettings,
            self::allRequired(
                self::$defaultEndpointsProtocolSetting,
                self::$accountNameSetting,
                self::$accountKeySetting
            ),
            self::optional(
                self::$blobEndpointSetting,
                self::$queueEndpointSetting,
                self::$tableEndpointSetting,
                self::$fileEndpointSetting,
                self::$endpointSuffixSetting
            )
        );
        if ($matchedSpecs) {
            $scheme         = Utilities::tryGetValueInsensitive(
                Resources::DEFAULT_ENDPOINTS_PROTOCOL_NAME,
                $tokenizedSettings
            );
            $accountName    = Utilities::tryGetValueInsensitive(
                Resources::ACCOUNT_NAME_NAME,
                $tokenizedSettings
            );
            $endpointSuffix = Utilities::tryGetValueInsensitive(
                Resources::ENDPOINT_SUFFIX_NAME,
                $tokenizedSettings
            );
            return self::createStorageServiceSettings(
                $tokenizedSettings,
                self::getServiceEndpoint(
                    $scheme,
                    $accountName,
                    Resources::BLOB_DNS_PREFIX,
                    $endpointSuffix
                ),
                self::getServiceEndpoint(
                    $scheme,
                    $accountName,
                    Resources::QUEUE_DNS_PREFIX,
                    $endpointSuffix
                ),
                self::getServiceEndpoint(
                    $scheme,
                    $accountName,
                    Resources::TABLE_DNS_PREFIX,
                    $endpointSuffix
                ),
                self::getServiceEndpoint(
                    $scheme,
                    $accountName,
                    Resources::FILE_DNS_PREFIX,
                    $endpointSuffix
                ),
                self::getServiceEndpoint(
                    $scheme,
                    $accountName,
                    Resources::BLOB_DNS_PREFIX,
                    $endpointSuffix,
                    true
                ),
                self::getServiceEndpoint(
                    $scheme,
                    $accountName,
                    Resources::QUEUE_DNS_PREFIX,
                    $endpointSuffix,
                    true
                ),
                self::getServiceEndpoint(
                    $scheme,
                    $accountName,
                    Resources::TABLE_DNS_PREFIX,
                    $endpointSuffix,
                    true
                ),
                self::getServiceEndpoint(
                    $scheme,
                    $accountName,
                    Resources::FILE_DNS_PREFIX,
                    $endpointSuffix,
                    true
                )
            );
        }

        // Explicit case for AccountName/AccountKey combination
        $matchedSpecs = self::matchedSpecification(
            $tokenizedSettings,
            self::atLeastOne(
                self::$blobEndpointSetting,
                self::$queueEndpointSetting,
                self::$tableEndpointSetting,
                self::$fileEndpointSetting
            ),
            self::allRequired(
                self::$accountNameSetting,
                self::$accountKeySetting
            )
        );
        if ($matchedSpecs) {
            return self::createStorageServiceSettings($tokenizedSettings);
        }

        // Explicit case for SAS token
        $matchedSpecs = self::matchedSpecification(
            $tokenizedSettings,
            self::atLeastOne(
                self::$blobEndpointSetting,
                self::$queueEndpointSetting,
                self::$tableEndpointSetting,
                self::$fileEndpointSetting
            ),
            self::allRequired(
                self::$sasTokenSetting
            )
        );
        if ($matchedSpecs) {
            return self::createStorageServiceSettings($tokenizedSettings);
        }

        self::noMatch($connectionString);
    }

Creates a StorageServiceSettings object from the given connection string.

@param string $connectionString The storage settings connection string.

@return StorageServiceSettings

Creates a StorageServiceSettings object from the given connection string .


public static function createFromConnectionStringForTokenCredential($connectionString)
    {
        // Explicit case for AAD token, Connection string could only have account
        // name.
        $tokenizedSettings = self::parseAndValidateKeys($connectionString);

        $scheme         = Utilities::tryGetValueInsensitive(
            Resources::DEFAULT_ENDPOINTS_PROTOCOL_NAME,
            $tokenizedSettings
        );
        $accountName    = Utilities::tryGetValueInsensitive(
            Resources::ACCOUNT_NAME_NAME,
            $tokenizedSettings
        );
        $endpointSuffix = Utilities::tryGetValueInsensitive(
            Resources::ENDPOINT_SUFFIX_NAME,
            $tokenizedSettings
        );
        return self::createStorageServiceSettings(
            $tokenizedSettings,
            self::getServiceEndpoint(
                $scheme,
                $accountName,
                Resources::BLOB_DNS_PREFIX,
                $endpointSuffix
            ),
            self::getServiceEndpoint(
                $scheme,
                $accountName,
                Resources::QUEUE_DNS_PREFIX,
                $endpointSuffix
            ),
            self::getServiceEndpoint(
                $scheme,
                $accountName,
                Resources::TABLE_DNS_PREFIX,
                $endpointSuffix
            ),
            self::getServiceEndpoint(
                $scheme,
                $accountName,
                Resources::FILE_DNS_PREFIX,
                $endpointSuffix
            ),
            self::getServiceEndpoint(
                $scheme,
                $accountName,
                Resources::BLOB_DNS_PREFIX,
                $endpointSuffix,
                true
            ),
            self::getServiceEndpoint(
                $scheme,
                $accountName,
                Resources::QUEUE_DNS_PREFIX,
                $endpointSuffix,
                true
            ),
            self::getServiceEndpoint(
                $scheme,
                $accountName,
                Resources::TABLE_DNS_PREFIX,
                $endpointSuffix,
                true
            ),
            self::getServiceEndpoint(
                $scheme,
                $accountName,
                Resources::FILE_DNS_PREFIX,
                $endpointSuffix,
                true
            )
        );
    }

Creates a StorageServiceSettings object from the given connection string.
Note this is only for AAD connection string, it should at least contain
the account name.

@param string $connectionString The storage settings connection string.

@return StorageServiceSettings

Creates a StorageServiceSettings object from the given connection string . Note this is only for AAD connection string it should at least contain the account name .


public function encodeMimeMultipart(array $bodyPartContents)
    {
        $count         = count($bodyPartContents);
        $mimeType      = Resources::MULTIPART_MIXED_TYPE;
        $batchGuid     = Utilities::getGuid();
        $batchId       = sprintf('batch_%s', $batchGuid);
        $contentType1  = array('content_type' => "$mimeType");
        $changeSetGuid = Utilities::getGuid();
        $changeSetId   = sprintf('changeset_%s', $changeSetGuid);
        $contentType2  = array('content_type' => "$mimeType; boundary=$changeSetId");
        $options       = array(
            'encoding'     => 'binary',
            'content_type' => Resources::HTTP_TYPE
        );

        $eof = "\r\n";

        $result            = array();
        $result['body']    = Resources::EMPTY_STRING;
        $result['headers'] = array();

        $batchBody         =& $result['body'];
        $batchHeaders      =& $result['headers'];

        $batchHeaders['Content-Type'] = $mimeType . "; $eof boundary=\"$batchId\"";

        $batchBody .= "--" . $batchId . $eof;
        $batchBody .= "Content-Type: $mimeType; boundary=\"$changeSetId\"" . $eof;

        $batchBody .= $eof;
        for ($i = 0; $i < count($bodyPartContents); $i++) {
            $batchBody .= "--" . $changeSetId . $eof;

            $batchBody .= "Content-Transfer-Encoding: binary" . $eof;
            $batchBody .= "Content-Type: " . Resources::HTTP_TYPE . $eof;

            $batchBody .= $eof . $bodyPartContents[$i] . $eof;
        }
        $batchBody .= "--" . $changeSetId . "--" . $eof;
        $batchBody .= $eof;
        $batchBody .= "--" . $batchId . "--" . $eof;

        return $result;
    }

Given array of MIME parts in raw string, this function converts them into MIME
representation.

@param array $bodyPartContents The MIME body parts.

@return array Returns array with two elements 'headers' and 'body' which
represents the MIME message.

Given array of MIME parts in raw string this function converts them into MIME representation .


public function decodeMimeMultipart($mimeBody)
    {
        // Find boundary
        $boundaryRegex = '~boundary=(changesetresponse_.*)~';
        preg_match($boundaryRegex, $mimeBody, $matches);

        $boundary = trim($matches[1]);

        // Split the requests
        $requests = explode('--' . $boundary, $mimeBody);

        // Get the body of each request
        $result = array();

        // The first and last element are not request
        for ($i = 1; $i < count($requests) - 1; $i++) {
            // Split the request header and body
            preg_match("/^.*?\r?\n\r?\n(.*)/s", $requests[$i], $matches);
            $result[] = $matches[1];
        }

        return $result;
    }

Parses given mime HTTP response body into array. Each array element
represents a change set result.

@param string $mimeBody The raw MIME body result.

@return array

Parses given mime HTTP response body into array . Each array element represents a change set result .


public static function create(array $parsedResponse, $location = '')
    {
        $result               = new ListSharesResult();
        $serviceEndpoint      = Utilities::tryGetKeysChainValue(
            $parsedResponse,
            Resources::XTAG_ATTRIBUTES,
            Resources::XTAG_SERVICE_ENDPOINT
        );
        $result->setAccountName(Utilities::tryParseAccountNameFromUrl(
            $serviceEndpoint
        ));
        $result->setPrefix(Utilities::tryGetValue(
            $parsedResponse,
            Resources::QP_PREFIX
        ));
        $result->setMarker(Utilities::tryGetValue(
            $parsedResponse,
            Resources::QP_MARKER
        ));

        $nextMarker = Utilities::tryGetValue(
            $parsedResponse,
            Resources::QP_NEXT_MARKER
        );

        if ($nextMarker != null) {
            $result->setContinuationToken(
                new MarkerContinuationToken(
                    $nextMarker,
                    $location
                )
            );
        }

        $result->setMaxResults(Utilities::tryGetValue(
            $parsedResponse,
            Resources::QP_MAX_RESULTS
        ));
        $shares = array();
        $shareArrays = array();

        if (!empty($parsedResponse[Resources::QP_SHARES])) {
            $array = $parsedResponse[Resources::QP_SHARES][Resources::QP_SHARE];
            $shareArrays    = Utilities::getArray($array);
        }

        foreach ($shareArrays as $shareArray) {
            $shares[] = Share::create($shareArray);
        }

        $result->setShares($shares);
        return $result;
    }

public static function create ( array $ parsedResponse , $ location = '' ) { $ result = new ListSharesResult ( ) ; $ serviceEndpoint = Utilities :: tryGetKeysChainValue ( $ parsedResponse , Resources :: XTAG_ATTRIBUTES , Resources :: XTAG_SERVICE_ENDPOINT ) ; $ result -> setAccountName ( Utilities :: tryParseAccountNameFromUrl ( $ serviceEndpoint ) ) ; $ result -> setPrefix ( Utilities :: tryGetValue ( $ parsedResponse , Resources :: QP_PREFIX ) ) ; $ result -> setMarker ( Utilities :: tryGetValue ( $ parsedResponse , Resources :: QP_MARKER ) ) ; $ nextMarker = Utilities :: tryGetValue ( $ parsedResponse , Resources :: QP_NEXT_MARKER ) ; if ( $ nextMarker != null ) { $ result -> setContinuationToken ( new MarkerContinuationToken ( $ nextMarker , $ location ) ) ; } $ result -> setMaxResults ( Utilities :: tryGetValue ( $ parsedResponse , Resources :: QP_MAX_RESULTS ) ) ; $ shares = array ( ) ; $ shareArrays = array ( ) ; if ( ! empty ( $ parsedResponse [ Resources :: QP_SHARES ] ) ) { $ array = $ parsedResponse [ Resources :: QP_SHARES ] [ Resources :: QP_SHARE ] ; $ shareArrays = Utilities :: getArray ( $ array ) ; } foreach ( $ shareArrays as $ shareArray ) { $ shares [ ] = Share :: create ( $ shareArray ) ; } $ result -> setShares ( $ shares ) ; return $ result ; }

Creates ListSharesResult object from parsed XML response.

@param array  $parsedResponse XML response parsed into array.
@param string $location       Contains the location for the previous
request.

@internal

@return ListSharesResult

Creates ListSharesResult object from parsed XML response .


protected function setShares(array $shares)
    {
        $this->shares = array();
        foreach ($shares as $share) {
            $this->shares[] = clone $share;
        }
    }

protected function setShares ( array $ shares ) { $ this -> shares = array ( ) ; foreach ( $ shares as $ share ) { $ this -> shares [ ] = clone $ share ; } }

Sets shares.

@param array $shares list of shares.

@return void


private function retry(
        RequestInterface $request,
        array $options,
        ResponseInterface $response = null
    ) {
        $options['delay'] = call_user_func(
            $this->intervalCalculator,
            ++$options['retries']
        );

        //Change the request URI according to the location mode.
        if (array_key_exists(Resources::ROS_LOCATION_MODE, $options)) {
            $locationMode = $options[Resources::ROS_LOCATION_MODE];
            //If have RA-GRS enabled for the request, switch between
            //primary and secondary.
            if ($locationMode == LocationMode::PRIMARY_THEN_SECONDARY ||
                $locationMode == LocationMode::SECONDARY_THEN_PRIMARY) {
                $primaryUri = $options[Resources::ROS_PRIMARY_URI];
                $secondaryUri = $options[Resources::ROS_SECONDARY_URI];

                $target = $request->getRequestTarget();
                if (Utilities::startsWith($target, '/')) {
                    $target = substr($target, 1);
                    $primaryUri = new Uri($primaryUri . $target);
                    $secondaryUri = new Uri($secondaryUri . $target);
                }

                //substitute the uri.
                if ((string)$request->getUri() == (string)$primaryUri) {
                    $request = $request->withUri($secondaryUri);
                } elseif ((string)$request->getUri() == (string)$secondaryUri) {
                    $request = $request->withUri($primaryUri);
                }
            }
        }
        $handler = $options[Resources::ROS_HANDLER];

        return \call_user_func($handler, $request, $options);
    }

This function does the real retry job.

@param  RequestInterface  $request  the request sent.
@param  array             $options  the options that the request sent with.
@param  ResponseInterface $response the response of the request

@return callable


public static function applyAnd(Filter $left, Filter $right)
    {
        $filter = new BinaryFilter($left, 'and', $right);
        return $filter;
    }

public static function applyAnd ( Filter $ left , Filter $ right ) { $ filter = new BinaryFilter ( $ left , 'and' , $ right ) ; return $ filter ; }

Apply and operation between two filters

@param Filter $left  The left filter
@param Filter $right The right filter

@return \MicrosoftAzure\Storage\Table\Models\Filters\BinaryFilter


public static function applyOr(Filter $left, Filter $right)
    {
        $filter = new BinaryFilter($left, 'or', $right);
        return $filter;
    }

public static function applyOr ( Filter $ left , Filter $ right ) { $ filter = new BinaryFilter ( $ left , 'or' , $ right ) ; return $ filter ; }

Apply or operation on the passed filers

@param Filter $left  The left operand
@param Filter $right The right operand

@return BinaryFilter


public static function applyEq(Filter $left, Filter $right)
    {
        $filter = new BinaryFilter($left, 'eq', $right);
        return $filter;
    }

public static function applyEq ( Filter $ left , Filter $ right ) { $ filter = new BinaryFilter ( $ left , 'eq' , $ right ) ; return $ filter ; }

Apply eq operation on the passed filers

@param Filter $left  The left operand
@param Filter $right The right operand

@return BinaryFilter


public static function applyNe(Filter $left, Filter $right)
    {
        $filter = new BinaryFilter($left, 'ne', $right);
        return $filter;
    }

public static function applyNe ( Filter $ left , Filter $ right ) { $ filter = new BinaryFilter ( $ left , 'ne' , $ right ) ; return $ filter ; }

Apply ne operation on the passed filers

@param Filter $left  The left operand
@param Filter $right The right operand

@return BinaryFilter


public static function applyGe(Filter $left, Filter $right)
    {
        $filter = new BinaryFilter($left, 'ge', $right);
        return $filter;
    }

public static function applyGe ( Filter $ left , Filter $ right ) { $ filter = new BinaryFilter ( $ left , 'ge' , $ right ) ; return $ filter ; }

Apply ge operation on the passed filers

@param Filter $left  The left operand
@param Filter $right The right operand

@return BinaryFilter


public static function applyGt(Filter $left, Filter $right)
    {
        $filter = new BinaryFilter($left, 'gt', $right);
        return $filter;
    }

public static function applyGt ( Filter $ left , Filter $ right ) { $ filter = new BinaryFilter ( $ left , 'gt' , $ right ) ; return $ filter ; }

Apply gt operation on the passed filers

@param Filter $left  The left operand
@param Filter $right The right operand

@return BinaryFilter


public static function applyLt(Filter $left, Filter $right)
    {
        $filter = new BinaryFilter($left, 'lt', $right);
        return $filter;
    }

public static function applyLt ( Filter $ left , Filter $ right ) { $ filter = new BinaryFilter ( $ left , 'lt' , $ right ) ; return $ filter ; }

Apply lt operation on the passed filers

@param Filter $left  The left operand
@param Filter $right The right operand

@return BinaryFilter


public static function applyLe(Filter $left, Filter $right)
    {
        $filter = new BinaryFilter($left, 'le', $right);
        return $filter;
    }

public static function applyLe ( Filter $ left , Filter $ right ) { $ filter = new BinaryFilter ( $ left , 'le' , $ right ) ; return $ filter ; }

Apply le operation on the passed filers

@param Filter $left  The left operand
@param Filter $right The right operand

@return BinaryFilter


public function setLocation($location)
    {
        Validate::canCastAsString($location, 'location');
        Validate::isTrue(
            $location == LocationMode::PRIMARY_ONLY ||
            $location == LocationMode::SECONDARY_ONLY ||
            $location == '',
            sprintf(
                Resources::INVALID_VALUE_MSG,
                'location',
                LocationMode::PRIMARY_ONLY . ' or ' . LocationMode::SECONDARY_ONLY
            )
        );

        $this->location = $location;
    }

public
function
setLocation
(
$
location
)
{
Validate
::
canCastAsString
(
$
location
,
'location'
)
;
Validate
::
isTrue
(
$
location
==
LocationMode
::
PRIMARY_ONLY
||
$
location
==
LocationMode
::
SECONDARY_ONLY
||
$
location
==
''
,
sprintf
(
Resources
::
INVALID_VALUE_MSG
,
'location'
,
LocationMode
::
PRIMARY_ONLY
.
' or '
.
LocationMode
::
SECONDARY_ONLY
)
)
;
$
this
->
location
=
$
location
;
}

Setter for location

@param string $location the location to be set.


public function unserialize($serialized)
    {
        Validate::canCastAsString($serialized, 'serialized');

        $json = json_decode($serialized);
        if ($json && !is_array($json)) {
            return get_object_vars($json);
        } else {
            return $json;
        }
    }

public function unserialize ( $ serialized ) { Validate :: canCastAsString ( $ serialized , 'serialized' ) ; $ json = json_decode ( $ serialized ) ; if ( $ json && ! is_array ( $ json ) ) { return get_object_vars ( $ json ) ; } else { return $ json ; } }

Unserializes given serialized string to array.

@param string $serialized The serialized object in string representation.

@return array

Unserializes given serialized string to array .


public static function create($parsedResponse)
    {
        $result        = new PeekMessagesResult();
        $queueMessages = array();

        if (!empty($parsedResponse)) {
            $rawMessages = Utilities::getArray(
                $parsedResponse[Resources::QP_QUEUE_MESSAGE]
            );
            foreach ($rawMessages as $value) {
                $message = QueueMessage::createFromPeekMessages($value);

                $queueMessages[] = $message;
            }
        }
        $result->setQueueMessages($queueMessages);

        return $result;
    }

public static function create ( $ parsedResponse ) { $ result = new PeekMessagesResult ( ) ; $ queueMessages = array ( ) ; if ( ! empty ( $ parsedResponse ) ) { $ rawMessages = Utilities :: getArray ( $ parsedResponse [ Resources :: QP_QUEUE_MESSAGE ] ) ; foreach ( $ rawMessages as $ value ) { $ message = QueueMessage :: createFromPeekMessages ( $ value ) ; $ queueMessages [ ] = $ message ; } } $ result -> setQueueMessages ( $ queueMessages ) ; return $ result ; }

Creates PeekMessagesResult object from parsed XML response.

@param array $parsedResponse XML response parsed into array.

@internal

@return PeekMessagesResult

Creates PeekMessagesResult object from parsed XML response .


public static function create($body, IODataReaderWriter $serializer)
    {
        $result = new GetEntityResult();
        $result->setEntity($serializer->parseEntity($body));

        return $result;
    }

public static function create ( $ body , IODataReaderWriter $ serializer ) { $ result = new GetEntityResult ( ) ; $ result -> setEntity ( $ serializer -> parseEntity ( $ body ) ) ; return $ result ; }

Create GetEntityResult object from HTTP response parts.

@param string             $body            The HTTP response body.
@param IODataReaderWriter $odataSerializer The OData reader and writer.

@internal

@return GetEntityResult

Create GetEntityResult object from HTTP response parts .


private function createOperationsContexts(array $operations)
    {
        $contexts = array();

        foreach ($operations as $operation) {
            $context = null;
            $type    = $operation->getType();

            switch ($type) {
                case BatchOperationType::INSERT_ENTITY_OPERATION:
                case BatchOperationType::UPDATE_ENTITY_OPERATION:
                case BatchOperationType::MERGE_ENTITY_OPERATION:
                case BatchOperationType::INSERT_REPLACE_ENTITY_OPERATION:
                case BatchOperationType::INSERT_MERGE_ENTITY_OPERATION:
                    $table   = $operation->getParameter(
                        BatchOperationParameterName::BP_TABLE
                    );
                    $entity  = $operation->getParameter(
                        BatchOperationParameterName::BP_ENTITY
                    );
                    $context = $this->getOperationContext($table, $entity, $type);
                    break;

                case BatchOperationType::DELETE_ENTITY_OPERATION:
                    $table        = $operation->getParameter(
                        BatchOperationParameterName::BP_TABLE
                    );
                    $partitionKey = $operation->getParameter(
                        BatchOperationParameterName::BP_PARTITION_KEY
                    );
                    $rowKey       = $operation->getParameter(
                        BatchOperationParameterName::BP_ROW_KEY
                    );
                    $etag         = $operation->getParameter(
                        BatchOperationParameterName::BP_ETAG
                    );
                    $options      = new DeleteEntityOptions();
                    $options->setETag($etag);
                    $context = $this->constructDeleteEntityContext(
                        $table,
                        $partitionKey,
                        $rowKey,
                        $options
                    );
                    break;

                default:
                    throw new \InvalidArgumentException();
            }

            $contexts[] = $context;
        }

        return $contexts;
    }

private function createOperationsContexts ( array $ operations ) { $ contexts = array ( ) ; foreach ( $ operations as $ operation ) { $ context = null ; $ type = $ operation -> getType ( ) ; switch ( $ type ) { case BatchOperationType :: INSERT_ENTITY_OPERATION : case BatchOperationType :: UPDATE_ENTITY_OPERATION : case BatchOperationType :: MERGE_ENTITY_OPERATION : case BatchOperationType :: INSERT_REPLACE_ENTITY_OPERATION : case BatchOperationType :: INSERT_MERGE_ENTITY_OPERATION : $ table = $ operation -> getParameter ( BatchOperationParameterName :: BP_TABLE ) ; $ entity = $ operation -> getParameter ( BatchOperationParameterName :: BP_ENTITY ) ; $ context = $ this -> getOperationContext ( $ table , $ entity , $ type ) ; break ; case BatchOperationType :: DELETE_ENTITY_OPERATION : $ table = $ operation -> getParameter ( BatchOperationParameterName :: BP_TABLE ) ; $ partitionKey = $ operation -> getParameter ( BatchOperationParameterName :: BP_PARTITION_KEY ) ; $ rowKey = $ operation -> getParameter ( BatchOperationParameterName :: BP_ROW_KEY ) ; $ etag = $ operation -> getParameter ( BatchOperationParameterName :: BP_ETAG ) ; $ options = new DeleteEntityOptions ( ) ; $ options -> setETag ( $ etag ) ; $ context = $ this -> constructDeleteEntityContext ( $ table , $ partitionKey , $ rowKey , $ options ) ; break ; default : throw new \ InvalidArgumentException ( ) ; } $ contexts [ ] = $ context ; } return $ contexts ; }

Creates contexts for batch operations.

@param array $operations The batch operations array.

@return array

@throws \InvalidArgumentException


private function getOperationContext($table, Entity $entity, $type)
    {
        switch ($type) {
            case BatchOperationType::INSERT_ENTITY_OPERATION:
                return $this->constructInsertEntityContext($table, $entity, null);

            case BatchOperationType::UPDATE_ENTITY_OPERATION:
                return $this->constructPutOrMergeEntityContext(
                    $table,
                    $entity,
                    Resources::HTTP_PUT,
                    true,
                    null
                );

            case BatchOperationType::MERGE_ENTITY_OPERATION:
                return $this->constructPutOrMergeEntityContext(
                    $table,
                    $entity,
                    Resources::HTTP_MERGE,
                    true,
                    null
                );

            case BatchOperationType::INSERT_REPLACE_ENTITY_OPERATION:
                return $this->constructPutOrMergeEntityContext(
                    $table,
                    $entity,
                    Resources::HTTP_PUT,
                    false,
                    null
                );

            case BatchOperationType::INSERT_MERGE_ENTITY_OPERATION:
                return $this->constructPutOrMergeEntityContext(
                    $table,
                    $entity,
                    Resources::HTTP_MERGE,
                    false,
                    null
                );

            default:
                throw new \InvalidArgumentException();
        }
    }

private function getOperationContext ( $ table , Entity $ entity , $ type ) { switch ( $ type ) { case BatchOperationType :: INSERT_ENTITY_OPERATION : return $ this -> constructInsertEntityContext ( $ table , $ entity , null ) ; case BatchOperationType :: UPDATE_ENTITY_OPERATION : return $ this -> constructPutOrMergeEntityContext ( $ table , $ entity , Resources :: HTTP_PUT , true , null ) ; case BatchOperationType :: MERGE_ENTITY_OPERATION : return $ this -> constructPutOrMergeEntityContext ( $ table , $ entity , Resources :: HTTP_MERGE , true , null ) ; case BatchOperationType :: INSERT_REPLACE_ENTITY_OPERATION : return $ this -> constructPutOrMergeEntityContext ( $ table , $ entity , Resources :: HTTP_PUT , false , null ) ; case BatchOperationType :: INSERT_MERGE_ENTITY_OPERATION : return $ this -> constructPutOrMergeEntityContext ( $ table , $ entity , Resources :: HTTP_MERGE , false , null ) ; default : throw new \ InvalidArgumentException ( ) ; } }

Creates operation context for the API.

@param string $table  The table name.
@param Entity $entity The entity object.
@param string $type   The API type.

@return \MicrosoftAzure\Storage\Common\Internal\Http\HttpCallContext

@throws \InvalidArgumentException


private function createBatchRequestBody(array $operations, array $contexts)
    {
        $mimeBodyParts = array();
        $contentId     = 1;
        $count         = count($operations);

        Validate::isTrue(
            count($operations) == count($contexts),
            Resources::INVALID_OC_COUNT_MSG
        );

        for ($i = 0; $i < $count; $i++) {
            $operation = $operations[$i];
            $context   = $contexts[$i];
            $type      = $operation->getType();

            switch ($type) {
                case BatchOperationType::INSERT_ENTITY_OPERATION:
                case BatchOperationType::UPDATE_ENTITY_OPERATION:
                case BatchOperationType::MERGE_ENTITY_OPERATION:
                case BatchOperationType::INSERT_REPLACE_ENTITY_OPERATION:
                case BatchOperationType::INSERT_MERGE_ENTITY_OPERATION:
                    $contentType  = $context->getHeader(Resources::CONTENT_TYPE);
                    $body         = $context->getBody();
                    $contentType .= ';type=entry';
                    $context->addOptionalHeader(Resources::CONTENT_TYPE, $contentType);
                    // Use mb_strlen instead of strlen to get the length of the string
                    // in bytes instead of the length in chars.
                    $context->addOptionalHeader(
                        Resources::CONTENT_LENGTH,
                        strlen($body)
                    );
                    break;

                case BatchOperationType::DELETE_ENTITY_OPERATION:
                    break;

                default:
                    throw new \InvalidArgumentException();
            }

            $context->addOptionalHeader(Resources::CONTENT_ID, $contentId);
            $mimeBodyPart    = $context->__toString();
            $mimeBodyParts[] = $mimeBodyPart;
            $contentId++;
        }

        return $this->mimeSerializer->encodeMimeMultipart($mimeBodyParts);
    }

Creates MIME part body for batch API.

@param array $operations The batch operations.
@param array $contexts   The contexts objects.

@return array

@throws \InvalidArgumentException


private function constructDeleteEntityContext(
        $table,
        $partitionKey,
        $rowKey,
        DeleteEntityOptions $options = null
    ) {
        Validate::canCastAsString($table, 'table');
        Validate::notNullOrEmpty($table, 'table');
        Validate::isTrue(!is_null($partitionKey), Resources::NULL_TABLE_KEY_MSG);
        Validate::isTrue(!is_null($rowKey), Resources::NULL_TABLE_KEY_MSG);

        $method      = Resources::HTTP_DELETE;
        $headers     = array();
        $queryParams = array();
        $statusCode  = Resources::STATUS_NO_CONTENT;
        $path        = $this->getEntityPath($table, $partitionKey, $rowKey);

        if (is_null($options)) {
            $options = new DeleteEntityOptions();
        }

        $etagObj = $options->getETag();
        $ETag    = !is_null($etagObj);
        $this->addOptionalHeader(
            $headers,
            Resources::IF_MATCH,
            $ETag ? $etagObj : Resources::ASTERISK
        );

        $this->addOptionalHeader(
            $headers,
            Resources::ACCEPT_HEADER,
            Resources::JSON_CONTENT_TYPE
        );

        $options->setLocationMode(LocationMode::PRIMARY_ONLY);

        $context = new HttpCallContext();
        $context->setHeaders($headers);
        $context->setMethod($method);
        $context->setPath($path);
        $context->setQueryParameters($queryParams);
        $context->addStatusCode($statusCode);
        $context->setBody('');
        $context->setServiceOptions($options);

        return $context;
    }

private function constructDeleteEntityContext ( $ table , $ partitionKey , $ rowKey , DeleteEntityOptions $ options = null ) { Validate :: canCastAsString ( $ table , 'table' ) ; Validate :: notNullOrEmpty ( $ table , 'table' ) ; Validate :: isTrue ( ! is_null ( $ partitionKey ) , Resources :: NULL_TABLE_KEY_MSG ) ; Validate :: isTrue ( ! is_null ( $ rowKey ) , Resources :: NULL_TABLE_KEY_MSG ) ; $ method = Resources :: HTTP_DELETE ; $ headers = array ( ) ; $ queryParams = array ( ) ; $ statusCode = Resources :: STATUS_NO_CONTENT ; $ path = $ this -> getEntityPath ( $ table , $ partitionKey , $ rowKey ) ; if ( is_null ( $ options ) ) { $ options = new DeleteEntityOptions ( ) ; } $ etagObj = $ options -> getETag ( ) ; $ ETag = ! is_null ( $ etagObj ) ; $ this -> addOptionalHeader ( $ headers , Resources :: IF_MATCH , $ ETag ? $ etagObj : Resources :: ASTERISK ) ; $ this -> addOptionalHeader ( $ headers , Resources :: ACCEPT_HEADER , Resources :: JSON_CONTENT_TYPE ) ; $ options -> setLocationMode ( LocationMode :: PRIMARY_ONLY ) ; $ context = new HttpCallContext ( ) ; $ context -> setHeaders ( $ headers ) ; $ context -> setMethod ( $ method ) ; $ context -> setPath ( $ path ) ; $ context -> setQueryParameters ( $ queryParams ) ; $ context -> addStatusCode ( $ statusCode ) ; $ context -> setBody ( '' ) ; $ context -> setServiceOptions ( $ options ) ; return $ context ; }

Constructs HTTP call context for deleteEntity API.

@param string              $table        The name of the table.
@param string              $partitionKey The entity partition key.
@param string              $rowKey       The entity row key.
@param DeleteEntityOptions $options      The optional parameters.

@return HttpCallContext

Constructs HTTP call context for deleteEntity API .


private function constructPutOrMergeEntityContext(
        $table,
        Entity $entity,
        $verb,
        $useETag,
        TableServiceOptions $options = null
    ) {
        Validate::canCastAsString($table, 'table');
        Validate::notNullOrEmpty($table, 'table');
        Validate::notNullOrEmpty($entity, 'entity');
        Validate::isTrue($entity->isValid($msg), $msg);

        $method       = $verb;
        $headers      = array();
        $queryParams  = array();
        $statusCode   = Resources::STATUS_NO_CONTENT;
        $partitionKey = $entity->getPartitionKey();
        $rowKey       = $entity->getRowKey();
        $path         = $this->getEntityPath($table, $partitionKey, $rowKey);
        $body         = $this->odataSerializer->getEntity($entity);

        if (is_null($options)) {
            $options = new TableServiceOptions();
        }

        if ($useETag) {
            $etag         = $entity->getETag();
            $ifMatchValue = is_null($etag) ? Resources::ASTERISK : $etag;

            $this->addOptionalHeader($headers, Resources::IF_MATCH, $ifMatchValue);
        }

        $this->addOptionalHeader(
            $headers,
            Resources::CONTENT_TYPE,
            Resources::JSON_CONTENT_TYPE
        );
        $this->addOptionalHeader(
            $headers,
            Resources::ACCEPT_HEADER,
            Resources::JSON_FULL_METADATA_CONTENT_TYPE
        );

        $options->setLocationMode(LocationMode::PRIMARY_ONLY);
        $context = new HttpCallContext();
        $context->setBody($body);
        $context->setHeaders($headers);
        $context->setMethod($method);
        $context->setPath($path);
        $context->setQueryParameters($queryParams);
        $context->addStatusCode($statusCode);
        $context->setServiceOptions($options);

        return $context;
    }

private function constructPutOrMergeEntityContext ( $ table , Entity $ entity , $ verb , $ useETag , TableServiceOptions $ options = null ) { Validate :: canCastAsString ( $ table , 'table' ) ; Validate :: notNullOrEmpty ( $ table , 'table' ) ; Validate :: notNullOrEmpty ( $ entity , 'entity' ) ; Validate :: isTrue ( $ entity -> isValid ( $ msg ) , $ msg ) ; $ method = $ verb ; $ headers = array ( ) ; $ queryParams = array ( ) ; $ statusCode = Resources :: STATUS_NO_CONTENT ; $ partitionKey = $ entity -> getPartitionKey ( ) ; $ rowKey = $ entity -> getRowKey ( ) ; $ path = $ this -> getEntityPath ( $ table , $ partitionKey , $ rowKey ) ; $ body = $ this -> odataSerializer -> getEntity ( $ entity ) ; if ( is_null ( $ options ) ) { $ options = new TableServiceOptions ( ) ; } if ( $ useETag ) { $ etag = $ entity -> getETag ( ) ; $ ifMatchValue = is_null ( $ etag ) ? Resources :: ASTERISK : $ etag ; $ this -> addOptionalHeader ( $ headers , Resources :: IF_MATCH , $ ifMatchValue ) ; } $ this -> addOptionalHeader ( $ headers , Resources :: CONTENT_TYPE , Resources :: JSON_CONTENT_TYPE ) ; $ this -> addOptionalHeader ( $ headers , Resources :: ACCEPT_HEADER , Resources :: JSON_FULL_METADATA_CONTENT_TYPE ) ; $ options -> setLocationMode ( LocationMode :: PRIMARY_ONLY ) ; $ context = new HttpCallContext ( ) ; $ context -> setBody ( $ body ) ; $ context -> setHeaders ( $ headers ) ; $ context -> setMethod ( $ method ) ; $ context -> setPath ( $ path ) ; $ context -> setQueryParameters ( $ queryParams ) ; $ context -> addStatusCode ( $ statusCode ) ; $ context -> setServiceOptions ( $ options ) ; return $ context ; }

Constructs HTTP call context for updateEntity, mergeEntity,
insertOrReplaceEntity and insertOrMergeEntity.

@param string              $table   The table name.
@param Entity              $entity  The entity instance to use.
@param string              $verb    The HTTP method.
@param boolean             $useETag The flag to include etag or not.
@param TableServiceOptions $options The optional parameters.

@return HttpCallContext

Constructs HTTP call context for updateEntity mergeEntity insertOrReplaceEntity and insertOrMergeEntity .


private function constructInsertEntityContext(
        $table,
        Entity $entity,
        TableServiceCreateOptions $options = null
    ) {
        Validate::canCastAsString($table, 'table');
        Validate::notNullOrEmpty($table, 'table');
        Validate::notNullOrEmpty($entity, 'entity');
        Validate::isTrue($entity->isValid($msg), $msg);

        $method      = Resources::HTTP_POST;
        $context     = new HttpCallContext();
        $headers     = array();
        $queryParams = array();
        $statusCode  = Resources::STATUS_CREATED;
        $path        = $table;
        $body        = $this->odataSerializer->getEntity($entity);

        if (is_null($options)) {
            $options = new TableServiceCreateOptions();
        }

        $this->addOptionalHeader(
            $headers,
            Resources::CONTENT_TYPE,
            Resources::JSON_CONTENT_TYPE
        );
        $this->addOptionalHeader(
            $headers,
            Resources::ACCEPT_HEADER,
            $options->getAccept()
        );
        $this->addOptionalHeader(
            $headers,
            Resources::PREFER,
            $options->getDoesReturnContent() ? Resources::RETURN_CONTENT : null
        );

        $options->setLocationMode(LocationMode::PRIMARY_ONLY);
        $context->setBody($body);
        $context->setHeaders($headers);
        $context->setMethod($method);
        $context->setPath($path);
        $context->setQueryParameters($queryParams);
        $context->addStatusCode($statusCode);
        $context->setServiceOptions($options);

        return $context;
    }

private function constructInsertEntityContext ( $ table , Entity $ entity , TableServiceCreateOptions $ options = null ) { Validate :: canCastAsString ( $ table , 'table' ) ; Validate :: notNullOrEmpty ( $ table , 'table' ) ; Validate :: notNullOrEmpty ( $ entity , 'entity' ) ; Validate :: isTrue ( $ entity -> isValid ( $ msg ) , $ msg ) ; $ method = Resources :: HTTP_POST ; $ context = new HttpCallContext ( ) ; $ headers = array ( ) ; $ queryParams = array ( ) ; $ statusCode = Resources :: STATUS_CREATED ; $ path = $ table ; $ body = $ this -> odataSerializer -> getEntity ( $ entity ) ; if ( is_null ( $ options ) ) { $ options = new TableServiceCreateOptions ( ) ; } $ this -> addOptionalHeader ( $ headers , Resources :: CONTENT_TYPE , Resources :: JSON_CONTENT_TYPE ) ; $ this -> addOptionalHeader ( $ headers , Resources :: ACCEPT_HEADER , $ options -> getAccept ( ) ) ; $ this -> addOptionalHeader ( $ headers , Resources :: PREFER , $ options -> getDoesReturnContent ( ) ? Resources :: RETURN_CONTENT : null ) ; $ options -> setLocationMode ( LocationMode :: PRIMARY_ONLY ) ; $ context -> setBody ( $ body ) ; $ context -> setHeaders ( $ headers ) ; $ context -> setMethod ( $ method ) ; $ context -> setPath ( $ path ) ; $ context -> setQueryParameters ( $ queryParams ) ; $ context -> addStatusCode ( $ statusCode ) ; $ context -> setServiceOptions ( $ options ) ; return $ context ; }

Constructs HTTP call context for insertEntity API.

@param string                    $table   The name of the table.
@param Entity                    $entity  The table entity.
@param TableServiceCreateOptions $options The optional parameters.

@return HttpCallContext

Constructs HTTP call context for insertEntity API .


private function getEntityPath($table, $partitionKey, $rowKey)
    {
        $encodedPK = $this->encodeODataUriValue($partitionKey);
        $encodedRK = $this->encodeODataUriValue($rowKey);

        return "$table(PartitionKey='$encodedPK',RowKey='$encodedRK')";
    }

Constructs URI path for entity.

@param string $table        The table name.
@param string $partitionKey The entity's partition key.
@param string $rowKey       The entity's row key.

@return string